Java Code Examples for org.eclipse.jgit.api.Git#push()

The following examples show how to use org.eclipse.jgit.api.Git#push() . 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: 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 2
Source File: ForgeTestSupport.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected Build assertCodeChangeTriggersWorkingBuild(final String projectName, Build firstBuild) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }


    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent()).setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;


    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JobWithDetails job = assertJob(projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber()).describedAs("Waiting for latest build for job " + projectName + " to start").isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(forgeClient, projectName);
}
 
Example 3
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected Iterable<PushResult> doPush(Git git) throws Exception {
    PushCommand command = git.push();
    configureCommand(command, userDetails);
    return command.setRemote(getRemote()).call();
}
 
Example 4
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 5
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);
}