Java Code Examples for org.eclipse.jgit.lib.Ref

The following examples show how to use org.eclipse.jgit.lib.Ref. These examples are extracted from open source projects. 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 Project: cf-butler   Source File: GitClient.java    License: Apache License 2.0 6 votes vote down vote up
public RevCommit getLatestCommit(Repository repo) throws IOException, GitAPIException {
	RevCommit latestCommit = null;
	int inc = 0;
	try(
		Git git = new Git(repo);
		RevWalk walk = new RevWalk(repo);
	) {
		List<Ref> branches = git.branchList().call();
		for(Ref branch : branches) {
			RevCommit commit = walk.parseCommit(branch.getObjectId());
			if (inc == 0)
				latestCommit = commit;
			if(commit.getAuthorIdent().getWhen().compareTo(latestCommit.getAuthorIdent().getWhen()) > 0)
				latestCommit = commit;
			inc++;
		}
	}
	return latestCommit;
}
 
Example 2
Source Project: git-client-plugin   Source File: JGitAPIImpl.java    License: MIT License 6 votes vote down vote up
/** {@inheritDoc} */
   @Override
   public Set<String> getRefNames(String refPrefix) throws GitException, InterruptedException {
if (refPrefix.isEmpty()) {
    refPrefix = RefDatabase.ALL;
} else {
    refPrefix = refPrefix.replace(' ', '_');
}
try (Repository repo = getRepository()) {
    List<Ref> refList = repo.getRefDatabase().getRefsByPrefix(refPrefix);
    Set<String> refs = new HashSet<>(refList.size());
    for (Ref ref : refList) {
	refs.add(ref.getName());
    }
    return refs;
} catch (IOException e) {
    throw new GitException("Error retrieving refs with prefix " + refPrefix, e);
}
   }
 
Example 3
Source Project: verigreen   Source File: JGitOperator.java    License: Apache License 2.0 6 votes vote down vote up
boolean isRefBehind( Ref behind, Ref tracking ) throws IOException {
  RevWalk walk = new RevWalk( _git.getRepository() );
  try {
    RevCommit behindCommit = walk.parseCommit( behind.getObjectId() );
    RevCommit trackingCommit = walk.parseCommit( tracking.getObjectId() );
    walk.setRevFilter( RevFilter.MERGE_BASE );
    walk.markStart( behindCommit );
    walk.markStart( trackingCommit );
    RevCommit mergeBase = walk.next();
    walk.reset();
    walk.setRevFilter( RevFilter.ALL );
    int aheadCount = RevWalkUtils.count( walk, behindCommit, mergeBase );
    int behindCount = RevWalkUtils.count( walk, trackingCommit, mergeBase );
    
    return behindCount > aheadCount ? true:false;
  } catch (Throwable e) {
         throw new RuntimeException(String.format(
                 "Failed to check if [%s] behind [%s]",
                 behind,
                 tracking), e);
     } 
  finally {
    walk.dispose();
  }
}
 
Example 4
Source Project: git-client-plugin   Source File: CliGitAPIImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Returns the remote branches defined in this repository.
 *
 * @return {@link java.util.Set} of remote branches in this repository
 * @throws hudson.plugins.git.GitException if underlying git operation fails
 * @throws java.lang.InterruptedException if interrupted
 */
@Override
public Set<Branch> getRemoteBranches() throws GitException, InterruptedException {
    try (Repository db = getRepository()) {
        Map<String, Ref> refs = db.getAllRefs();
        Set<Branch> branches = new HashSet<>();

        for(Ref candidate : refs.values()) {
            if(candidate.getName().startsWith(Constants.R_REMOTES)) {
                Branch buildBranch = new Branch(candidate);
                if (!GitClient.quietRemoteBranches) {
                    listener.getLogger().println("Seen branch in repository " + buildBranch.getName());
                }
                branches.add(buildBranch);
            }
        }

        if (branches.size() == 1) {
            listener.getLogger().println("Seen 1 remote branch");
        } else {
            listener.getLogger().println(MessageFormat.format("Seen {0} remote branches", branches.size()));
        }

        return branches;
    }
}
 
Example 5
Source Project: Refactoring-Bot   Source File: GitService.java    License: MIT License 6 votes vote down vote up
/**
 * This method creates a new branch.
 * 
 * @param gitConfig
 * @param branchName
 * @param origin
 * @throws BotRefactoringException
 * @throws GitWorkflowException
 */
public void createBranch(GitConfiguration gitConfig, String branchName, String newBranch, String origin)
		throws BotRefactoringException, GitWorkflowException {
	try (Git git = Git.open(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))) {
		// Try to create new branch
		@SuppressWarnings("unused")
		Ref ref = git.checkout().setCreateBranch(true).setName(newBranch)
				.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
				.setStartPoint(origin + "/" + branchName).call();
		// Pull data
		git.pull();
		// If branch already exists
	} catch (RefAlreadyExistsException r) {
		logger.error(r.getMessage(), r);
		throw new BotRefactoringException(
				"Issue was already refactored in the past! The bot database might have been resetted but not the fork itself.");
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw new GitWorkflowException("Branch with the name " + "'" + newBranch + "' could not be created!");
	}
}
 
Example 6
Source Project: onedev   Source File: RevisionSelector.java    License: MIT License 6 votes vote down vote up
public RevisionSelector(String id, IModel<Project> projectModel, @Nullable String revision, boolean canCreateRef) {
	super(id);
	
	Preconditions.checkArgument(revision!=null || !canCreateRef);

	this.projectModel = projectModel;
	this.revision = revision;		
	if (canCreateRef) {
		Project project = projectModel.getObject();
		canCreateBranch = SecurityUtils.canCreateBranch(project, Constants.R_HEADS);						
		canCreateTag = SecurityUtils.canCreateTag(project, Constants.R_TAGS);						
	} else {
		canCreateBranch = false;
		canCreateTag = false;
	}
	if (revision != null) {
		Ref ref = projectModel.getObject().getRef(revision);
		branchesActive = ref == null || GitUtils.ref2tag(ref.getName()) == null;
	} else {
		branchesActive = true;
	}
	
	refs = findRefs();
}
 
Example 7
Source Project: onedev   Source File: DefaultCommitInfoManager.java    License: MIT License 6 votes vote down vote up
private void collect(Project project) {
	List<CollectingWork> works = new ArrayList<>();
	try (RevWalk revWalk = new RevWalk(project.getRepository())) {
		Collection<Ref> refs = new ArrayList<>();
		refs.addAll(project.getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS));
		refs.addAll(project.getRepository().getRefDatabase().getRefsByPrefix(Constants.R_TAGS));

		for (Ref ref: refs) {
			RevObject revObj = revWalk.peel(revWalk.parseAny(ref.getObjectId()));
			if (revObj instanceof RevCommit)
				works.add(new CollectingWork(PRIORITY, (RevCommit) revObj, ref.getName()));
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}

	Collections.sort(works, new CommitTimeComparator());
	
	for (CollectingWork work: works)
		batchWorkManager.submit(getBatchWorker(project.getId()), work);
}
 
Example 8
Source Project: onedev   Source File: Project.java    License: MIT License 6 votes vote down vote up
public RevCommit getLastCommit() {
	if (lastCommitHolder == null) {
		RevCommit lastCommit = null;
		try {
			for (Ref ref: getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS)) {
				RevCommit commit = getRevCommit(ref.getObjectId(), false);
				if (commit != null) {
					if (lastCommit != null) {
						if (commit.getCommitTime() > lastCommit.getCommitTime())
							lastCommit = commit;
					} else {
						lastCommit = commit;
					}
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		lastCommitHolder = Optional.fromNullable(lastCommit);
	}
	return lastCommitHolder.orNull();
}
 
Example 9
/**
 * 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 10
Source Project: onedev   Source File: CreateTagAction.java    License: MIT License 6 votes vote down vote up
@Override
public void execute(Build build) {
	PersonIdent tagIdent = OneDev.getInstance(UserManager.class).getSystem().asPerson();
	Project project = build.getProject();
	String tagName = getTagName();

	CreateTagAction instance = new CreateTagAction();
	instance.setTagName(tagName);
	if (project.getBuildSetting().isActionAuthorized(build, instance)) {
		Ref tagRef = project.getTagRef(tagName);
		if (tagRef != null) {
			OneDev.getInstance(ProjectManager.class).deleteTag(project, tagName);
			project.createTag(tagName, build.getCommitHash(), tagIdent, getTagMessage());
		} else {
			project.createTag(tagName, build.getCommitHash(), tagIdent, getTagMessage());
		}
	} else {
		throw new OneException("Creating tag '" + tagName + "' is not allowed in this build");
	}
}
 
Example 11
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 12
Source Project: super-cloudops   Source File: JgitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tagListTest() throws IOException, GitAPIException {
    Git git = Git.open(new File(gitPath));
    /*ListTagCommand listTagCommand = git.tagList();
    List<Ref> call = listTagCommand.call();
    for(Ref ref : call){
        System.out.println(ref.getName());
    }*/

    //
    FetchCommand fetchCommand = git.fetch().setTagOpt(TagOpt.FETCH_TAGS);
    fetchCommand.setCredentialsProvider(usernamePasswordCredentialsProvider);
    fetchCommand.call();
    List<Ref> tags = git.tagList().call();
    if(tags != null && tags.size() > 0) {
        for(Ref tag : tags) {
            System.out.println(tag.getName());
        }
    }
}
 
Example 13
Source Project: apidiff   Source File: GitServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>(); 
	for (Ref ref : repository.getAllRefs().values()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			currentRemoteRefs.add(ref.getObjectId());
		}
	}
	
	List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);
	
	RevWalk walk = new RevWalk(repository);
	for (TrackingRefUpdate newRef : newRemoteRefs) {
		if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
			walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
		}
	}
	for (ObjectId oldRef : currentRemoteRefs) {
		walk.markUninteresting(walk.parseCommit(oldRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 14
Source Project: netbeans   Source File: PullCommand.java    License: Apache License 2.0 6 votes vote down vote up
private String findRemoteBranchName () throws GitException {
    Ref ref = null;
    try {
        ref = getRepository().findRef(branchToMerge);
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    if (ref != null) {
        for (String s : refSpecs) {
            RefSpec spec = new RefSpec(s);
            if (spec.matchDestination(ref)) {
                spec = spec.expandFromDestination(ref);
                String refName = spec.getSource();
                if (refName.startsWith(Constants.R_HEADS)) {
                    return refName.substring(Constants.R_HEADS.length());
                }
            }
        }
    }
    return branchToMerge;
}
 
Example 15
Source Project: jgitver   Source File: VersionStrategy.java    License: Apache License 2.0 6 votes vote down vote up
protected Version getBaseVersionAndRegisterMetadata(Commit base, Ref tagToUse) {
    Version baseVersion = Version.DEFAULT_VERSION;

    if (tagToUse != null) {
        String tagName = GitUtils.tagNameFromRef(tagToUse);
        baseVersion = versionFromTag(tagToUse);
        TagType tagType = computeTagType(tagToUse, maxVersionTag(base.getAnnotatedTags()).orElse(null));

        getRegistrar().registerMetadata(Metadatas.BASE_TAG_TYPE, tagType.name());
        getRegistrar().registerMetadata(Metadatas.BASE_TAG, tagName);
    }

    getRegistrar().registerMetadata(Metadatas.BASE_VERSION, baseVersion.toString());
    getRegistrar().registerMetadata(Metadatas.CURRENT_VERSION_MAJOR, Integer.toString(baseVersion.getMajor()));
    getRegistrar().registerMetadata(Metadatas.CURRENT_VERSION_MINOR, Integer.toString(baseVersion.getMinor()));
    getRegistrar().registerMetadata(Metadatas.CURRENT_VERSION_PATCH, Integer.toString(baseVersion.getPatch()));

    return baseVersion;
}
 
Example 16
Source Project: fabric8-forge   Source File: RepositoryResource.java    License: Apache License 2.0 6 votes vote down vote up
protected ObjectId getBranchObjectId(Git git) {
    Ref branchRef = null;
    try {
        String branchRevName = "refs/heads/" + branch;
        List<Ref> branches = git.branchList().call();
        for (Ref ref : branches) {
            String revName = ref.getName();
            if (Objects.equals(branchRevName, revName)) {
                branchRef = ref;
                break;
            }
        }
    } catch (GitAPIException e) {
        LOG.warn("Failed to find branches " + e, e);
    }

    ObjectId branchObjectId = null;
    if (branchRef != null) {
        branchObjectId = branchRef.getObjectId();
    }
    return branchObjectId;
}
 
Example 17
Source Project: centraldogma   Source File: GitRepository.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static void doRefUpdate(org.eclipse.jgit.lib.Repository jGitRepository, RevWalk revWalk,
                        String ref, ObjectId commitId) throws IOException {

    if (ref.startsWith(Constants.R_TAGS)) {
        final Ref oldRef = jGitRepository.exactRef(ref);
        if (oldRef != null) {
            throw new StorageException("tag ref exists already: " + ref);
        }
    }

    final RefUpdate refUpdate = jGitRepository.updateRef(ref);
    refUpdate.setNewObjectId(commitId);

    final Result res = refUpdate.update(revWalk);
    switch (res) {
        case NEW:
        case FAST_FORWARD:
            // Expected
            break;
        default:
            throw new StorageException("unexpected refUpdate state: " + res);
    }
}
 
Example 18
Source Project: spring-cloud-release-tools   Source File: GitRepo.java    License: 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 19
Source Project: verigreen   Source File: JGitOperator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String createBranch(String commitId, String branchName) {
    
    Ref result = null;
    CreateBranchCommand branchCreate = _git.branchCreate();
    branchCreate.setName(branchName);
    branchCreate.setStartPoint(commitId);
    try {
        result = branchCreate.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format(
                "Failed creating branch: %s for commit [%s]",
                branchName,
                commitId), e);
    }
    
    return result.getName();
}
 
Example 20
Source Project: gocd   Source File: ConfigRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrowExceptionWhenThereIsMergeConflict() throws Exception {
    String original = "first\nsecond\n";
    String nextUpdate = "1st\nsecond\n";
    String latestUpdate = "2nd\nsecond\n";
    configRepo.checkin(goConfigRevision(original, "md5-1"));
    configRepo.checkin(goConfigRevision(nextUpdate, "md5-2"));
    RevCommit currentRevCommitOnMaster = configRepo.getCurrentRevCommit();
    try {
        configRepo.getConfigMergedWithLatestRevision(goConfigRevision(latestUpdate, "md5-3"), "md5-1");
        fail("should have bombed for merge conflict");
    } catch (ConfigMergeException e) {
        assertThat(e.getMessage(), is(ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH));
    }

    List<Ref> branches = getAllBranches();
    assertThat(branches.size(), is(1));
    assertThat(branches.get(0).getName().endsWith("master"), is(true));
    assertThat(configRepo.getCurrentRevCommit(), is(currentRevCommitOnMaster));
}
 
Example 21
Source Project: Stringlate   Source File: GitWrapper.java    License: 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 22
Source Project: orion.server   Source File: RemoteBranch.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Ref findRef() {
	try {
		Set<String> configNames = getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
		for (String configName : configNames) {
			if (configName.equals(remote.getName())) {
				final String fullName = getName(true, false);
				Ref ref = db.getRefDatabase().getRef(fullName);
				if (ref != null && !ref.isSymbolic()) {
					return ref;
				}
			}
		}
	} catch (IOException e) {
		// ignore, return null
	}
	return null;
}
 
Example 23
Source Project: git-client-plugin   Source File: JGitAPIImpl.java    License: MIT License 6 votes vote down vote up
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error")
private Set<String> listRemoteBranches(String remote) throws NotSupportedException, TransportException, URISyntaxException {
    Set<String> branches = new HashSet<>();
    try (final Repository repo = getRepository()) {
        StoredConfig config = repo.getConfig();
        try (final Transport tn = Transport.open(repo, new URIish(config.getString("remote",remote,"url")))) {
            tn.setCredentialsProvider(getProvider());
            try (final FetchConnection c = tn.openFetch()) {
                for (final Ref r : c.getRefs()) {
                    if (r.getName().startsWith(R_HEADS))
                        branches.add("refs/remotes/"+remote+"/"+r.getName().substring(R_HEADS.length()));
                }
            }
        }
    }
    return branches;
}
 
Example 24
Source Project: submarine   Source File: GitUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void branchCreateAndCheckout() {
  if (token == null) {
    LOG.warn("Token not set!");
    return;
  } else {
    gitUtils.commit(LOCALPATH, "add new file.");
    Ref ref = gitUtils.branchCreate(LOCALPATH, BRANCHNAME);
    assertEquals(true, ref.getName().endsWith(BRANCHNAME));

    ref = gitUtils.checkout(LOCALPATH, BRANCHNAME);
    assertEquals(true, ref.getName().endsWith(BRANCHNAME));
  }
}
 
Example 25
Source Project: MergeProcessor   Source File: GitMergeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the commit message for the merge unit.
 */
private void evaluteCommitMessage() {
	final String localBranch = getLocalSourceBranch();
	if (localBranch == null) {
		return;
	}
	try {
		final List<Ref> branchListResult = repo.branchList().call();
		final boolean localBranchExists = branchListResult.stream()
				.anyMatch(ref -> ref.getName().endsWith(localBranch));
		CheckoutCommand branchCmd = repo.checkout().setName(localBranch);
		if (!localBranchExists) {
			branchCmd = branchCmd.setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
					.setStartPoint(mergeUnit.getBranchSource());
		}
		branchCmd.call();

		final ObjectId id = ObjectId.fromString(mergeUnit.getRevisionInfo());
		commitMessage = repo.log().add(id).call().iterator().next().getFullMessage();
		/*
		 * Remove merge processor commit information, if the commmit is done by merge
		 * processor e.g. MP [29c64cf540d8f3ea116c3683eade862c3d996dfb] V1.1 -> master:
		 * (2018-03-06 12:17:22)
		 */
		commitMessage = commitMessage.replaceAll("MP \\[[A-Za-z0-9]*\\] .* -> .*: \\(.*\\) ", ""); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (GitAPIException | MissingObjectException | IncorrectObjectTypeException e) {
		exception = new MergeUnitException(String.format("Could not checkout branch '%s'", localBranch), e); //$NON-NLS-1$
	}
}
 
Example 26
Source Project: ant-git-tasks   Source File: TagListTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
        try {
                List<Ref> tagRefList = git.tagList().call();
                processReferencesAndOutput(tagRefList);
        } catch (GitAPIException e) {
                throw new GitBuildException(MESSAGE_TAG_LIST_FAILED, e);
        }
}
 
Example 27
protected void createTemporaryBranch(String site, Git git) throws GitAPIException {
    List<Ref> branches = git.branchList().call();
    if(branches.stream().anyMatch(b -> b.getName().contains(siteUpgradeBranch))) {
        logger.debug("Temporary branch already exists, changes will be discarded");
        deleteTemporaryBranch(git);
    }
    logger.debug("Creating temporary branch {0} for site {1}", siteUpgradeBranch, site);
    git.branchCreate().setName(siteUpgradeBranch).call();
}
 
Example 28
Source Project: Jpom   Source File: GitUtil.java    License: 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 29
Source Project: ParallelGit   Source File: TagUtilsTagCommitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tagHeadCommit_theResultTagShouldPointToTheHeadCommit() throws IOException {
  writeSomethingToCache();
  AnyObjectId expected = commit();
  RepositoryUtils.detachRepositoryHead(repo, expected);
  Ref tag = TagUtils.tagHeadCommit("test_tag", repo);
  assertEquals(expected, tag.getPeeledObjectId());
}
 
Example 30
Source Project: gradle-gitsemver   Source File: Tags.java    License: Apache License 2.0 5 votes vote down vote up
private static ObjectId getIdForTag(Repository repo, Map.Entry<String, Ref> tag) {
    Ref ref = repo.peel(tag.getValue());
    if (ref.getPeeledObjectId() == null) {
        return ref.getObjectId();
    } else {
        return ref.getPeeledObjectId();
    }
}