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

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

Introduction

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

Prototype

public ListBranchCommand branchList() 

Source Link

Document

Return a command object used to list branches

Usage

From source file:org.zanata.sync.plugin.git.service.impl.GitSyncService.java

License:Open Source License

private void checkOutBranch(File destPath, String branch) {
    try {//  ww w  .j  a  v  a 2s  .  co m
        Git git = Git.open(destPath);
        List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        /* refs will have name like these:
        refs/heads/master
        refs/remotes/origin/master
        refs/remotes/origin/zanata
        */
        Optional<Ref> localBranchRef = Optional.empty();
        Optional<Ref> remoteBranchRef = Optional.empty();
        for (Ref ref : refs) {
            String refName = ref.getName();
            if (refName.equals("refs/heads/" + branch)) {
                localBranchRef = Optional.of(ref);
            }
            if (refName.equals("refs/remotes/origin/" + branch)) {
                remoteBranchRef = Optional.of(ref);
            }
        }

        if (branch.equals("master")) {
            log.debug("merging origin/master");
            git.checkout().setName("master").call();
            git.merge().setFastForward(MergeCommand.FastForwardMode.FF_ONLY).include(remoteBranchRef.get())
                    .call();
            return;
        }

        /**
         * If branch found in local and is not master, delete it, create new local branch from remote.
         * If branch does not exists in remote, create new local branch based on master branch.
         */
        Ref ref;
        if (localBranchRef.isPresent()) {
            git.checkout().setName("master").setForce(true).call();
            git.branchDelete().setBranchNames(branch).call();
        }

        if (remoteBranchRef.isPresent()) {
            ref = git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/" + branch)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).call();
        } else {
            ref = git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/master")
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).call();
        }
        log.debug("checked out {}", ref);
        git.checkout().setName(branch).call();
        if (log.isDebugEnabled()) {
            log.debug("current branch is: {}", git.getRepository().getBranch());
        }
    } catch (IOException | GitAPIException e) {
        throw new RepoSyncException(e);
    }
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

@Test
public void deleteBranch() throws IOException, GitAPIException {
    // given/*www.  j a  va  2s .  c o  m*/
    Repository repository = support.Git.createRepository("keesun", "test", false);
    Git git = new Git(repository);

    String fileName = "readme.md";
    String contents = "Hello World";
    String commitMessage = "Initial commit";
    addCommit(git, fileName, contents, commitMessage, null);

    git.branchCreate().setName("develop").setForce(true).call();
    GitRepository.checkout(repository, "develop");

    // When
    String branchName = "refs/heads/master";
    GitRepository.deleteBranch(repository, branchName);

    // Then
    List<Ref> refs = git.branchList().call();
    for (Ref ref : refs) {
        if (ref.getName().equals(branchName)) {
            fail("deleting branch was failed");
        }
    }
}

From source file:replicatorg.app.ui.panels.UpdateChecker.java

License:Open Source License

private void updateFilaments() {
    final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
    final Git git;
    final Status repoStatus;
    final RemoteAddCommand remoteAddCmd;
    ResetCommand resetCmd;//www .  j  a v a  2  s . com
    CheckoutCommand checkoutCmd;
    final String currentBranch, newBranch;
    final List<Ref> branchList;
    Repository filamentsRepo;
    boolean branchFoundLocally = false;
    RevCommit stash = null;

    repoBuilder.setMustExist(true);
    repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git"));

    try {
        try {
            Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass());
            filamentsRepo = repoBuilder.build();
        } catch (RepositoryNotFoundException ex) {
            try {
                Base.writeLog("Repository wasn't initialized, initializing it to the given URL: "
                        + FILAMENTS_REPO_URL, this.getClass());
                repoBuilder.setMustExist(false);
                filamentsRepo = repoBuilder.build();
                filamentsRepo.create();
            } catch (IOException ex1) {
                Base.writeLog("IOException while attempting to initialize repository, not updating filaments",
                        this.getClass());
                return;
            }
        }

        currentBranch = filamentsRepo.getBranch();

    } catch (IOException ex) {
        Base.writeLog("IOException while attempting to open repository, not updating filaments",
                this.getClass());
        return;
    }

    git = new Git(filamentsRepo);

    try {
        // it should be only 1, but it shortens the code needed, as the call()
        // method returns an iterable
        for (RevCommit commit : git.log().setMaxCount(1).call()) {
            Base.writeLog("Current commit hash: " + commit, this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog(
                "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update",
                this.getClass());
    }

    try {
        remoteAddCmd = git.remoteAdd();
        remoteAddCmd.setName("origin");
        remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL));
        remoteAddCmd.call();
    } catch (URISyntaxException ex) {
        Base.writeLog("Invalid git filament repo remote URL!", this.getClass());
        return;
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass());
        return;
    }

    try {

        if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) {
            Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH
                    + ", searching for it", this.getClass());
            checkoutCmd = git.checkout();
            checkoutCmd.setName(FILAMENTS_REPO_BRANCH);

            branchList = git.branchList().call();

            for (Ref ref : branchList) {
                if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) {
                    Base.writeLog("Correct branch was found locally", this.getClass());
                    branchFoundLocally = true;
                    break;
                }
            }

            if (branchFoundLocally == false) {
                Base.writeLog(
                        "No correct branch was found locally, attempting to checkout a new branch tracking the remote",
                        this.getClass());
                checkoutCmd.setCreateBranch(true);
                checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
                checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH);
                git.fetch().call();
            }

            RevCommit backup = null;
            if (git.status().call().isClean() == false) {
                git.add().addFilepattern(".").call();
                backup = git.commit().setMessage("local backup of user modifications").call();
            }

            newBranch = checkoutCmd.call().getName();

            if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) {
                Base.writeLog("Unable to change to correct branch, aborting update", this.getClass());
                return;
            } else {
                Base.writeLog("Changed to correct branch, " + newBranch, this.getClass());
            }

            try {
                for (RevCommit commit : git.log().setMaxCount(1).call()) {
                    Base.writeLog("Commit hash after branch change: " + commit, this.getClass());

                }
            } catch (GitAPIException ex) {
                // we don't want all the process to stop just because we couldn't acquire the hash here,
                // hence this catch
                Base.writeLog(
                        "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update",
                        this.getClass());
            }

            if (backup != null) {
                // TODO: restore backup of user modifications
                //git.cherryPick().setNoCommit(true).include(backup).call();
            }
        }

        repoStatus = git.status().call();

        checkoutCmd = git.checkout();
        checkoutCmd.setName(FILAMENTS_REPO_BRANCH);
        checkoutCmd.call();

        git.fetch();
        resetCmd = git.reset();
        resetCmd.setMode(ResetType.HARD);
        resetCmd.call();

        git.pull().call();

        /*
        repoStatus = git.status().call();
        if (repoStatus.hasUncommittedChanges()) {
        Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass());
        stash = git.stashCreate().call();
        git.pull().call();
        git.stashApply().call();        // will apply the last stash made
        git.stashDrop().call();         // remove the last stash made
        } else {
        Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass());
        git.pull().call();
        }
        */

        Base.writeLog("Filament update concluded successfully!", this.getClass());

        try {
            for (RevCommit commit : git.log().setMaxCount(1).call()) {
                Base.writeLog("Commit hash after update process finished: " + commit, this.getClass());

            }
        } catch (GitAPIException ex) {
            // we don't want all the process to stop just because we couldn't acquire the hash here,
            // hence this catch
            Base.writeLog(
                    "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update",
                    this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass());
        try {
            resetCmd = git.reset();
            resetCmd.setMode(ResetType.HARD);
            resetCmd.call();

            if (stash != null) {
                git.stashApply().call();
                git.stashDrop().call();
            }

        } catch (GitAPIException ex1) {
            Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...",
                    this.getClass());
        }
    }

}