Java Code Examples for org.eclipse.jgit.lib.Ref#getObjectId()

The following examples show how to use org.eclipse.jgit.lib.Ref#getObjectId() . 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: Project.java    From onedev with MIT License 6 votes vote down vote up
@Nullable
public String getDefaultBranch() {
	if (defaultBranchOptional == null) {
		try {
			Ref headRef = getRepository().findRef("HEAD");
			if (headRef != null 
					&& headRef.isSymbolic() 
					&& headRef.getTarget().getName().startsWith(Constants.R_HEADS) 
					&& headRef.getObjectId() != null) {
				defaultBranchOptional = Optional.of(Repository.shortenRefName(headRef.getTarget().getName()));
			} else {
				defaultBranchOptional = Optional.absent();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	return defaultBranchOptional.orNull();
}
 
Example 2
Source File: StudioNodeSyncGlobalRepoTask.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
        IOException, ServiceLayerException {
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(Constants.MASTER);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS + Constants.MASTER);
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            mergeCommand.call();
        }
    }

    Files.delete(tempKey);
}
 
Example 3
Source File: Log.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
static Map<ObjectId, Map<String, Ref>> getCommitToTagMap(URI cloneLocation, Repository db) throws MissingObjectException, IOException {
	HashMap<ObjectId, Map<String, Ref>> commitToTag = new HashMap<ObjectId, Map<String, Ref>>();
	for (Entry<String, Ref> tag : db.getTags().entrySet()) {
		Ref ref = db.peel(tag.getValue());
		ObjectId commitId = ref.getPeeledObjectId();
		if (commitId == null)
			commitId = ref.getObjectId();

		Map<String, Ref> tags = commitToTag.get(commitId);
		if (tags != null) {
			tags.put(tag.getKey(), tag.getValue());
		} else {
			tags = new HashMap<String, Ref>();
			tags.put(tag.getKey(), tag.getValue());
			commitToTag.put(commitId, tags);
		}
	}
	return commitToTag;
}
 
Example 4
Source File: RepositoryResource.java    From fabric8-forge with 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 5
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Java 11 spotbugs error")
public ObjectId getHeadRev(String remoteRepoUrl, String branchSpec) throws GitException {
    try (Repository repo = openDummyRepository();
         final Transport tn = Transport.open(repo, new URIish(remoteRepoUrl))) {
        final String branchName = extractBranchNameFromBranchSpec(branchSpec);
        String regexBranch = createRefRegexFromGlob(branchName);

        tn.setCredentialsProvider(getProvider());
        try (FetchConnection c = tn.openFetch()) {
            for (final Ref r : c.getRefs()) {
                if (r.getName().matches(regexBranch)) {
                    return r.getPeeledObjectId() != null ? r.getPeeledObjectId() : r.getObjectId();
                }
            }
        }
    } catch (IOException | URISyntaxException | IllegalStateException e) {
        throw new GitException(e);
    }
    return null;
}
 
Example 6
Source File: GitBasedArtifactRepository.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if an existing local repository is a valid git repository
 *
 * @param gitRepoCtx RepositoryContext instance
 * @return true if a valid git repo, else false
 */
private static boolean isValidGitRepo(RepositoryContext gitRepoCtx) {

    // check if has been marked as cloned before
    if (gitRepoCtx.cloneExists()) {
        // repo is valid
        return true;
    }

    for (Ref ref : gitRepoCtx.getLocalRepo().getAllRefs().values()) { //check if has been previously cloned successfully, not empty
        if (ref.getObjectId() == null)
            continue;
        return true;
    }

    return false;
}
 
Example 7
Source File: GitRepo.java    From git-changelog-lib with Apache License 2.0 6 votes vote down vote up
public ObjectId getRef(final String fromRef) throws GitChangelogRepositoryException {
  try {
    for (final Ref foundRef : getAllRefs().values()) {
      if (foundRef.getName().endsWith(fromRef)) {
        final Ref ref = getAllRefs().get(foundRef.getName());
        final Ref peeledRef = this.repository.peel(ref);
        if (peeledRef.getPeeledObjectId() != null) {
          return peeledRef.getPeeledObjectId();
        } else {
          return ref.getObjectId();
        }
      }
    }
  } catch (final Exception e) {
    throw new GitChangelogRepositoryException(fromRef + " not found in:\n" + toString(), e);
  }
  throw new GitChangelogRepositoryException(fromRef + " not found in:\n" + toString());
}
 
Example 8
Source File: GitUtil.java    From apigee-deploy-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
	 * IMP NOTE: Tag number will be displayed only if git tags are peeled manually using the command "git gc"
	 * @return
	 */
	public  String getTagNameForWorkspaceHeadRevision() {
		String headRevision = getWorkspaceHeadRevisionString();
		
		Map<String, Ref> tags = git.getRepository().getAllRefs();
		for (Ref tagRef : tags.values()) {
			String tagName = tagRef.getName();
			ObjectId obj = tagRef.getPeeledObjectId();
			if (obj == null) obj = tagRef.getObjectId();
//			 System.out.println(">>>>>>>>>>>>>>>>>" + tagRef.getName() + "," +
//			 obj.getName() +"," + headRevision  );
			if (headRevision.equals(obj.getName())) {
				if (tagName.contains("/tags/")) {
					int lastSlashIndex = tagName.lastIndexOf("/");
					if (lastSlashIndex > 0) {
						tagName = tagName.substring(lastSlashIndex + 1);
						return tagName;
					}
				}
			}

		}
		return null;
	}
 
Example 9
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Map<String, ObjectId> getRemoteReferences(String url, String pattern, boolean headsOnly, boolean tagsOnly)
        throws GitException, InterruptedException {
    Map<String, ObjectId> references = new HashMap<>();
    String regexPattern = null;
    if (pattern != null) {
        regexPattern = createRefRegexFromGlob(pattern);
    }
    try (Repository repo = openDummyRepository()) {
        LsRemoteCommand lsRemote = new LsRemoteCommand(repo);
        if (headsOnly) {
            lsRemote.setHeads(headsOnly);
        }
        if (tagsOnly) {
            lsRemote.setTags(tagsOnly);
        }
        lsRemote.setRemote(url);
        lsRemote.setCredentialsProvider(getProvider());
        Collection<Ref> refs = lsRemote.call();
            for (final Ref r : refs) {
                final String refName = r.getName();
                final ObjectId refObjectId =
                        r.getPeeledObjectId() != null ? r.getPeeledObjectId() : r.getObjectId();
                if (regexPattern != null) {
                    if (refName.matches(regexPattern)) {
                        references.put(refName, refObjectId);
                    }
                } else {
                    references.put(refName, refObjectId);
                }
            }
    } catch (JGitInternalException | GitAPIException | IOException e) {
        throw new GitException(e);
    }
    return references;
}
 
Example 10
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 11
Source File: GitRepos.java    From gradle-gitsemver with Apache License 2.0 5 votes vote down vote up
public static ObjectId getHeadObjectId(Repository repo) {
    Ref headRef = repo.getAllRefs().get("HEAD");
    if (headRef == null) {
        throw new SemverGitflowPlugin.VersionApplicationException(
                "Project is not in a Git repository. Cannot use semver versioning in a non repository.");
    }
    return headRef.getObjectId();
}
 
Example 12
Source File: StudioNodeSyncSandboxTask.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
        IOException, ServiceLayerException {
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(REPO_SANDBOX_BRANCH);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS +
                    studioConfiguration.getProperty(REPO_SANDBOX_BRANCH));
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            MergeResult result = mergeCommand.call();
            if (result.getMergeStatus().isSuccessful()) {
                deploymentService.syncAllContentToPreview(siteId, true);
            }
        }
    }

    Files.delete(tempKey);
}
 
Example 13
Source File: GitUtilities.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if an existing local repository is a valid git repository
 *
 * @param repository Repository instance
 * @return true if a valid git repo, else false
 */
public static boolean isValidGitRepo (Repository repository) {

    for (Ref ref : repository.getAllRefs().values()) { //check if has been previously cloned successfully, not empty
        if (ref.getObjectId() == null)
            continue;
        return true;
    }

    return false;
}
 
Example 14
Source File: Tags.java    From gradle-gitsemver with Apache License 2.0 5 votes vote down vote up
private static ObjectId getObjectIdForTag(Repository repo, String tag) {
    Ref ref = repo.getTags().get(tag);
    repo.peel(ref);
    if (ref.getPeeledObjectId() == null) {
        return ref.getObjectId();
    } else {
        return ref.getPeeledObjectId();
    }
}
 
Example 15
Source File: Tags.java    From gradle-gitsemver with 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();
    }
}
 
Example 16
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public int countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example 17
Source File: GitServiceImpl.java    From apidiff with MIT License 5 votes vote down vote up
@Override
public Integer countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example 18
Source File: JgitTests.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
protected static String getBranchName(Ref ref) {
    String name = ref.getName();
    if ("HEAD".equals(trimToEmpty(name))) {
        ObjectId objectId = ref.getObjectId();
        name = objectId.getName();
    } else {
        int index = name.lastIndexOf("/");
        name = name.substring(index + 1);
    }
    return name;
}
 
Example 19
Source File: GenericBasedGitVcsOperator.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Get (local) branch name.
 *
 * @param ref
 * @return
 */
protected static String getBranchName(Ref ref) {
    String name = ref.getName();
    if ("HEAD".equals(trimToEmpty(name))) {
        ObjectId objectId = ref.getObjectId();
        name = objectId.getName();
    } else {
        int index = name.lastIndexOf("/");
        name = name.substring(index + 1);
    }
    return name;
}
 
Example 20
Source File: MergeMessageFormatter.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Construct the merge commit message.
 *
 * @param refsToMerge
 *            the refs which will be merged
 * @param target
 *            the branch ref which will be merged into
 * @return merge commit message
 */
public String format(List<Ref> refsToMerge, Ref target) {
	StringBuilder sb = new StringBuilder();
	sb.append("Merge "); //$NON-NLS-1$

	List<String> branches = new ArrayList<>();
	List<String> remoteBranches = new ArrayList<>();
	List<String> tags = new ArrayList<>();
	List<String> commits = new ArrayList<>();
	List<String> others = new ArrayList<>();
	for (Ref ref : refsToMerge) {
		if (ref.getName().startsWith(Constants.R_HEADS)) {
			branches.add("'" + Repository.shortenRefName(ref.getName()) //$NON-NLS-1$
					+ "'"); //$NON-NLS-1$
		} else if (ref.getName().startsWith(Constants.R_REMOTES)) {
			remoteBranches.add("'" //$NON-NLS-1$
					+ Repository.shortenRefName(ref.getName()) + "'"); //$NON-NLS-1$
		} else if (ref.getName().startsWith(Constants.R_TAGS)) {
			tags.add("'" + Repository.shortenRefName(ref.getName()) + "'"); //$NON-NLS-1$ //$NON-NLS-2$
		} else {
			ObjectId objectId = ref.getObjectId();
			if (objectId != null && ref.getName().equals(objectId.getName())) {
				commits.add("'" + ref.getName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
			} else {
				others.add(ref.getName());
			}
		}
	}

	List<String> listings = new ArrayList<>();

	if (!branches.isEmpty())
		listings.add(joinNames(branches, "branch", "branches")); //$NON-NLS-1$//$NON-NLS-2$

	if (!remoteBranches.isEmpty())
		listings.add(joinNames(remoteBranches, "remote-tracking branch", //$NON-NLS-1$
				"remote-tracking branches")); //$NON-NLS-1$

	if (!tags.isEmpty())
		listings.add(joinNames(tags, "tag", "tags")); //$NON-NLS-1$ //$NON-NLS-2$

	if (!commits.isEmpty())
		listings.add(joinNames(commits, "commit", "commits")); //$NON-NLS-1$ //$NON-NLS-2$

	if (!others.isEmpty())
		listings.add(StringUtils.join(others, ", ", " and ")); //$NON-NLS-1$ //$NON-NLS-2$

	sb.append(StringUtils.join(listings, ", ")); //$NON-NLS-1$

	String targetName = target.getLeaf().getName();
	if (!targetName.equals(Constants.R_HEADS + Constants.MASTER)) {
		String targetShortName = Repository.shortenRefName(targetName);
		sb.append(" into " + targetShortName); //$NON-NLS-1$
	}

	return sb.toString();
}