Java Code Examples for org.eclipse.jgit.api.PushCommand#call()

The following examples show how to use org.eclipse.jgit.api.PushCommand#call() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConfigurationExporter.java    From opsgenie-configuration-backup with Apache License 2.0 6 votes vote down vote up
/**
 * This is main export method. This method export opsgenie configuration to local folder. If git
 * is enabled from BackupProperties parameters it will export those configurations to remote
 * git.
 */
void export() throws GitAPIException, InterruptedException, IOException {
    if (getBackupProperties().isGitEnabled()) {
        cloneGit(getBackupProperties());
    }
    init();
    logger.info("Export operation started!");
    for (final Exporter exporter : exporters) {
        exporter.export();
    }

    if (getBackupProperties().isGitEnabled()) {
        logger.info("Export to remote git operation started!");
        getGit().add().addFilepattern("OpsGenieBackups").call();
        getGit().commit().setAll(true).setAllowEmpty(true).setMessage("Opsgenie Backups").setCommitter("opsgenie", "[email protected]").call();
        PushCommand pc = getGit().push();
        pc.setTransportConfigCallback(getCallBack());
        pc.setForce(true).setPushAll();
        pc.call();
        logger.info("Export to remote git operation finished!");
    }
    logger.info("Export operation finished!");
}
 
Example 2
Source File: OldGitHubNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private void pushToRemoteSteam() {
  try {
    LOG.debug("Pushing latest changes to remote stream");
    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(
      new UsernamePasswordCredentialsProvider(
        zeppelinConfiguration.getZeppelinNotebookGitUsername(),
        zeppelinConfiguration.getZeppelinNotebookGitAccessToken()
      )
    );

    pushCommand.call();
  } catch (GitAPIException e) {
    LOG.error("Error when pushing latest changes to remote repository", e);
  }
}
 
Example 3
Source File: GitHubNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private void pushToRemoteSteam() {
  try {
    LOG.debug("Pushing latest changes to remote stream");
    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(
      new UsernamePasswordCredentialsProvider(
        zeppelinConfiguration.getZeppelinNotebookGitUsername(),
        zeppelinConfiguration.getZeppelinNotebookGitAccessToken()
      )
    );

    pushCommand.call();
  } catch (GitAPIException e) {
    LOG.error("Error when pushing latest changes to remote repository", e);
  }
}
 
Example 4
Source File: GitCatalogDao.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@Override
public void write(CatalogData data) {
    File localRepoFile = new File(localRepoPath);
    if (!localRepoFile.exists() || !localRepoFile.canWrite()) {
        throw new CatalogModificationException("Catalog is not writable: " + localRepoFile.getAbsolutePath());
    }

    try (FileWriter writer = new FileWriter(catalogFile)){
        String text = mapper.writeValueAsString(data);
        writer.write(text);
    } catch (IOException ioException) {
        throw new CatalogModificationException("Unable to write catalog file.", ioException);
    }

    try (Git git = Git.open(localRepoFile)) {
        git.add().addFilepattern(catalogPath).call();
        git.commit().setMessage("Catalog updated").call();
        updateRepo();
        PushCommand pushCommand = git.push();
        if (credentialsProvider != null) {
            pushCommand.setCredentialsProvider(credentialsProvider);
        }
        if (transportConfigCallback != null) {
            pushCommand.setTransportConfigCallback(transportConfigCallback);
        }
        pushCommand.call();
    } catch (GitAPIException | IOException ex) {
        throw new CatalogModificationException("Unable to modify catalog", ex);
    }
}
 
Example 5
Source File: LocalGitRepo.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
@Override
public void pushTags(Collection<AnnotatedTag> tags) throws GitAPIException {
    PushCommand pushCommand = git.push()
        .setCredentialsProvider(credentialsProvider);
    if (remoteUrl != null) {
        pushCommand.setRemote(remoteUrl);
    }

    for (AnnotatedTag tag : tags) {
        pushCommand.add(tag.saveAtHEAD(git));
    }

    pushCommand.call();
}
 
Example 6
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Pushes the local comments and reviews back to the origin.
 */
private void pushCommentsAndReviews() throws Exception {
  try (Git git = new Git(repo)) {
    RefSpec spec = new RefSpec(DEVTOOLS_PUSH_REFSPEC);
    PushCommand pushCommand = git.push();
    pushCommand.setRefSpecs(spec);
    pushCommand.call();
  }
}
 
Example 7
Source File: GitHubConnector.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
/**
 * Must be called after #{createGitRepository()}
 */
public void pushAllChangesToGit() throws IOException {
    if (localRepository == null) {
        throw new IOException("Git has not been created, call createGitRepositoryFirst");
    }
    try {
        UserService userService = new UserService();
        userService.getClient().setOAuth2Token(oAuthToken);
        User user = userService.getUser();
        String name = user.getLogin();
        String email = user.getEmail();
        if (email == null) {
            // This is the e-mail addressed used by GitHub on web commits where the users mail is private. See:
            // https://github.com/settings/emails
            email = name + "@users.noreply.github.com";
        }

        localRepository.add().addFilepattern(".").call();
        localRepository.commit()
                .setMessage("Initial commit")
                .setCommitter(name, email)
                .call();
        PushCommand pushCommand = localRepository.push();
        addAuth(pushCommand);
        pushCommand.call();
    } catch (GitAPIException e) {
        throw new IOException("Error pushing changes to GitHub", e);
    }
}
 
Example 8
Source File: PushJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPush(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	// /git/remote/{remote}/{branch}/file/{path}
	File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
	Repository db = null;
	JSONObject result = new JSONObject();
	try {
		db = FileRepositoryBuilder.create(gitDir);
		Git git = Git.wrap(db);

		PushCommand pushCommand = git.push();
		pushCommand.setProgressMonitor(gitMonitor);
		pushCommand.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		pushCommand.setCredentialsProvider(credentials);

		boolean pushToGerrit = branch.startsWith("for/");
		RefSpec spec = new RefSpec(srcRef + ':' + (pushToGerrit ? "refs/" : Constants.R_HEADS) + branch);
		pushCommand.setRemote(remote).setRefSpecs(spec);
		if (tags)
			pushCommand.setPushTags();
		pushCommand.setForce(force);
		Iterable<PushResult> resultIterable = pushCommand.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		PushResult pushResult = resultIterable.iterator().next();
		boolean error = false;
		JSONArray updates = new JSONArray();
		result.put(GitConstants.KEY_COMMIT_MESSAGE, pushResult.getMessages());
		result.put(GitConstants.KEY_UPDATES, updates);
		for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
			if (monitor.isCanceled()) {
				return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
			}
			final String rm = rru.getRemoteName();
			// check status only for branch given in the URL or tags
			if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS) || rm.startsWith(Constants.R_REFS + "for/")) {
				JSONObject object = new JSONObject();
				RemoteRefUpdate.Status status = rru.getStatus();
				if (status != RemoteRefUpdate.Status.UP_TO_DATE || !rm.startsWith(Constants.R_TAGS)) {
					object.put(GitConstants.KEY_COMMIT_MESSAGE, rru.getMessage());
					object.put(GitConstants.KEY_RESULT, status.name());
					TrackingRefUpdate refUpdate = rru.getTrackingRefUpdate();
					if (refUpdate != null) {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
					} else {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(rru.getSrcRef()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(rru.getRemoteName()));
					}
					updates.put(object);
				}
				if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
					error = true;
			}
			// TODO: return results for all updated branches once push is available for remote, see bug 352202
		}
		// needs to handle multiple
		result.put("Severity", error ? "Error" : "Ok");
	} catch (JSONException e) {
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
 
Example 9
Source File: JGitOperator.java    From verigreen with Apache License 2.0 4 votes vote down vote up
@Override
public boolean push(String sourceBranch, String destinationBranch) {
       
       PushCommand command = _git.push();
       boolean ret = true;
       RefSpec refSpec = new RefSpec().setSourceDestination(sourceBranch, destinationBranch);
       command.setRefSpecs(refSpec);
       try {
       	List<Ref> remoteBranches = _git.branchList().setListMode(ListMode.REMOTE).call();
           if(_cp != null)
               command.setCredentialsProvider(_cp);
           Iterable<PushResult> results = command.call();
           for (PushResult pushResult : results) {
           	Collection<RemoteRefUpdate> resultsCollection = pushResult.getRemoteUpdates();
           	Map<PushResult,RemoteRefUpdate> resultsMap = new HashMap<>();
           	for(RemoteRefUpdate remoteRefUpdate : resultsCollection)
           	{
           		resultsMap.put(pushResult, remoteRefUpdate);
           	}
           	
               RemoteRefUpdate remoteUpdate = pushResult.getRemoteUpdate(destinationBranch);
               if (remoteUpdate != null) {
                   org.eclipse.jgit.transport.RemoteRefUpdate.Status status =
                           remoteUpdate.getStatus();
                   ret =
                           status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK)
                                   || status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE);
               }
               
               if(remoteUpdate == null && !remoteBranches.toString().contains(destinationBranch))
               {	
            
               	
               	for(RemoteRefUpdate resultValue : resultsMap.values())
               	{
               		if(resultValue.toString().contains("REJECTED_OTHER_REASON"))
               		{
               			ret = false;
               		}
               	}
               }	
           }
       } catch (Throwable e) {
           throw new RuntimeException(String.format(
                   "Failed to push [%s] into [%s]",
                   sourceBranch,
                   destinationBranch), e);
       }
       
       return ret;
   }
 
Example 10
Source File: Push.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void execute(Wandora wandora, Context context) {
    
    try {
        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);
}
 
Example 11
Source File: CommitPush.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void execute(Wandora wandora, Context context) {

    try {
        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);
}