Example usage for org.eclipse.jgit.api Git push

List of usage examples for org.eclipse.jgit.api Git push

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git push.

Prototype

public PushCommand push() 

Source Link

Document

Return a command object to execute a Push command

Usage

From source file:org.eclipse.orion.server.tests.servlets.git.GitFetchTest.java

License:Open Source License

@Test
public void testFetchRemoteBranch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    // clone1: create
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    String projectId1 = project1.getString(ProtocolConstants.KEY_ID);
    IPath clonePath1 = new Path("file").append(project1.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    JSONObject clone1 = clone(clonePath1);
    String cloneContentLocation1 = clone1.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH);

    // get project1 metadata
    WebRequest request = getGetFilesRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);//from   www  .  j a v  a2 s . c o  m
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);
    String gitIndexUri1 = gitSection1.getString(GitConstants.KEY_INDEX);
    String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD);

    // clone1: branch 'a'
    Repository db1 = getRepositoryForContentLocation(cloneContentLocation1);
    Git git1 = new Git(db1);
    branch(branchesLocation1, "a");

    // clone1: push all
    // TODO: replace with REST API when bug 339115 is fixed
    git1.push().setPushAll().call();

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    IPath clonePath2 = new Path("file").append(project2.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    clone(clonePath2);
    // XXX: checked out 'a'

    // get project2 metadata
    request = getGetFilesRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection2);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);

    // clone1: switch to 'a'
    assertBranchExist(git1, "a");
    checkoutBranch(cloneLocation1, "a");

    // clone1: change
    request = getPutFileRequest(projectId1 + "/test.txt", "branch 'a' change");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri1);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming branch 'a' commit", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: push
    ServerStatus pushStatus = push(gitRemoteUri1, 2, 0, "a", Constants.HEAD, false);
    assertTrue(pushStatus.isOK());

    // clone1: switch to 'master'
    checkoutBranch(cloneLocation1, Constants.MASTER);

    // clone1: change
    request = getPutFileRequest(projectId1 + "/test.txt", "branch 'master' change");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri1);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming branch 'master' commit", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: push
    push(gitRemoteUri1, 2, 0, Constants.MASTER, Constants.HEAD, false);

    // clone2: get remote details
    // XXX: checked out 'a'
    JSONObject aDetails = getRemoteBranch(gitRemoteUri2, 2, 0, "a");
    String aOldRefId = aDetails.getString(ProtocolConstants.KEY_ID);
    String aBranchLocation = aDetails.getString(ProtocolConstants.KEY_LOCATION);
    JSONObject masterDetails = getRemoteBranch(gitRemoteUri2, 2, 1, Constants.MASTER);
    String masterOldRefId = masterDetails.getString(ProtocolConstants.KEY_ID);

    // clone2: fetch 'a'
    fetch(aBranchLocation);

    // clone2: check for new content on 'a'
    masterDetails = getRemoteBranch(gitRemoteUri2, 2, 0, "a");
    String newRefId = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertFalse(aOldRefId.equals(newRefId));

    // clone2: assert nothing new on 'master'
    masterDetails = getRemoteBranch(gitRemoteUri2, 2, 1, Constants.MASTER);
    newRefId = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertEquals(masterOldRefId, newRefId);

}

From source file:org.eclipse.orion.server.tests.servlets.git.GitPullTest.java

License:Open Source License

@Test
public void testPullRemote() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);

    // clone1: create
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath1 = getClonePath(workspaceId, project1);
    JSONObject clone1 = clone(clonePath1);
    String cloneContentLocation1 = clone1.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH);

    // get project1 metadata
    WebRequest request = getGetFilesRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);/*from   w ww  .  j  a  va 2 s.c o m*/
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);

    // clone1: branch 'a'
    Repository db1 = getRepositoryForContentLocation(cloneContentLocation1);
    Git git1 = new Git(db1);
    branch(branchesLocation1, "a");

    // clone1: push all
    // TODO: replace with REST API when bug 339115 is fixed
    git1.push().setPushAll().call();

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    IPath clonePath2 = getClonePath(workspaceId, project2);
    JSONObject clone2 = clone(clonePath2);
    String cloneLocation2 = clone2.getString(ProtocolConstants.KEY_LOCATION);

    // get project2 metadata
    request = getGetFilesRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection2);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);

    // clone1: switch to 'a'
    assertBranchExist(git1, "a");
    checkoutBranch(cloneLocation1, "a");

    // clone1: change, add, commit
    JSONObject testTxt1 = getChild(project1, "test.txt");
    modifyFile(testTxt1, "branch 'a' change");
    addFile(testTxt1);
    commitFile(testTxt1, "incoming branch 'a' commit", false);

    // clone1: push
    ServerStatus pushStatus = push(gitRemoteUri1, 2, 0, "a", Constants.HEAD, false);
    assertTrue(pushStatus.isOK());

    // clone1: switch to 'master'
    checkoutBranch(cloneLocation1, Constants.MASTER);

    // clone1: change
    testTxt1 = getChild(project1, "test.txt");
    modifyFile(testTxt1, "branch 'master' change");
    addFile(testTxt1);
    commitFile(testTxt1, "incoming branch 'master' commit", false);

    // clone1: push
    push(gitRemoteUri1, 2, 0, Constants.MASTER, Constants.HEAD, false);

    // clone2: get remote details
    JSONObject aDetails = getRemoteBranch(gitRemoteUri2, 2, 1, "a");
    String aOldRefId = aDetails.getString(ProtocolConstants.KEY_ID);
    JSONObject masterDetails = getRemoteBranch(gitRemoteUri2, 2, 0, Constants.MASTER);
    String masterOldRefId = masterDetails.getString(ProtocolConstants.KEY_ID);

    // clone2: pull
    pull(cloneLocation2);

    // clone2: check for new content on 'a'
    masterDetails = getRemoteBranch(gitRemoteUri2, 2, 1, "a");
    String newRefId = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertFalse(aOldRefId.equals(newRefId));

    // clone2: assert nothing new on 'master'
    masterDetails = getRemoteBranch(gitRemoteUri2, 2, 0, Constants.MASTER);
    newRefId = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertFalse(masterOldRefId.equals(newRefId));

    // make sure the change has been pulled into the current branch
    JSONObject testTxt2 = getChild(project2, "test.txt");
    assertEquals("branch 'master' change", getFileContent(testTxt2));
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitRemoteTest.java

License:Open Source License

@Test
public void testGetRemoteBranches() throws Exception {
    // clone a  repo
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    JSONObject clone = clone(clonePath);
    String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
    String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

    // get project metadata
    WebRequest request = getGetFilesRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());

    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);/*  w w  w . j  ava  2s .c  om*/
    String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE, null);
    assertNotNull(gitRemoteUri);

    Repository db1 = getRepositoryForContentLocation(cloneContentLocation);
    Git git = new Git(db1);
    int localBefore = git.branchList().call().size();
    int remoteBefore = git.branchList().setListMode(ListMode.REMOTE).call().size();
    int allBefore = git.branchList().setListMode(ListMode.ALL).call().size();
    branch(branchesLocation, "a");

    assertEquals(1, git.branchList().call().size() - localBefore);
    assertEquals(0, git.branchList().setListMode(ListMode.REMOTE).call().size() - remoteBefore);
    assertEquals(1, git.branchList().setListMode(ListMode.ALL).call().size() - allBefore);

    // push all
    // TODO: replace with REST API when bug 339115 is fixed
    git.push().setPushAll().call();

    assertEquals(1, git.branchList().call().size() - localBefore);
    assertEquals(1, git.branchList().setListMode(ListMode.REMOTE).call().size() - remoteBefore);
    assertEquals(2, git.branchList().setListMode(ListMode.ALL).call().size() - allBefore);

    checkoutBranch(cloneLocation, Constants.MASTER);
    JSONObject remoteBranch = getRemoteBranch(gitRemoteUri, 2, 0, Constants.MASTER);
    assertNotNull(remoteBranch);

    checkoutBranch(cloneLocation, "a");
    remoteBranch = getRemoteBranch(gitRemoteUri, 2, 0, "a");
    assertNotNull(remoteBranch);
}

From source file:org.exist.git.xquery.Push.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//from   w  w  w.j av  a2 s  . co  m
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        Git git = Git.open(new Resource(localPath), FS);

        Iterable<PushResult> answer = git.push().setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(args[1].getStringValue(), args[2].getStringValue()))
                .call();

        MemTreeBuilder builder = getContext().getDocumentBuilder();

        int nodeNr = builder.startElement(PUSH, null);

        for (PushResult push : answer) {

            builder.startElement(RESULT, null);

            for (TrackingRefUpdate tracking : push.getTrackingRefUpdates()) {

                builder.startElement(TRACKING_REF_UPDATE, null);

                builder.addAttribute(REMOTE_NAME, tracking.getRemoteName());
                builder.addAttribute(LOCAL_NAME, tracking.getLocalName());

                //builder.addAttribute(FORCE_UPDATE, Boolean.toString(tracking.forceUpdate));

                builder.addAttribute(OLD_OBJECTID, tracking.getOldObjectId().name());
                builder.addAttribute(NEW_OBJECTID, tracking.getNewObjectId().name());
            }

            for (RemoteRefUpdate remote : push.getRemoteUpdates()) {

                builder.startElement(REMOTE_REF_UPDATE, null);

                builder.addAttribute(REMOTE_NAME, remote.getRemoteName());
                builder.addAttribute(STATUS, remote.getStatus().name());

                if (remote.isExpectingOldObjectId())
                    builder.addAttribute(EXPECTED_OLD_OBJECTID, remote.getExpectedOldObjectId().name());

                if (remote.getNewObjectId() != null)
                    builder.addAttribute(NEW_OBJECTID, remote.getNewObjectId().name());

                builder.addAttribute(FAST_FORWARD, Boolean.toString(remote.isFastForward()));
                builder.addAttribute(FORCE_UPDATE, Boolean.toString(remote.isForceUpdate()));

                if (remote.getMessage() != null)
                    builder.characters(remote.getMessage());

                builder.endElement();
            }
            builder.endElement();
        }

        builder.endElement();

        return builder.getDocument().getNode(nodeNr);
    } catch (Throwable e) {
        e.printStackTrace();
        throw new XPathException(this, Module.EXGIT001, e);
    }
}

From source file:org.fusesource.fabric.git.internal.GitDataStore.java

License:Apache License

/**
 * Pushes any committed changes to the remote repo
 *//* w  w w .ja  v a2 s  .  co  m*/
protected Iterable<PushResult> doPush(Git git, GitContext gitContext, CredentialsProvider credentialsProvider)
        throws Exception {
    assertValid();
    Repository repository = git.getRepository();
    StoredConfig config = repository.getConfig();
    String url = config.getString("remote", remote, "url");
    if (Strings.isNullOrBlank(url)) {
        LOG.info("No remote repository defined yet for the git repository at "
                + GitHelpers.getRootGitDirectory(git) + " so not doing a push");
        return Collections.EMPTY_LIST;
    }

    String branch = gitContext != null && gitContext.getPushBranch() != null ? gitContext.getPushBranch()
            : GitHelpers.currentBranch(git);
    if (!branch.equals(MASTER_BRANCH)) {
        return git.push().setCredentialsProvider(credentialsProvider)
                .setRefSpecs(new RefSpec(MASTER_BRANCH), new RefSpec(branch)).call();
    } else {
        return git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(branch)).call();
    }
}

From source file:org.fusesource.fabric.itests.basic.git.FabricGitTestSupport.java

License:Apache License

/**
 * Create a profile in git and check that its bridged to the registry.
 *
 * @param git     The git object of the test repository.
 * @param version The version of the profile.
 * @param profile The profile name./* www .j  av a  2 s . co m*/
 * @throws Exception
 */
public void createAndTestProfileInGit(Git git, String version, String profile) throws Exception {
    //Create the test profile in git
    System.err.println("Create test profile:" + profile + " in git.");
    GitUtils.checkoutBranch(git, "origin", version);
    File testProfileDir = new File(git.getRepository().getWorkTree(), profile);
    testProfileDir.mkdirs();
    File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
    testProfileConfig.createNewFile();
    Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
    git.add().addFilepattern(profile).call();
    git.commit().setMessage("Create " + profile).call();
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
    GitUtils.waitForBranchUpdate(getCurator(), version);
    //Check that it has been bridged in zookeeper
    Thread.sleep(5000);
    assertNotNull(getCurator().checkExists().forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, profile)));
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

public void testWithProfiles() throws Exception {
    String testProfileNameBase = "mytestprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult()
            .build();//from  www . ja v a  2  s  .  c o m
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());

    GitUtils.waitForBranchUpdate(getCurator(), "1.0");

    Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo)
            .setCredentialsProvider(getCredentialsProvider()).call();
    Git git = Git.open(testrepo);
    GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0");
    git.fetch().setCredentialsProvider(getCredentialsProvider());
    GitUtils.checkoutBranch(git, "origin", "1.0");

    //Check that the default profile exists
    assertTrue(new File(testrepo, "default").exists());

    //Create test profile
    for (int i = 1; i <= 3; i++) {
        String testProfileName = testProfileNameBase + i;
        System.err.println("Create test profile:" + testProfileName + " in zookeeper");
        getFabricService().getVersion("1.0").createProfile(testProfileName);
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        git.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call();
        //Check that a newly created profile exists
        assertTrue(new File(testrepo, testProfileName).exists());
        //Delete test profile
        System.err.println("Delete test profile:" + testProfileName + " in git.");
        git.rm().addFilepattern(testProfileName).call();
        git.commit().setMessage("Delete " + testProfileName).call();
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        Thread.sleep(5000);
        assertFalse(new File(testrepo, testProfileName).exists());
        assertNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));

        //Create the test profile in git
        System.err.println("Create test profile:" + testProfileName + " in git.");
        File testProfileDir = new File(testrepo, testProfileName);
        testProfileDir.mkdirs();
        File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
        testProfileConfig.createNewFile();
        Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
        git.add().addFilepattern(testProfileName).call();
        RevCommit commit = git.commit().setMessage("Create " + testProfileName).call();
        FileTreeIterator fileTreeItr = new FileTreeIterator(git.getRepository());
        IndexDiff indexDiff = new IndexDiff(git.getRepository(), commit.getId(), fileTreeItr);
        System.out.println(indexDiff.getChanged());
        System.out.println(indexDiff.getAdded());
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        //Check that it has been bridged in zookeeper
        Thread.sleep(15000);
        assertNotNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));
    }
}

From source file:org.ihtsdo.ttk.services.sync.Example.java

License:Apache License

/**
 * Method description/*from w w  w  . ja va  2s .  c  om*/
 *
 *
 * @param args
 */
public static void main(String[] args) {
    try {

        // jGit provides the ability to manage the git repositories from 
        // your code in a very easy manner. For example, to create the new 
        // repository, you just have to indicate the target directory:
        File targetDir = new File("target/newRepository.git");
        Repository repo = new FileRepository(targetDir);
        repo.create(true);

        //Cloning the existing git repository is also very easy and nice:
        Git.cloneRepository().setURI(targetDir.toURI().toString()).setDirectory(new File("target/working-copy"))
                .setBranch("master").setBare(false).setRemote("origin").setNoCheckout(false).call();

        // And here is the way how you can add the changes, 
        // commit and push them to the origin:
        Git git = new Git(new FileRepository(new File("target/working-copy")));
        git.add().addFilepattern(".").call();
        git.commit().setMessage("some comment").call();
        git.push().setPushAll().setRemote("origin").call();

        // http://jzelenkov.com/post/35653947951/diving-into-jgit

        // http://download.eclipse.org/jgit/docs/jgit-2.0.0.201206130900-r/apidocs/org/eclipse/jgit/api/package-summary.html

        // http://blogs.atlassian.com/2013/04/git-flow-comes-to-java/
    } catch (IOException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    } catch (GitAPIException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public void commit(ProjectVersion project, IProgressMonitor monitor) throws TeamProviderException {
    try {//  w w  w .  ja  v  a 2 s  .c om
        Repository repository = createRepository(project);
        SubMonitor subMon = SubMonitor.convert(monitor, "Commit", 100);
        Git git = new Git(repository);
        // AddCommand addCommand = git.add();
        List<String> changedFiles = addNewFiles(git, subMon.newChild(30));
        if (!changedFiles.isEmpty()) {
            checkCanceled(subMon);
            CommitCommand commit = git.commit();
            Preferences node = PreferencesUtil.scopeFor(project.getParent());
            String username = node.get(GitConstants.KEY_USERNAME, "Jabylon");
            String email = node.get(GitConstants.KEY_EMAIL, "jabylon@example.org");
            String message = node.get(GitConstants.KEY_MESSAGE, "Auto Sync-up by Jabylon");
            boolean insertChangeId = node.getBoolean(GitConstants.KEY_INSERT_CHANGE_ID, false);
            commit.setAuthor(username, email);
            commit.setCommitter(username, email);
            commit.setInsertChangeId(insertChangeId);
            commit.setMessage(message);
            for (String path : changedFiles) {
                checkCanceled(subMon);
                commit.setOnly(path);

            }
            commit.call();
            subMon.worked(10);
        } else {
            LOGGER.info("No changed files, skipping commit phase");
        }
        checkCanceled(subMon);
        PushCommand push = git.push();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            push.setRemote(stripUserInfo(uri).toString());
        push.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(60)));
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            push.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        push.setCredentialsProvider(createCredentialsProvider(project.getParent()));

        RefSpec spec = createRefSpec(project);
        push.setRefSpecs(spec);

        Iterable<PushResult> result = push.call();
        for (PushResult r : result) {
            for (RemoteRefUpdate rru : r.getRemoteUpdates()) {
                if (rru.getStatus() != RemoteRefUpdate.Status.OK
                        && rru.getStatus() != RemoteRefUpdate.Status.UP_TO_DATE) {
                    String error = "Push failed: " + rru.getStatus();
                    LOGGER.error(error);
                    throw new TeamProviderException(error);
                }
            }
        }

        Ref ref = repository.getRef(project.getName());
        if (ref != null) {
            LOGGER.info("Successfully pushed {} to {}", ref.getObjectId(),
                    project.getParent().getRepositoryURI());
        }
    } catch (NoHeadException e) {
        throw new TeamProviderException(e);
    } catch (NoMessageException e) {
        throw new TeamProviderException(e);
    } catch (ConcurrentRefUpdateException e) {
        throw new TeamProviderException(e);
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (WrongRepositoryStateException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } finally {
        if (monitor != null)
            monitor.done();
    }
}

From source file:org.jboss.forge.rest.main.GitCommandCompletePostProcessor.java

License:Apache License

protected RevCommit doCommitAndPush(Git git, String message, CredentialsProvider credentials,
        PersonIdent author, String remote, String branch) throws IOException, GitAPIException {
    CommitCommand commit = git.commit().setAll(true).setMessage(message);
    if (author != null) {
        commit = commit.setAuthor(author);
    }/*from www  .j a  v a 2 s.  c  o m*/

    RevCommit answer = commit.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage());
    }

    if (isPushOnCommit()) {
        Iterable<PushResult> results = git.push().setCredentialsProvider(credentials).setRemote(remote).call();
        for (PushResult result : results) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch
                        + " updates: " + GitHelpers.toString(result.getRemoteUpdates()));
            }
        }
    }
    return answer;

}