List of usage examples for org.eclipse.jgit.api Git push
public PushCommand push()
From source file:org.spdx.tools.LicenseListPublisher.java
License:Apache License
/** * Publish a license list to the license data git repository * @param release license list release name (must be associatd with a tag in the license-list-xml repo) * @param gitUserName github username to be used - must have commit access to the license-xml-data repo * @param gitPassword github password//from w w w .j av a 2s . c o m * @throws LicensePublisherException * @throws LicenseGeneratorException */ private static void publishLicenseList(String release, String gitUserName, String gitPassword, boolean ignoreWarnings) throws LicensePublisherException, LicenseGeneratorException { CredentialsProvider githubCredentials = new UsernamePasswordCredentialsProvider(gitUserName, gitPassword); File licenseXmlDir = null; File licenseDataDir = null; Git licenseXmlGit = null; Git licenseDataGit = null; try { licenseXmlDir = Files.createTempDirectory("LicenseXML").toFile(); System.out.println("Cloning the license XML repository - this could take a while..."); licenseXmlGit = Git.cloneRepository().setCredentialsProvider(githubCredentials) .setDirectory(licenseXmlDir).setURI(LICENSE_XML_URI).call(); Ref releaseTag = licenseXmlGit.getRepository().getTags().get(release); if (releaseTag == null) { throw new LicensePublisherException( "Release " + release + " not found as a tag in the License List XML repository"); } licenseXmlGit.checkout().setName(releaseTag.getName()).call(); licenseDataDir = Files.createTempDirectory("LicenseData").toFile(); System.out.println("Cloning the license data repository - this could take a while..."); licenseDataGit = Git.cloneRepository().setCredentialsProvider(githubCredentials) .setDirectory(licenseDataDir).setURI(LICENSE_DATA_URI).call(); Ref dataReleaseTag = licenseDataGit.getRepository().getTags().get(release); boolean dataReleaseTagExists = false; if (dataReleaseTag != null) { dataReleaseTagExists = true; licenseDataGit.checkout().setName(releaseTag.getName()).call(); } cleanLicenseDataDir(licenseDataDir); String todayDate = new SimpleDateFormat("dd-MMM-yyyy").format(Calendar.getInstance().getTime()); List<String> warnings = LicenseRDFAGenerator.generateLicenseData( new File(licenseXmlDir.getPath() + File.separator + "src"), licenseDataDir, release, todayDate); if (warnings.size() > 0 && !ignoreWarnings) { throw new LicensePublisherException( "There are some skipped or invalid license input data. Publishing aborted. To ignore, add the --ignore option as the first parameter"); } licenseDataGit.add().addFilepattern(".").call(); licenseDataGit.commit().setAll(true) .setCommitter("SPDX License List Publisher", "spdx-tech@lists.spdx.org") .setMessage("License List Publisher for " + gitUserName + ". License list version " + release) .call(); if (!dataReleaseTagExists) { licenseDataGit.tag().setName(release).setMessage("SPDX License List release " + release).call(); } licenseDataGit.push().setCredentialsProvider(githubCredentials).setPushTags().call(); } catch (IOException e) { throw new LicensePublisherException("I/O Error publishing license list", e); } catch (InvalidRemoteException e) { throw new LicensePublisherException("Invalid remote error trying to access the git repositories", e); } catch (TransportException e) { throw new LicensePublisherException("Transport error trying to access the git repositories", e); } catch (GitAPIException e) { throw new LicensePublisherException("GIT API error trying to access the git repositories", e); } finally { if (licenseXmlGit != null) { licenseXmlGit.close(); } if (licenseDataGit != null) { licenseDataGit.close(); } if (licenseXmlDir != null) { deleteDir(licenseXmlDir); } if (licenseDataDir != null) { deleteDir(licenseDataDir); } } }
From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java
License:Apache License
/** * Tests a special use case where the remote repository has been updated with a forced * push conflicting with the local repo of the Config Server. The Config Server has to * reset hard on the new reference because a simple pull operation could result in a * conflicting local repository.// w w w.java 2 s . c o m */ @Test public void pullDirtyRepo() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); // Create a remote bare repository. Repository remote = ConfigServerTestUtils.prepareBareRemote(); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); // Pushes the raw branch to remote repository. git.push().call(); String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false) .run("--spring.cloud.config.server.git.uri=" + uri); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); // Fetches the repository for the first time. SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), commitToRevertBeforePull); // Resets to the original commit. git.reset().setMode(ResetType.HARD).setRef("master").call(); // Generate a conflicting commit who will be forced on the origin. Path applicationFilePath = Paths.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml"); Files.write(applicationFilePath, Arrays.asList("info:", " foo: bar", "raw: false"), StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); git.add().addFilepattern(".").call(); git.commit().setMessage("Conflicting commit.").call(); git.push().setForce(true).call(); String conflictingCommit = git.log().setMaxCount(1).call().iterator().next().getName(); // Reset to the raw branch. git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call(); // Triggers the repository refresh. locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), conflictingCommit); assertTrue("Local repository is not cleaned after retrieving resources.", git.status().call().isClean()); }
From source file:org.uberfire.java.nio.fs.jgit.util.JGitUtil.java
License:Apache License
public static void pushRepository(final Git git, final CredentialsProvider credentialsProvider, final String origin, boolean force) throws InvalidRemoteException { if (origin != null && !origin.isEmpty()) { try {/*from www. j a va 2 s. c o m*/ final StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "upstream", "url", origin); config.save(); } catch (final Exception ex) { throw new RuntimeException(ex); } final List<RefSpec> specs = new ArrayList<RefSpec>(); specs.add(new RefSpec("+refs/heads/*:refs/remotes/upstream/*")); specs.add(new RefSpec("+refs/tags/*:refs/tags/*")); specs.add(new RefSpec("+refs/notes/*:refs/notes/*")); try { git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(specs).setRemote(origin) .setForce(force).setPushAll().call(); } catch (final InvalidRemoteException e) { throw e; } catch (final Exception ex) { throw new RuntimeException(ex); } } }
From source file:org.wandora.application.tools.git.CommitPush.java
License:Open Source License
@Override public void execute(Wandora wandora, Context context) { try {// w w w . ja v a 2s . c om Git git = getGit(); if (git != null) { if (isNotEmpty(getGitRemoteUrl())) { if (commitPushUI == null) { commitPushUI = new CommitPushUI(); } commitPushUI.setPassword(getPassword()); commitPushUI.setUsername(getUsername()); commitPushUI.openInDialog(); if (commitPushUI.wasAccepted()) { setDefaultLogger(); setLogTitle("Git commit and push"); saveWandoraProject(); log("Removing deleted files from local repository."); org.eclipse.jgit.api.Status status = git.status().call(); Set<String> missing = status.getMissing(); if (missing != null && !missing.isEmpty()) { for (String missingFile : missing) { git.rm().addFilepattern(missingFile).call(); } } log("Adding new files to the local repository."); git.add().addFilepattern(".").call(); log("Committing changes to the local repository."); String commitMessage = commitPushUI.getMessage(); if (commitMessage == null || commitMessage.length() == 0) { commitMessage = getDefaultCommitMessage(); log("No commit message provided. Using default message."); } git.commit().setMessage(commitMessage).call(); String username = commitPushUI.getUsername(); String password = commitPushUI.getPassword(); setUsername(username); setPassword(password); PushCommand push = git.push(); if (isNotEmpty(username)) { log("Setting push credentials."); CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( username, password); push.setCredentialsProvider(credentialsProvider); } log("Pushing upstream."); push.call(); log("Ready."); } } else { log("Repository has no remote origin and can't be pushed. " + "Commit changes to the local repository using Commit to local... " + "To push changes to a remote repository initialize repository by cloning."); } } else { logAboutMissingGitRepository(); } } catch (GitAPIException gae) { log(gae.toString()); } catch (NoWorkTreeException nwte) { log(nwte.toString()); } catch (IOException ioe) { log(ioe.toString()); } catch (TopicMapException tme) { log(tme.toString()); } catch (Exception e) { log(e); } setState(WAIT); }
From source file:org.wandora.application.tools.git.Push.java
License:Open Source License
@Override public void execute(Wandora wandora, Context context) { try {/*w w w . j av a2 s . c o m*/ Git git = getGit(); if (git != null) { if (isNotEmpty(getGitRemoteUrl())) { if (pushUI == null) { pushUI = new PushUI(); } pushUI.setPassword(getPassword()); pushUI.setUsername(getUsername()); pushUI.setRemoteUrl(getGitRemoteUrl()); pushUI.openInDialog(); if (pushUI.wasAccepted()) { setDefaultLogger(); setLogTitle("Git push"); String username = pushUI.getUsername(); String password = pushUI.getPassword(); String remoteUrl = pushUI.getRemoteUrl(); setUsername(username); setPassword(password); // setGitRemoteUrl(remoteUrl); PushCommand push = git.push(); log("Pushing local changes to upstream."); if (username != null && username.length() > 0) { CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( username, password); push.setCredentialsProvider(credentialsProvider); } Iterable<PushResult> pushResults = push.call(); for (PushResult pushResult : pushResults) { String pushResultMessage = pushResult.getMessages(); if (isNotEmpty(pushResultMessage)) { log(pushResultMessage); } } log("Ready."); } } else { log("Repository has no remote origin and can't be pushed. " + "Initialize repository by cloning remote repository to set the remote origin."); } } else { logAboutMissingGitRepository(); } } catch (TransportException tre) { if (tre.toString().contains("origin: not found.")) { log("Git remote origin is not found. Check the remote url and remote git repository."); } } catch (GitAPIException gae) { log(gae.toString()); } catch (NoWorkTreeException nwte) { log(nwte.toString()); } catch (Exception e) { log(e); } setState(WAIT); }
From source file:org.webcat.core.git.GitUtilities.java
License:Open Source License
@SuppressWarnings("deprecation") public static RevCommit pushWorkingCopyImmediately(Repository workingCopy, String authorName, String emailAddress, String commitMessage) { try {/*from w w w . j a v a2 s . c o m*/ boolean amend = false; GitRepository gitRepo = new GitRepository(workingCopy); GitRef ref = gitRepo.refWithName(Constants.R_HEADS + Constants.MASTER); NSArray<GitCommit> commits = ref.commits(); if (commits != null && !commits.isEmpty()) { GitCommit commit = commits.objectAtIndex(0); if (commitMessage.equals(commit.shortMessage()) && commit.commitTime().timeIntervalSinceNow() > -3 * 60 * 60) { amend = true; } } Git git = new Git(workingCopy); git.add().addFilepattern(".").setUpdate(false).call(); RevCommit commit = git.commit().setAuthor(authorName, emailAddress) .setCommitter(authorName, emailAddress).setMessage(commitMessage).setAmend(amend).call(); RefSpec allHeadsSpec = new RefSpec().setForceUpdate(true).setSourceDestination( Constants.R_HEADS + Constants.MASTER, Constants.R_HEADS + Constants.MASTER); git.push().setRefSpecs(allHeadsSpec).call(); return commit; } catch (Exception e) { log.error("Error updating repository: ", e); } return null; }
From source file:org.wso2.carbon.appfactory.repository.mgt.git.JGitAgent.java
License:Apache License
/** * Push changes to remote repository//w w w. ja v a2 s. co m * * @param remoteRepoUrl remote repository url * @param pushBranch branch to push * @param repoFile repository directory where .git exists. If not exists will get cloned using {@code * remoteRepoUrl} * @return success * @throws RepositoryMgtException if error while branching */ @Override public boolean push(String remoteRepoUrl, String pushBranch, File repoFile) throws RepositoryMgtException { try { Git gitRepo = getGitRepository(remoteRepoUrl, repoFile); Iterable<PushResult> pushResults = gitRepo.push().setRemote(remoteRepoUrl) .setRefSpecs(new RefSpec("refs/heads/" + pushBranch)) .setCredentialsProvider(getCredentialsProvider()).call(); // we need to verify if git push was successful. Here we can check RemoteRefUpdate status is rejected or not. boolean pushed = true; for (PushResult pushResult : pushResults) { if (pushResult.getRemoteUpdates().size() > 0) { Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates(); if (refUpdates != null && refUpdates.size() > 0) { for (RemoteRefUpdate refUpdate : refUpdates) { if (refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_OTHER_REASON || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_NODELETE || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED) { pushed = false; log.warn("Failed to push artifacts on repo, So called pushFailed method" + remoteRepoUrl + " due to " + refUpdate.getStatus() + " Message " + refUpdate.getMessage() + " Application" + repoFile); break; } } } } } synchronized (remoteRepoUrl) { int currentPushTry = 1; boolean pushedInRetry = pushed; while (currentPushTry < MAX_RETRY_COUNT && !pushedInRetry) { Thread.sleep(10000 * currentPushTry); //Pause for 10*retrycount seconds pushedInRetry = pushFailed(remoteRepoUrl, pushBranch, repoFile, currentPushTry); currentPushTry++; } pushed = pushedInRetry; } return pushed; } catch (RepositoryMgtException e) { String msg = "Error while pushing : " + pushBranch + " due to " + e.getMessage() + " from RepositoryMgtException"; log.error(msg, e); throw new RepositoryMgtException(msg, e); } catch (GitAPIException e) { String msg = "Error while pushing : " + pushBranch + " due to " + e.getMessage() + " from GitAPIException"; log.error(msg, e); throw new RepositoryMgtException(msg, e); } catch (InterruptedException e) { String msg = "Thread is interupted due to " + e.getMessage(); log.error(msg, e); return false; } }
From source file:org.wso2.carbon.appfactory.repository.mgt.git.JGitAgent.java
License:Apache License
/** * Re-try the push with using this method. * * @param remoteRepoUrl remote repository url * @param pushBranch branch to push/*from w w w . jav a2 s. c o m*/ * @param repoFile repository directory where .git exists. If not exists will get cloned using {@code * remoteRepoUrl} * @param currentPushTry - Push try count * @return success * @throws RepositoryMgtException if error while branching * @throws GitAPIException if error while merging or pushing */ public boolean pushFailed(String remoteRepoUrl, String pushBranch, File repoFile, int currentPushTry) throws RepositoryMgtException, GitAPIException { log.warn("Re trying " + currentPushTry + " time, for " + repoFile); boolean pushed; log.warn("Lock obtained for remote repo URL: " + remoteRepoUrl); Git gitRepo = getGitRepository(remoteRepoUrl, repoFile); gitRepo.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call(); Iterable<PushResult> pushResults = gitRepo.push().setRemote(remoteRepoUrl) .setRefSpecs(new RefSpec("refs/heads/" + pushBranch)) .setCredentialsProvider(getCredentialsProvider()).call(); // we need to verify if git push was successful. Here we can check RemoteRefUpdate status is rejected or not. pushed = true; for (PushResult pushResult : pushResults) { if (pushResult.getRemoteUpdates().size() > 0) { Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates(); if (refUpdates != null && refUpdates.size() > 0) { for (RemoteRefUpdate refUpdate : refUpdates) { if (refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_OTHER_REASON || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_NODELETE || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD || refUpdate.getStatus() == RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED) { pushed = false; log.warn("Failed to push artifacts on repo:" + remoteRepoUrl + " due to " + refUpdate.getStatus() + " Message " + refUpdate.getMessage() + " Application" + repoFile); break; } } } } } return pushed; }
From source file:org.zanata.sync.plugin.git.service.impl.GitSyncService.java
License:Open Source License
@Override public void syncTranslationToRepo(String repoUrl, String branch, File baseDir) throws RepoSyncException { try {//from w ww.j ava2 s .co m Git git = Git.open(baseDir); StatusCommand statusCommand = git.status(); Status status = statusCommand.call(); Set<String> uncommittedChanges = status.getUncommittedChanges(); uncommittedChanges.addAll(status.getUntracked()); if (!uncommittedChanges.isEmpty()) { log.info("uncommitted files in git repo: {}", uncommittedChanges); AddCommand addCommand = git.add(); addCommand.addFilepattern("."); addCommand.call(); log.info("commit changed files"); CommitCommand commitCommand = git.commit(); commitCommand.setCommitter("Zanata Auto Repo Sync", "zanata-users@redhat.com"); commitCommand.setMessage("Zanata Auto Repo Sync (pushing translations)"); commitCommand.call(); log.info("push to remote repo"); PushCommand pushCommand = git.push(); UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider( getCredentials().getUsername(), getCredentials().getSecret()); pushCommand.setCredentialsProvider(user); pushCommand.call(); } else { log.info("nothing changed so nothing to do"); } } catch (IOException e) { throw new RepoSyncException("failed opening " + baseDir + " as git repo", e); } catch (GitAPIException e) { throw new RepoSyncException("Failed committing translations into the repo", e); } }
From source file:org.zend.sdkcli.internal.commands.GitPushApplicationCommand.java
License:Open Source License
@Override protected boolean doExecute() { Repository repo = null;/*from w w w. ja va2 s.com*/ try { File gitDir = getRepo(); if (!gitDir.exists()) { getLogger().error("Git repository is not available in provided location"); return false; } repo = FileRepositoryBuilder.create(getRepo()); } catch (IOException e) { getLogger().error(e); return false; } if (repo != null) { Git git = new Git(repo); String remote = doGetRemote(repo); if (remote == null) { getLogger().error("Invalid remote value: " + getRemote()); return false; } // perform operation only if it is clone of phpCloud repository String repoUrl = git.getRepository().getConfig().getString("remote", remote, "url"); AddCommand addCommand = git.add(); addCommand.setUpdate(false); // add all new files addCommand.addFilepattern("."); try { addCommand.call(); } catch (NoFilepatternException e) { // should not occur because '.' is used getLogger().error(e); return false; } catch (GitAPIException e) { getLogger().error(e); return false; } CommitCommand commitCommand = git.commit(); // automatically stage files that have been modified and deleted commitCommand.setAll(true); PersonIdent ident = getPersonalIdent(repoUrl); if (ident == null) { getLogger().error("Invalid author information provided: " + getAuthor()); return false; } commitCommand.setAuthor(ident); commitCommand.setInsertChangeId(true); commitCommand.setMessage(getMessage()); try { commitCommand.call(); } catch (Exception e) { getLogger().error(e); return false; } // at the end push all changes PushCommand pushCommand = git.push(); pushCommand.setPushAll(); pushCommand.setRemote(remote); pushCommand.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out))); try { URIish uri = new URIish(repoUrl); if (GITHUB_HOST.equals(uri.getHost()) && "git".equals(uri.getUser())) { if (!prepareSSHFactory()) { return false; } } else { CredentialsProvider credentials = getCredentials(repoUrl); if (credentials != null) { pushCommand.setCredentialsProvider(credentials); } } Iterable<PushResult> result = pushCommand.call(); for (PushResult pushResult : result) { pushResult.getAdvertisedRefs(); Collection<RemoteRefUpdate> updates = pushResult.getRemoteUpdates(); for (RemoteRefUpdate remoteRefUpdate : updates) { TrackingRefUpdate trackingRefUpdate = remoteRefUpdate.getTrackingRefUpdate(); getLogger().info(MessageFormat.format("Remote name: {0}, status: {1}", remoteRefUpdate.getRemoteName(), remoteRefUpdate.getStatus().toString())); getLogger().info(MessageFormat.format("Remote name: {0}, result: {1}", trackingRefUpdate.getRemoteName(), trackingRefUpdate.getResult().toString())); } } } catch (JGitInternalException e) { getLogger().error(e); return false; } catch (InvalidRemoteException e) { // should not occur because selected remote is available getLogger().error(e); return false; } catch (URISyntaxException e) { getLogger().error(e); return false; } catch (TransportException e) { getLogger().error(e); return false; } catch (GitAPIException e) { getLogger().error(e); return false; } } return true; }