Java 类org.eclipse.jgit.api.PushCommand 实例源码

项目:jira-dvcs-connector    文件:GitTestSupport.java   
/**
 * Push current state to remote repository.
 *
 * @param repositoryName for which repository
 * @param username committer username
 * @param password committer password
 */
public void push(String repositoryName, String username, String password)
{
    RepositoryContext repositoryContext = repositoryByName.get(repositoryName);

    try
    {
        PushCommand pushCommand = repositoryContext.git.push();
        pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
        pushCommand.call();
    }
    catch (GitAPIException e)
    {
        throw new RuntimeException(e);
    }
}
项目:release-maven-plugin-parent    文件:GitProposedTag.java   
@Override
public void delete() throws SCMException {
    try {
        final List<String> deleted = git.tagDelete().setTags(name()).call();
        if (!deleted.isEmpty()) {
            final PushCommand pushCommand = git.push().add(":refs/tags/" + name());
            if (remoteUrlOrNull != null) {
                pushCommand.setRemote(remoteUrlOrNull);
            }
            pushAndLogResult(pushCommand);
        }
        log.info(String.format("Deleted tag '%s' from repository", name()));
    } catch (final GitAPIException e) {
        throw new SCMException(e, "Remote tag '%s' could not be deleted!", name());
    }
}
项目:fabric8-devops    文件:GitHelpers.java   
public static RevCommit doCommitAndPush(Git git, String message, UserDetails userDetails, PersonIdent author, String branch, String origin, boolean pushOnCommit) throws GitAPIException {
    CommitCommand commit = git.commit().setAll(true).setMessage(message);
    if (author != null) {
        commit = commit.setAuthor(author);
    }

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

    if (pushOnCommit) {
        PushCommand push = git.push();
        configureCommand(push, userDetails);
        Iterable<PushResult> results = push.setRemote(origin).call();
        for (PushResult result : results) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates()));
            }
        }
    }
    return answer;
}
项目:gerrit    文件:GitUtil.java   
public static PushResult pushOne(
    TestRepository<?> testRepo,
    String source,
    String target,
    boolean pushTags,
    boolean force,
    List<String> pushOptions)
    throws GitAPIException {
  PushCommand pushCmd = testRepo.git().push();
  pushCmd.setForce(force);
  pushCmd.setPushOptions(pushOptions);
  pushCmd.setRefSpecs(new RefSpec((source != null ? source : "") + ":" + target));
  if (pushTags) {
    pushCmd.setPushTags();
  }
  Iterable<PushResult> r = pushCmd.call();
  return Iterables.getOnlyElement(r);
}
项目:release-maven-plugin-parent    文件:GitProposedTag.java   
private void pushAndLogResult(final PushCommand pushCommand)
        throws GitAPIException, InvalidRemoteException, TransportException {
    for (final PushResult result : pushCommand.call()) {
        for (final RemoteRefUpdate upd : result.getRemoteUpdates()) {
            log.info(upd.toString());
        }
    }
}
项目:release-maven-plugin-parent    文件:GitProposedTag.java   
@Override
public void tagAndPush() throws SCMException {
    log.info(String.format("About to tag the repository with %s", name()));
    try {
        final PushCommand pushCommand = git.push().add(saveAtHEAD());
        if (remoteUrlOrNull != null) {
            pushCommand.setRemote(remoteUrlOrNull);
        }
        pushAndLogResult(pushCommand);
    } catch (final GitAPIException e) {
        throw new SCMException(e, "Tag '%s' could not be pushed!", name());
    }
}
项目:multi-module-maven-release-plugin    文件:LocalGitRepo.java   
@Override
public void pushTags(Collection<AnnotatedTag> tags) throws GitAPIException {
    PushCommand pushCommand = git.push();
    if (remoteUrl != null) {
        pushCommand.setRemote(remoteUrl);
    }

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

    pushCommand.call();
}
项目:git-appraise-eclipse    文件:AppraiseGitReviewClient.java   
/**
 * 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();
  }
}
项目:gerrit    文件:GitUtil.java   
public static PushResult pushTag(TestRepository<?> testRepo, String tag, boolean force)
    throws GitAPIException {
  PushCommand pushCmd = testRepo.git().push();
  pushCmd.setForce(force);
  pushCmd.setRefSpecs(new RefSpec("refs/tags/" + tag + ":refs/tags/" + tag));
  Iterable<PushResult> r = pushCmd.call();
  return Iterables.getOnlyElement(r);
}
项目:Elegit    文件:SessionController.java   
private void pushBranchOrAllDetails(RepoHelperBuilder.AuthDialogResponse response, PushType pushType,
                                    PushCommand push) throws
        TransportException {
    try{
        RepositoryMonitor.resetFoundNewChanges(false);
        RepoHelper helper = theModel.getCurrentRepoHelper();
        if (response != null) {
            helper.ownerAuth =
                    new UsernamePasswordCredentialsProvider(response.username, response.password);
        }
        if (pushType == PushType.BRANCH) {
            helper.pushCurrentBranch(push);
        } else if (pushType == PushType.ALL) {
            helper.pushAll(push);
        } else {
            assert false : "PushType enum case not handled";
        }
        gitStatus();
    } catch (InvalidRemoteException e) {
        showNoRemoteNotification();
    } catch (PushToAheadRemoteError e) {
        showPushToAheadRemoteNotification(e.isAllRefsRejected());
    } catch (TransportException e) {
        throw e;
    } catch(Exception e) {
        showGenericErrorNotification();
        e.printStackTrace();
    }
}
项目:Elegit    文件:PushPullTest.java   
@Test
public void cloneThenPushTestWithoutAuthentication() throws Exception {
    File authData = new File(testFileLocation + "httpUsernamePassword.txt");

    // If a developer does not have this file present, test should just pass.
    if (!authData.exists() && looseTesting)
        return;

    Scanner scanner = new Scanner(authData);
    String ignoreURL = scanner.next();
    String username = scanner.next();
    String password = scanner.next();
    UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);

    String remoteURL = "https://github.com/TheElegitTeam/PushPullTests.git";
    //String remoteURL = "https://github.com/connellyj/HelloWorld.git";

    Path repoPathPush = directoryPath.resolve("clonepush");
    ClonedRepoHelper helperPush = new ClonedRepoHelper(repoPathPush, remoteURL, credentials);
    assertNotNull(helperPush);
    helperPush.obtainRepository(remoteURL);

    // Update the file, then commit and push
    Path readmePath = repoPathPush.resolve("README.md");
    System.out.println(readmePath);
    String timestamp = (new Date()).toString() + "\n";
    Files.write(readmePath, timestamp.getBytes(), StandardOpenOption.APPEND);
    helperPush.addFilePathTest(readmePath);
    helperPush.commit("added a character");
    PushCommand push = helperPush.prepareToPushAll();
    helperPush.pushAll(push);

}
项目:tool.accelerate.core    文件:GitHubConnector.java   
/**
 * 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);
    }
}
项目:Android-Password-Store    文件:PushOperation.java   
@Override
public void execute() {
    if (this.provider != null) {
        ((PushCommand) this.command).setCredentialsProvider(this.provider);
    }
    new GitAsyncTask(callingActivity, true, false, this).execute(this.command);
}
项目:pactbroker-maven-plugin    文件:GitApi.java   
/**
 * adds, commits and pushes changes only, if there are actually changes
 * 
 * @param message
 * @return false, if there were no changes to be pushed
 * @throws Exception
 */
public boolean pushChanges(String message) throws Exception {

    if (repository.diff().call().isEmpty()) {
        return false;
    }

    repository.add().addFilepattern(".").call();
    repository.commit().setMessage(message).call();

    PushCommand pushCmd = repository.push();
    credentialsProvider.ifPresent(c -> pushCmd.setCredentialsProvider(c));
    pushCmd.call();
    return true;
}
项目:ivy-pdi-git-steps    文件:PushGitCommand.java   
public Git call(final GitOperationsStep gitOperationsStep, Git git,
    CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder)
    throws IllegalArgumentException, IOException,
    InvalidRemoteException, TransportException, GitAPIException {

  PushCommand pc = git.push().setDryRun(dryRun).setForce(force)
      .setThin(thin);
  if (cp != null) {
    pc = pc.setCredentialsProvider(cp);
  }
  if (!Const.isEmpty(this.receivePack)) {
    pc = pc.setReceivePack(gitOperationsStep
        .environmentSubstitute(receivePack));
  }
  if (!Const.isEmpty(this.referenceToPush)) {
    pc = pc.add(gitOperationsStep
        .environmentSubstitute(this.referenceToPush));
  }
  if (!Const.isEmpty(this.remote)) {
    pc = pc.setRemote(gitOperationsStep
        .environmentSubstitute(this.remote));
  }
  if (this.pushAllBranches) {
    pc = pc.setPushAll();
  }
  if (this.pushAllTags) {
    pc = pc.setPushTags();
  }
  pc.call();
  return git;
}
项目:centraldogma    文件:GitWithAuth.java   
@Override
public PushCommand push() {
    return configure(super.push()).setProgressMonitor(progressMonitor("push"));
}
项目:spring-cloud-release-tools    文件:GitRepo.java   
PushCommand push(Git git) {
    return git.push()
            .setCredentialsProvider(this.provider)
            .setTransportConfigCallback(this.callback);
}
项目:github-bucket    文件:Config.java   
default PushCommand configure(PushCommand cmd) {
    return cmd;
}
项目:fabric8-forge    文件:ForgeTestSupport.java   
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);
}
项目:fabric8-forge    文件:RepositoryResource.java   
protected Iterable<PushResult> doPush(Git git) throws Exception {
    PushCommand command = git.push();
    configureCommand(command, userDetails);
    return command.setRemote(getRemote()).call();
}
项目:Elegit    文件:FastForwardTest.java   
@Test
public void testFastForward() throws Exception {
    File authData = new File(testFileLocation + "httpUsernamePassword.txt");

    // If a developer does not have this file present, test should just pass.
    if (!authData.exists() && looseTesting)
        return;

    Scanner scanner = new Scanner(authData);
    String ignoreURL = scanner.next();
    String username = scanner.next();
    String password = scanner.next();
    UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);

    String remoteURL = "https://github.com/TheElegitTeam/FastForwards.git";

    // Repo that will commit to make a fast forward commit
    Path repoPathFast = directoryPath.resolve("fastforward");
    ClonedRepoHelper helperFast = new ClonedRepoHelper(repoPathFast, remoteURL, credentials);
    assertNotNull(helperFast);
    helperFast.obtainRepository(remoteURL);

    // Find the remote 'fast_branch'
    remote_helper = (RemoteBranchHelper) helperFast.getBranchModel().getBranchByName(BranchModel.BranchType.REMOTE, "origin/fast_branch");

    // Track fast_branch and check it out
    fast_helper = helperFast.getBranchModel().trackRemoteBranch(remote_helper);
    fast_helper.checkoutBranch();

    // Update the file in fast_branch
    Path filePath = repoPathFast.resolve("fastforward.txt");
    String timestamp = (new Date()).toString() + "\n";
    Files.write(filePath, timestamp.getBytes(), StandardOpenOption.APPEND);
    helperFast.addFilePathTest(filePath);

    // Commit changes in fast_branch and push
    helperFast.commit("added a character");
    PushCommand command = helperFast.prepareToPushAll();
    helperFast.pushAll(command);

    //Checkout master
    master_helper = (LocalBranchHelper) helperFast.getBranchModel().getBranchByName(BranchModel.BranchType.LOCAL, "master");
    master_helper.checkoutBranch();

    // Merge fast_forward into master
    helperFast.getBranchModel().mergeWithBranch(fast_helper);

    // Check that Elegit recognizes there are unpushed commits
    assertEquals(true, helperFast.getAheadCount()>0);

    // Push changes
    command = helperFast.prepareToPushAll();
    helperFast.pushAll(command);

}
项目:Elegit    文件:FastForwardTest.java   
@Test
public void testFastForwardCommitCanPush() throws Exception {
    File authData = new File(testFileLocation + "httpUsernamePassword.txt");

    // If a developer does not have this file present, test should just pass.
    if (!authData.exists() && looseTesting)
        return;

    // a and b at the same spot
    // make changes, commit to a
    // push changes in a
    // merge a into b
    // check that we can push

    Scanner scanner = new Scanner(authData);
    String ignoreURL = scanner.next();
    String username = scanner.next();
    String password = scanner.next();
    UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);

    String remoteURL = "https://github.com/TheElegitTeam/FastForwards.git";

    // Repo that will commit to make a fast forward commit
    Path repoPathFast = directoryPath.resolve("fastforward");
    ClonedRepoHelper helperFast = new ClonedRepoHelper(repoPathFast, remoteURL, credentials);
    assertNotNull(helperFast);
    helperFast.obtainRepository(remoteURL);

    // Find the remote 'can_push'
    remote_helper = (RemoteBranchHelper) helperFast.getBranchModel().getBranchByName(BranchModel.BranchType.REMOTE, "origin/can_push");

    // Track can_push and check it out
    fast_helper = helperFast.getBranchModel().trackRemoteBranch(remote_helper);
    fast_helper.checkoutBranch();

    // Update the file in can_push
    Path filePath = repoPathFast.resolve("fastforward.txt");
    String timestamp = (new Date()).toString() + "\n";
    Files.write(filePath, timestamp.getBytes(), StandardOpenOption.APPEND);
    helperFast.addFilePathTest(filePath);

    // Commit changes in can_push and push
    helperFast.commit("added a character");
    PushCommand command = helperFast.prepareToPushAll();
    helperFast.pushAll(command);

    // Find the remote 'can_pushb' and check it out
    remote_helperb = (RemoteBranchHelper) helperFast.getBranchModel().getBranchByName(BranchModel.BranchType.REMOTE, "origin/can_pushb");
    fast_helperb = helperFast.getBranchModel().trackRemoteBranch(remote_helperb);
    fast_helperb.checkoutBranch();

    // Merge can_push into can_pushb
    helperFast.getBranchModel().mergeWithBranch(fast_helper);

    // Check that Elegit recognizes there are unpushed commits
    assertEquals(true, helperFast.getAheadCount()>0);

    // Push changes
    command = helperFast.prepareToPushAll();
    helperFast.pushAll(command);

}
项目:Elegit    文件:PushPullTest.java   
@Test
public void testPushPullBothCloned() throws Exception {
    File authData = new File(testFileLocation + "httpUsernamePassword.txt");

    // If a developer does not have this file present, test should just pass.
    if (!authData.exists() && looseTesting)
        return;

    Scanner scanner = new Scanner(authData);
    String ignoreURL = scanner.next();
    String username = scanner.next();
    String password = scanner.next();
    UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);

    String remoteURL = "https://github.com/TheElegitTeam/PushPullTests.git";

    // Repo that will push
    Path repoPathPush = directoryPath.resolve("pushpull1");
    ClonedRepoHelper helperPush = new ClonedRepoHelper(repoPathPush, remoteURL, credentials);
    assertNotNull(helperPush);
    helperPush.obtainRepository(remoteURL);

    // Repo that will pull
    Path repoPathPull = directoryPath.resolve("pushpull2");
    ClonedRepoHelper helperPull = new ClonedRepoHelper(repoPathPull, remoteURL, credentials);
    assertNotNull(helperPull);
    helperPull.obtainRepository(remoteURL);

    // Update the file, then commit and push
    Path readmePath = repoPathPush.resolve("README.md");
    System.out.println(readmePath);
    String timestamp = (new Date()).toString() + "\n";
    Files.write(readmePath, timestamp.getBytes(), StandardOpenOption.APPEND);
    helperPush.addFilePathTest(readmePath);
    helperPush.commit("added a character");
    PushCommand command = helperPush.prepareToPushAll();
    helperPush.pushAll(command);

    // Add a tag named for the current timestamp
    ObjectId headId = helperPush.getBranchModel().getCurrentBranch().getHeadId();
    String tagName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmSSS"));
    helperPush.getTagModel().tag(tagName,headId.name());
    helperPush.pushTags();

    // Remove the tag we just added
    helperPush.getTagModel().deleteTag(tagName);
    command = helperPush.prepareToPushAll();
    command.setRemote("origin").add(":refs/tags/" + tagName);
    helperPush.pushAll(command);

    // Now do the pull (well, a fetch)
    helperPull.fetch(false);
    helperPull.mergeFromFetch();

    // Update lists of branches
    helperPull.getBranchModel().updateAllBranches();

}
项目:Elegit    文件:PushPullTest.java   
@Test
public void testPushPullBothClonedExisting() throws Exception {
    File authData = new File(testFileLocation + "httpUsernamePassword.txt");

    // If a developer does not have this file present, test should just pass.
    if (!authData.exists() && looseTesting)
        return;

    Scanner scanner = new Scanner(authData);
    String ignoreURL = scanner.next();
    String username = scanner.next();
    String password = scanner.next();
    UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);

    String remoteURL = "https://github.com/TheElegitTeam/PushPullTests.git";

    // Repo that will push
    Path repoPathPush = directoryPath.resolve("pushpull1");
    ClonedRepoHelper helperPush = new ClonedRepoHelper(repoPathPush, remoteURL, credentials);
    assertNotNull(helperPush);
    helperPush.obtainRepository(remoteURL);

    // Repo that will pull
    Path repoPathPull = directoryPath.resolve("pushpull2");
    ClonedRepoHelper clonedHelperPull = new ClonedRepoHelper(repoPathPull, remoteURL, credentials);
    assertNotNull(clonedHelperPull);
    clonedHelperPull.obtainRepository(remoteURL);
    ExistingRepoHelper existingHelperPull = new ExistingRepoHelper(repoPathPull, new ElegitUserInfoTest());

    // Update the file, then commit and push
    Path readmePath = repoPathPush.resolve("README.md");
    System.out.println(readmePath);
    String timestamp = "testPushPullBothClonedExisting " + (new Date()).toString() + "\n";
    Files.write(readmePath, timestamp.getBytes(), StandardOpenOption.APPEND);
    helperPush.addFilePathTest(readmePath);
    helperPush.commit("added a character");
    PushCommand command = helperPush.prepareToPushAll();
    helperPush.pushAll(command);

    // Now do the pull (well, a fetch)
    existingHelperPull.fetch(false);
    existingHelperPull.mergeFromFetch();

}
项目:Elegit    文件:RemoteBranchTest.java   
@Test
public void testBranchPushAndDelete() throws Exception {
    File authData = new File(testFileLocation + "httpUsernamePassword.txt");

    // If a developer does not have this file present, test should just pass.
    if (!authData.exists() && looseTesting)
        return;

    Scanner scanner = new Scanner(authData);
    String ignoreURL = scanner.next();
    String username = scanner.next();
    String password = scanner.next();
    UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);

    String remoteURL = "https://github.com/TheElegitTeam/RemoteBranchDeletion.git";

    // Repo that will commit to master
    Path repoPathPush = directoryPath.resolve("pusher");
    ClonedRepoHelper helperPush = new ClonedRepoHelper(repoPathPush, remoteURL, credentials);
    assertNotNull(helperPush);
    helperPush.obtainRepository(remoteURL);


    /* ********************* BRANCH AND PUSH SECTION ********************* */
    // Check that a previous test wasn't interrupted, if so make sure our branch is not there
    for (RemoteBranchHelper helper : helperPush.getBranchModel().getRemoteBranchesTyped()) {
        if (helper.getRefName().contains("new_branch")) {
            helperPush.getBranchModel().deleteRemoteBranch(helper);
        }
    }

    // Make a new branch and push it
    helperPush.getBranchModel().createNewLocalBranch("new_branch");
    helperPush.getBranchModel().getBranchByName(BranchModel.BranchType.LOCAL, "new_branch").checkoutBranch();
    helperPush.updateModel();
    // Check that we can push
    assertEquals(true, helperPush.canPush());

    PushCommand push = helperPush.prepareToPushCurrentBranch(true);
    helperPush.pushCurrentBranch(push);
    helperPush.updateModel();
    // Check that there is a remote branch now
    assertEquals(true, helperPush.getBranchModel().getRemoteBranchesTyped().toString().contains("new_branch"));



    // Test that we can delete the branch too
    helperPush.getBranchModel().updateRemoteBranches();
    BranchHelper remoteBranchHelper = helperPush.getBranchModel().getBranchByName(BranchModel.BranchType.REMOTE, "origin/new_branch");
    helperPush.getBranchModel().deleteRemoteBranch((RemoteBranchHelper) remoteBranchHelper);

    // Check that the branch was deleted
    assertEquals(true, helperPush.getBranchModel().getCurrentRemoteBranch()==null);
}
项目:Elegit    文件:DuplicateRepoInvisCommitTest.java   
@Test
public void testSwitchingRepoInvisCommit() throws Exception {
    File authData = new File(testFileLocation + "httpUsernamePassword.txt");

    // If a developer does not have this file present, test should just pass.
    if (!authData.exists())
        return;

    Scanner scanner = new Scanner(authData);
    String ignoreURL = scanner.next();
    String username = scanner.next();
    String password = scanner.next();
    UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(username, password);

    // First copy of the repo
    Path repoPath1 = directoryPath.resolve("repo1");
    ClonedRepoHelper repo1 = new ClonedRepoHelper(repoPath1, REMOTE_URL, credentials);
    assertNotNull(repo1);
    repo1.obtainRepository(REMOTE_URL);

    CommitHelper repo1OldHead = repo1.getCommit("master");
    assertNotNull(repo1OldHead);

    // Make a change in repo1 and commit it
    File file = Paths.get(repoPath1.toString(), "File.txt").toFile();
    assertTrue(file.exists());

    try(PrintWriter fileTextWriter = new PrintWriter( file )){
        fileTextWriter.println("Add a line");
    }

    repo1.addFilePathTest(file.toPath());
    repo1.commit("Modified file.txt in a unit test!");

    CommitHelper repo1NewHead = repo1.getCommit("master");
    assertNotNull(repo1NewHead);

    // Second copy of the repo
    Path repoPath2 = directoryPath.resolve("repo2");
    ClonedRepoHelper repo2 = new ClonedRepoHelper(repoPath2, REMOTE_URL, credentials);
    assertNotNull(repo2);
    repo2.obtainRepository(REMOTE_URL);

    CommitHelper repo2OldHead = repo2.getCommit("master");
    assertNotNull(repo2OldHead);
    assertEquals(repo1OldHead.getId(), repo2OldHead.getId());

    // Push the previous commit
    PushCommand push = repo1.prepareToPushAll();
    repo1.pushAll(push);

    // Fetch into the second repo
    repo2.fetch(false);
    repo2.mergeFromFetch();

    CommitHelper repo2NewHead = repo2.getCommit("master");
    assertNotNull(repo2NewHead);
    assertEquals(repo1NewHead.getId(), repo2NewHead.getId());

    repo1.updateModel();
    List<CommitHelper> repo1LocalCommits = repo1.getLocalCommits();
    List<CommitHelper> repo1RemoteCommits = repo1.getRemoteCommits();

    assertTrue(repo1LocalCommits.contains(repo1OldHead));
    assertTrue(repo1RemoteCommits.contains(repo1OldHead));
    assertTrue(repo1LocalCommits.contains(repo1NewHead));
    assertTrue(repo1RemoteCommits.contains(repo1NewHead));

    repo2.updateModel();
    List<CommitHelper> repo2LocalCommits = repo2.getLocalCommits();
    List<CommitHelper> repo2RemoteCommits = repo2.getRemoteCommits();

    assertTrue(repo2LocalCommits.contains(repo2OldHead));
    assertTrue(repo2RemoteCommits.contains(repo2OldHead));
    assertTrue(repo2LocalCommits.contains(repo2NewHead));
    assertTrue(repo2RemoteCommits.contains(repo2NewHead));

}
项目:verigreen    文件:JGitOperator.java   
@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();
           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;
   }
项目:appformer    文件:GitImpl.java   
public PushCommand _push() {
    return git.push();
}
项目:Android-Password-Store    文件:GitAsyncTask.java   
@Override
protected String doInBackground(GitCommand... commands) {
    Integer nbChanges = null;
    for (GitCommand command : commands) {
        Log.d("doInBackground", "Executing the command <" + command.toString() + ">");
        try {
            if (command instanceof StatusCommand) {
                // in case we have changes, we want to keep track of it
                org.eclipse.jgit.api.Status status = ((StatusCommand) command).call();
                nbChanges = status.getChanged().size() + status.getMissing().size();
            } else if (command instanceof CommitCommand) {
                // the previous status will eventually be used to avoid a commit
                if (nbChanges == null || nbChanges > 0)
                    command.call();
            }else if (command instanceof PushCommand) {
                for (final PushResult result : ((PushCommand) command).call()) {
                    // Code imported (modified) from Gerrit PushOp, license Apache v2
                    for (final RemoteRefUpdate rru : result.getRemoteUpdates()) {
                        switch (rru.getStatus()) {
                            case REJECTED_NONFASTFORWARD:
                                return activity.getString(R.string.git_push_nff_error);
                            case REJECTED_NODELETE:
                            case REJECTED_REMOTE_CHANGED:
                            case NON_EXISTING:
                            case NOT_ATTEMPTED:
                                return activity.getString(R.string.git_push_generic_error) + rru.getStatus().name();
                            case REJECTED_OTHER_REASON:
                                if ("non-fast-forward".equals(rru.getMessage())) {
                                    return activity.getString(R.string.git_push_other_error);
                                } else {
                                    return activity.getString(R.string.git_push_generic_error) + rru.getMessage();
                                }
                            default:
                                break;
                        }
                    }
                }
            } else {
                command.call();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage() + "\nCaused by:\n" + e.getCause();
        }
    }
    return "";
}
项目:wandora    文件:Push.java   
@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);
}
项目:ant-git-tasks    文件:PushTask.java   
@Override
protected void doExecute() {
        try {
                StoredConfig config = git.getRepository().getConfig();
                List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

                if (remoteConfigs.isEmpty()) {
                        URIish uri = new URIish(getUri());

                        RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);

                        remoteConfig.addURI(uri);
                        remoteConfig.addFetchRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
                        remoteConfig.addPushRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
                        remoteConfig.update(config);

                        config.save();
                }

                String currentBranch = git.getRepository().getBranch();
                List<RefSpec> specs = Arrays.asList(new RefSpec(currentBranch + ":" + currentBranch));

                PushCommand pushCommand = git.push().
                        setPushAll().
                        setRefSpecs(specs).
                        setDryRun(false).
                        setRemote(getUri());

                setupCredentials(pushCommand);

                if (includeTags) {
                        pushCommand.setPushTags();
                }

                if (getProgressMonitor() != null) {
                        pushCommand.setProgressMonitor(getProgressMonitor());
                }

                Iterable<PushResult> pushResults = pushCommand.setForce(true).call();

                for (PushResult pushResult : pushResults) {
                        GitTaskUtils.validateTrackingRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getTrackingRefUpdates());
                        log(pushResult.getMessages());
                }
        } catch (Exception e) {
                if (pushFailedProperty != null) {
                        getProject().setProperty(pushFailedProperty, e.getMessage());
                }

                throw new GitBuildException(PUSH_FAILED_MESSAGE, e);
        }
}