org.eclipse.jgit.api.ListBranchCommand Java Examples

The following examples show how to use org.eclipse.jgit.api.ListBranchCommand. 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: BranchListTask.java    From ant-git-tasks with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the listing mode
 *
 * @antdoc.notrequired
 * @param listMode - optional: corresponds to the -r/-a options; by default, only local branches will be listed
 */
public void setListMode(String listMode) {
        if (!GitTaskUtils.isNullOrBlankString(listMode)) {
                try {
                        this.listMode = ListBranchCommand.ListMode.valueOf(listMode);
                }
                catch (IllegalArgumentException e) {
                        ListBranchCommand.ListMode[] listModes = ListBranchCommand.ListMode.values();

                        List<String> listModeValidValues = new ArrayList<String>(listModes.length);

                        for (ListBranchCommand.ListMode aListMode : listModes) {
                                listModeValidValues.add(aListMode.name());
                        }

                        String validModes = listModeValidValues.toString();

                        throw new BuildException(String.format("Valid listMode options are: %s.", validModes));
                }
        }
}
 
Example #2
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Look for a tag with the given name, and if not found looks for a branch.
 */
private Optional<Ref> findTagOrBranchHeadRevision(Git git, String tagOrBranch)
		throws GitAPIException, IOException {
	if (tagOrBranch.equals("HEAD")) {
		return Optional.of(git.getRepository().exactRef(Constants.HEAD).getTarget());
	}
	final Optional<Ref> tag = git.tagList().call().stream()
			.filter(ref -> ref.getName().equals("refs/tags/" + tagOrBranch))
			.findFirst();
	if (tag.isPresent()) {
		return tag;
	}

	return git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()
			.stream().filter(ref -> ref.getName().equals("refs/heads/" + tagOrBranch))
			.findFirst();
}
 
Example #3
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private Map<String, List<String>>  getRemoteBranches(Git git) throws GitAPIException {
    List<Ref> resultRemoteBranches = git.branchList()
            .setListMode(ListBranchCommand.ListMode.REMOTE)
            .call();
    Map<String, List<String>> remoteBranches = new HashMap<String, List<String>>();
    for (Ref remoteBranchRef : resultRemoteBranches) {
        String branchFullName = remoteBranchRef.getName().replace(Constants.R_REMOTES, "");
        String remotePart = StringUtils.EMPTY;
        String branchNamePart = StringUtils.EMPTY;
        int slashIndex = branchFullName.indexOf("/");
        if (slashIndex > 0) {
            remotePart = branchFullName.substring(0, slashIndex);
            branchNamePart = branchFullName.substring(slashIndex + 1);
        }

        if (!remoteBranches.containsKey(remotePart)) {
            remoteBranches.put(remotePart, new ArrayList<String>());
        }
        remoteBranches.get(remotePart).add(branchNamePart);
    }
    return remoteBranches;
}
 
Example #4
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Clone GIT repository from sourceforge.
 *
 * @param gitDirectory The directory of Git.
 */
private void gitClone(File gitDirectory) {
    try {
        git = Git.cloneRepository()
                .setDirectory(gitDirectory)
                .setURI(env.gitURI())
                //.setURI("http://git.code.sf.net/p/neembuuuploader/gitcode")
                .setProgressMonitor(new TextProgressMonitor()).call();

        for (Ref f : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            git.checkout().setName(f.getName()).call();
            System.out.println("checked out branch " + f.getName()
                    + ". HEAD: " + git.getRepository().getRef("HEAD"));
        }
        // try to checkout branches by specifying abbreviated names
        git.checkout().setName("master").call();
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #5
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Clone GIT repository from sourceforge.
 *
 * @param gitDirectory The directory of Git.
 */
private void gitClone(File gitDirectory) {
    try {
        git = Git.cloneRepository()
                .setDirectory(gitDirectory)
                .setURI("http://git.code.sf.net/p/neembuuuploader/gitcode")
                .setProgressMonitor(new TextProgressMonitor()).call();

        for (Ref f : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            git.checkout().setName(f.getName()).call();
            System.out.println("checked out branch " + f.getName()
                    + ". HEAD: " + git.getRepository().getRef("HEAD"));
        }
        // try to checkout branches by specifying abbreviated names
        git.checkout().setName("master").call();
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #6
Source File: GitWrapper.java    From Stringlate with MIT License 6 votes vote down vote up
public static ArrayList<String> getBranches(final File repo) {
    try {
        final List<Ref> refs = Git.open(repo)
                .branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();

        final ArrayList<String> result = new ArrayList<>();
        for (Ref ref : refs)
            result.add(ref.getName());

        return result;
    } catch (GitAPIException | IOException e) {
        e.printStackTrace();
    }

    return new ArrayList<>();
}
 
Example #7
Source File: GitUtil.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 获取仓库远程的所有分支
 *
 * @param url                 远程url
 * @param file                仓库clone到本地的文件夹
 * @param credentialsProvider 凭证
 * @return list
 * @throws GitAPIException api
 * @throws IOException     IO
 */
private static List<String> branchList(String url, File file, CredentialsProvider credentialsProvider) throws GitAPIException, IOException {
    try (Git git = initGit(url, file, credentialsProvider)) {
        //
        List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
        List<String> all = new ArrayList<>(list.size());
        list.forEach(ref -> {
            String name = ref.getName();
            if (name.startsWith(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME)) {
                all.add(name.substring((Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME).length() + 1));
            }
        });
        return all;
    } catch (TransportException t) {
        checkTransportException(t);
        throw t;
    }
}
 
Example #8
Source File: GetAvailableBranchesAdapter.java    From coderadar with MIT License 5 votes vote down vote up
private List<Branch> getBranches(Git git) throws GitAPIException {
  List<Branch> result = new ArrayList<>();
  for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
    String[] branchName = ref.getName().split("/");
    int length = branchName.length;
    String truncatedName = branchName[length - 1];
    if (result.stream().noneMatch(branch -> branch.getName().equals(truncatedName))) {
      result.add(new Branch().setName(truncatedName).setCommitHash(ref.getObjectId().getName()));
    }
  }
  return result;
}
 
Example #9
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
public Set<Branch> getBranchesInternal(ListBranchCommand.ListMode mode) throws GitException {
    try (Repository repo = getRepository()) {
        List<Ref> refs = git(repo).branchList().setListMode(mode).call();
        Set<Branch> branches = new HashSet<>(refs.size());
        for (Ref ref : refs) {
            branches.add(new Branch(ref));
        }
        return branches;
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #10
Source File: GitProctorCoreWithRepositoryTest.java    From proctor with Apache License 2.0 5 votes vote down vote up
/**
 * clone repo having master and test branch with only fetching refs of test branch
 */
@Test
public void testCloneRepositoryWithSingleBranch() throws Exception {
    final File workingDir = temporaryFolder.newFolder("testCloneRepositoryWithSingleBranch");
    final String branchName = "test";

    /* create branch test with one commit off master ***/
    remoteGit.checkout().setCreateBranch(true).setName(branchName).call();

    writeTrashFile(TEST_FILE_NAME, "test");
    remoteGit.add().addFilepattern(TEST_FILE_NAME).call();

    final String commitMessage = "Create a new branch";
    remoteGit.commit().setMessage(commitMessage).call();

    // Run cloneRepository with single branch
    final GitProctorCore gitProctorCore = new GitProctorCore(
            gitUrl,
            GIT_USERNAME,
            GIT_PASSWORD,
            TEST_DEFINITION_DIRECTORY,
            workingDir,
            branchName
    );

    final Git git = gitProctorCore.getGit();

    assertNotNull(git);
    final List<Ref> branchList = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    // should not contain master
    assertThat(branchList.stream().map(Ref::getName))
            .containsExactlyInAnyOrder("refs/heads/" + branchName, "refs/remotes/origin/test");

    final String localCommitMessage = git.log().call().iterator().next().getFullMessage();
    assertThat(localCommitMessage).isEqualTo(commitMessage);

    // should not throw any exceptions
    gitProctorCore.checkoutBranch(branchName);
}
 
Example #11
Source File: JGitEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private boolean containsBranch(Git git, String label, ListMode listMode)
		throws GitAPIException {
	ListBranchCommand command = git.branchList();
	if (listMode != null) {
		command.setListMode(listMode);
	}
	List<Ref> branches = command.call();
	for (Ref ref : branches) {
		if (ref.getName().endsWith("/" + label)) {
			return true;
		}
	}
	return false;
}
 
Example #12
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private boolean containsBranch(Git git, String label,
		ListBranchCommand.ListMode listMode) throws GitAPIException {
	ListBranchCommand command = git.branchList();
	if (listMode != null) {
		command.setListMode(listMode);
	}
	List<Ref> branches = command.call();
	for (Ref ref : branches) {
		if (ref.getName().endsWith("/" + label)) {
			return true;
		}
	}
	return false;
}
 
Example #13
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected List<String> doListBranches(Git git) throws Exception {
    SortedSet<String> names = new TreeSet<String>();
    List<Ref> call = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    for (Ref ref : call) {
        String name = ref.getName();
        int idx = name.lastIndexOf('/');
        if (idx >= 0) {
            name = name.substring(idx + 1);
        }
        if (name.length() > 0) {
            names.add(name);
        }
    }
    return new ArrayList<String>(names);
}
 
Example #14
Source File: GitCloner.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private void checkoutAllBranches(Repository repository) throws GitAPIException {
    final Git git = Git.wrap(repository);
    for (final Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call()) {
        final String refName = ref.getName();
        final String branchName = refName.substring(refName.lastIndexOf('/') + 1);
        try {
            git.checkout().setCreateBranch(true).setName(branchName).setStartPoint("origin/" + branchName).call();
        } catch (RefAlreadyExistsException e) {
            LOGGER.warning("Already exists, so ignoring " + e.getMessage());
        }
    }
}
 
Example #15
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
private boolean containsBranch(Git git, String label,
		ListBranchCommand.ListMode listMode) throws GitAPIException {
	ListBranchCommand command = git.branchList();
	if (listMode != null) {
		command.setListMode(listMode);
	}
	List<Ref> branches = command.call();
	for (Ref ref : branches) {
		if (ref.getName().endsWith("/" + label)) {
			return true;
		}
	}
	return false;
}
 
Example #16
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
boolean hasBranch(String branch) {
	try (Git git = this.gitFactory.open(file(this.basedir))) {
		List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL)
				.call();
		boolean present = refs.stream()
				.anyMatch(ref -> branch.equals(nameOfBranch(ref.getName())));
		if (log.isDebugEnabled()) {
			log.debug("Branch [{}] is present [{}]", branch, present);
		}
		return present;
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example #17
Source File: GitUtil.java    From Jpom with MIT License 5 votes vote down vote up
private static AnyObjectId getAnyObjectId(Git git, String branchName) throws GitAPIException {
    List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    for (Ref ref : list) {
        String name = ref.getName();
        if (name.startsWith(Constants.R_HEADS + branchName)) {
            return ref.getObjectId();
        }
    }
    return null;
}
 
Example #18
Source File: GitUtil.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 拉取对应分支最新代码
 *
 * @param url                 远程url
 * @param file                仓库路径
 * @param branchName          分支名
 * @param credentialsProvider 凭证
 * @throws IOException     IO
 * @throws GitAPIException api
 */
public static void checkoutPull(String url, File file, String branchName, CredentialsProvider credentialsProvider) throws IOException, GitAPIException {
    try (Git git = initGit(url, file, credentialsProvider)) {
        // 判断本地是否存在对应分支
        List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        boolean createBranch = true;
        for (Ref ref : list) {
            String name = ref.getName();
            if (name.startsWith(Constants.R_HEADS + branchName)) {
                createBranch = false;
                break;
            }
        }
        // 切换分支
        if (!StrUtil.equals(git.getRepository().getBranch(), branchName)) {
            git.checkout().
                    setCreateBranch(createBranch).
                    setName(branchName).
                    setForceRefUpdate(true).
                    setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).
                    call();
        }
        git.pull().setCredentialsProvider(credentialsProvider).call();
    } catch (TransportException t) {
        checkTransportException(t);
        throw t;
    }
}
 
Example #19
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
private boolean isBranch(Git git, String label) throws GitAPIException {
	return containsBranch(git, label, ListBranchCommand.ListMode.ALL);
}
 
Example #20
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@Test
public void testRefreshWithoutFetch() throws Exception {
	Git git = mock(Git.class);

	CloneCommand cloneCommand = mock(CloneCommand.class);
	when(cloneCommand.setURI(anyString())).thenReturn(cloneCommand);
	when(cloneCommand.setDirectory(any(File.class))).thenReturn(cloneCommand);
	when(cloneCommand.call()).thenReturn(git);

	MockGitFactory factory = new MockGitFactory(git, cloneCommand);

	StatusCommand statusCommand = mock(StatusCommand.class);
	CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
	Status status = mock(Status.class);
	Repository repository = mock(Repository.class, Mockito.RETURNS_DEEP_STUBS);
	StoredConfig storedConfig = mock(StoredConfig.class);
	Ref ref = mock(Ref.class);
	ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
	FetchCommand fetchCommand = mock(FetchCommand.class);
	FetchResult fetchResult = mock(FetchResult.class);
	Ref branch1Ref = mock(Ref.class);

	when(git.branchList()).thenReturn(listBranchCommand);
	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(git.checkout()).thenReturn(checkoutCommand);
	when(git.fetch()).thenReturn(fetchCommand);
	when(git.merge())
			.thenReturn(mock(MergeCommand.class, Mockito.RETURNS_DEEP_STUBS));
	when(repository.getConfig()).thenReturn(storedConfig);
	when(storedConfig.getString("remote", "origin", "url"))
			.thenReturn("http://example/git");
	when(statusCommand.call()).thenReturn(status);
	when(checkoutCommand.call()).thenReturn(ref);
	when(listBranchCommand.call()).thenReturn(Arrays.asList(branch1Ref));
	when(fetchCommand.call()).thenReturn(fetchResult);
	when(branch1Ref.getName()).thenReturn("origin/master");
	when(status.isClean()).thenReturn(true);

	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			new JGitEnvironmentProperties());
	repo.setGitFactory(factory);
	repo.setUri("http://somegitserver/somegitrepo");
	repo.setBasedir(this.basedir);

	// Set the refresh rate to 2 seconds and last update before 100ms. There should be
	// no remote repo fetch.
	repo.setLastRefresh(System.currentTimeMillis() - 100);
	repo.setRefreshRate(2);

	repo.refresh("master");

	// Verify no fetch but merge only.
	verify(git, times(0)).fetch();
	verify(git).merge();
}
 
Example #21
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 4 votes vote down vote up
private boolean isBranch(Git git, String label) throws GitAPIException {
	return containsBranch(git, label, ListBranchCommand.ListMode.ALL);
}
 
Example #22
Source File: ConfigRepositoryTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
private List<Ref> getAllBranches() throws GitAPIException {
    return configRepo.git().branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
}
 
Example #23
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 2 votes vote down vote up
/**
 * getBranches.
 *
 * @return a {@link java.util.Set} object.
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 */
@Override
public Set<Branch> getBranches() throws GitException {
    return getBranchesInternal(ListBranchCommand.ListMode.ALL);
}
 
Example #24
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 2 votes vote down vote up
/**
 * getRemoteBranches.
 *
 * @return a {@link java.util.Set} object.
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 */
@Override
public Set<Branch> getRemoteBranches() throws GitException {
    return getBranchesInternal(ListBranchCommand.ListMode.REMOTE);
}