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.ocpsoft.redoculous.model.impl.GitRepository.java

License:Open Source License

@Override
public Set<String> getRefs() {
    if (refs == null) {
        try {//from  w  w  w .  ja  va2 s .  c o m
            refs = new LinkedHashSet<String>();

            Git git = null;
            try {
                git = Git.open(getRepoDir());
                List<Ref> branches = git.branchList().setListMode(ListMode.ALL).call();
                refs.addAll(processRefs(branches));
                List<Ref> tags = git.tagList().call();
                refs.addAll(processRefs(tags));
            } finally {
                if (git != null) {
                    git.getRepository().close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(
                    "Failed to get list of active refs for repository [" + getUrl() + "] [" + getKey() + "]",
                    e);
        }
    }
    return refs;
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

private Set<String> getBranches(Git git, String hash) throws GitAPIException {

    if (!collectConfig.isCollectingBranches())
        return new HashSet<>();

    List<Ref> gitBranches = git.branchList().setContains(hash).call();
    Set<String> mappedBranches = gitBranches.stream()
            .map((ref) -> ref.getName().substring(ref.getName().lastIndexOf("/") + 1))
            .collect(Collectors.toSet());
    return mappedBranches;
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

private synchronized void deleteMMBranch(Git git) throws GitAPIException {
    List<Ref> refs = git.branchList().call();
    for (Ref r : refs) {
        if (r.getName().endsWith(BRANCH_MM)) {
            git.branchDelete().setBranchNames(BRANCH_MM).setForce(true).call();
            break;
        }/*from   w w w.  java 2  s .  com*/
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java

License:Apache License

private boolean containsBranch(Git git, String label, ListMode listMode) throws GitAPIException {
    ListBranchCommand command = git.branchList();
    if (listMode != null) {
        command.setListMode(listMode);/*from   www  .  j  a  va2s .  co m*/
    }
    List<Ref> branches = command.call();
    for (Ref ref : branches) {
        if (ref.getName().endsWith("/" + label)) {
            return true;
        }
    }
    return false;
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void testFetchException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenThrow(new InvalidRemoteException("invalid mock remote")); //here is our exception we are testing

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);//from  w  w  w .  j  a  v a 2s  .  co m
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", null);
    assertEquals(locations.getVersion(), newObjectId.getName());
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void testMergeException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.EMPTY_LIST);

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);//w  ww .  ja  v a2  s  .  co m
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

License:Apache License

@Test
public void testResetHardException() throws Exception {

    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment);
    this.repository.setGitFactory(factory);

    //refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true).thenReturn(false);

    //refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.EMPTY_LIST);

    //refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    //refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);// www .j a va  2 s .com
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);

    //refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing

    //refresh()->hardReset
    ResetCommand resetCommand = mock(ResetCommand.class);
    when(git.reset()).thenReturn(resetCommand);
    when(resetCommand.call()).thenReturn(ref);

    //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.getRef(anyString())).thenReturn(headRef);

    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);

    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
}

From source file:org.springframework.cloud.release.internal.git.GitRepo.java

License:Apache License

private boolean containsBranch(Git git, String label, ListBranchCommand.ListMode listMode)
        throws GitAPIException {
    ListBranchCommand command = git.branchList();
    if (listMode != null) {
        command.setListMode(listMode);/*from  w w w  . ja  v  a  2 s .co  m*/
    }
    List<Ref> branches = command.call();
    for (Ref ref : branches) {
        if (ref.getName().endsWith("/" + label)) {
            return true;
        }
    }
    return false;
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.BranchUtil.java

License:Apache License

public static void deleteUnfilteredBranches(final Repository repository, final List<String> branchesToKeep)
        throws GitAPIException {
    if (branchesToKeep == null || branchesToKeep.isEmpty()) {
        return;//from   w  w  w  . j a v a 2  s  . c om
    }

    final org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.wrap(repository);
    final String[] toDelete = git.branchList().call().stream().map(Ref::getName)
            .map(fullname -> fullname.substring(fullname.lastIndexOf('/') + 1))
            .filter(name -> !branchesToKeep.contains(name)).toArray(String[]::new);
    git.branchDelete().setBranchNames(toDelete).setForce(true).call();
}

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

License:Open Source License

protected static void checkOutBranch(Git git, String branch) throws GitAPIException, IOException {
    String currentBranch = git.getRepository().getBranch();
    if (currentBranch.equals(branch)) {
        log.info("already on branch: {}. will do a git pull", branch);
        PullResult pullResult = git.pull().call();
        log.debug("pull result: {}", pullResult);
        Preconditions.checkState(pullResult.isSuccessful());
        return;//w ww. j a  v a 2  s .  c  o m
    }

    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    /* refs will have name like these:
    refs/heads/master,
    refs/heads/trans,
    refs/heads/zanata,
    refs/remotes/origin/HEAD,
    refs/remotes/origin/master,
    refs/remotes/origin/trans,
    refs/remotes/origin/zanata
            
    where the local branches are: master, trans, zanata
    remote branches are: master, trans, 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 local branch exists and we are now on a different branch,
    // we delete it first then re-checkout
    if (localBranchRef.isPresent()) {
        log.debug("deleting local branch {}", branch);
        git.branchDelete().setBranchNames(branch).call();
    }

    if (remoteBranchRef.isPresent()) {
        // if remote branch exists, we create a new local branch based on it.
        git.checkout().setCreateBranch(true).setForce(true).setName(branch).setStartPoint("origin/" + branch)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    } else {
        // If branch does not exists in remote, create new local branch based on master branch.
        git.checkout().setCreateBranch(true).setForce(true).setName(branch).setStartPoint("origin/master")
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    }
    if (log.isDebugEnabled()) {
        log.debug("current branch is: {}", git.getRepository().getBranch());
    }
}