Example usage for org.eclipse.jgit.lib Repository resolve

List of usage examples for org.eclipse.jgit.lib Repository resolve

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository resolve.

Prototype

@Nullable
public ObjectId resolve(String revstr)
        throws AmbiguousObjectException, IncorrectObjectTypeException, RevisionSyntaxException, IOException 

Source Link

Document

Parse a git revision string and return an object id.

Usage

From source file:org.eclipse.egit.core.CommitUtil.java

License:Open Source License

/**
 * Returns whether the commits are on the current branch, ie. if they are
 * reachable from the current HEAD./*from www .ja  va  2  s.co m*/
 *
 * @param commits
 *            the commits to check
 * @param repository
 *            the repository
 * @return true if the commits are reachable from HEAD
 * @throws IOException
 *             if there is an I/O error
 */
public static boolean areCommitsInCurrentBranch(Collection<RevCommit> commits, Repository repository)
        throws IOException {
    try (RevWalk walk = new RevWalk(repository)) {
        ObjectId headCommitId = repository.resolve(Constants.HEAD);
        RevCommit headCommit = walk.parseCommit(headCommitId);

        for (final RevCommit commit : commits) {
            walk.reset();
            walk.markStart(headCommit);

            RevFilter revFilter = new RevFilter() {
                @Override
                public boolean include(RevWalk walker, RevCommit cmit) throws StopWalkException,
                        MissingObjectException, IncorrectObjectTypeException, IOException {

                    return cmit.equals(commit);
                }

                @Override
                public RevFilter clone() {
                    return null;
                }
            };
            walk.setRevFilter(revFilter);

            if (walk.next() == null)
                return false;
        }
        return true;
    }
}

From source file:org.eclipse.egit.core.op.CommitOperation.java

License:Open Source License

private void doCommits(String actMessage, HashMap<Repository, Tree> treeMap) throws IOException, TeamException {

    String commitMessage = actMessage;
    final Date commitDate = new Date();
    final TimeZone timeZone = TimeZone.getDefault();

    final PersonIdent authorIdent = RawParseUtils.parsePersonIdent(author);
    final PersonIdent committerIdent = RawParseUtils.parsePersonIdent(committer);

    for (java.util.Map.Entry<Repository, Tree> entry : treeMap.entrySet()) {
        Tree tree = entry.getValue();/*from   ww w.  ja  v  a 2s.  c  o  m*/
        Repository repo = tree.getRepository();
        repo.getIndex().write();
        writeTreeWithSubTrees(tree);

        ObjectId currentHeadId = repo.resolve(Constants.HEAD);
        ObjectId[] parentIds;
        if (amending) {
            RevCommit[] parents = previousCommit.getParents();
            parentIds = new ObjectId[parents.length];
            for (int i = 0; i < parents.length; i++)
                parentIds[i] = parents[i].getId();
        } else {
            if (currentHeadId != null)
                parentIds = new ObjectId[] { currentHeadId };
            else
                parentIds = new ObjectId[0];
        }
        if (createChangeId) {
            ObjectId parentId;
            if (parentIds.length > 0)
                parentId = parentIds[0];
            else
                parentId = null;
            ObjectId changeId = ChangeIdUtil.computeChangeId(tree.getId(), parentId, authorIdent,
                    committerIdent, commitMessage);
            commitMessage = ChangeIdUtil.insertId(commitMessage, changeId);
            if (changeId != null)
                commitMessage = commitMessage.replaceAll(
                        "\nChange-Id: I0000000000000000000000000000000000000000\n", //$NON-NLS-1$
                        "\nChange-Id: I" + changeId.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(tree.getTreeId());
        commit.setParentIds(parentIds);
        commit.setMessage(commitMessage);
        commit.setAuthor(new PersonIdent(authorIdent, commitDate, timeZone));
        commit.setCommitter(new PersonIdent(committerIdent, commitDate, timeZone));

        ObjectInserter inserter = repo.newObjectInserter();
        ObjectId commitId;
        try {
            commitId = inserter.insert(commit);
            inserter.flush();
        } finally {
            inserter.release();
        }

        final RefUpdate ru = repo.updateRef(Constants.HEAD);
        ru.setNewObjectId(commitId);
        ru.setRefLogMessage(buildReflogMessage(commitMessage), false);
        if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
            throw new TeamException(NLS.bind(CoreText.CommitOperation_failedToUpdate, ru.getName(), commitId));
        }
    }
}

From source file:org.eclipse.egit.core.RepositoryUtil.java

License:Open Source License

/**
 * Tries to map a commit to a symbolic reference.
 * <p>/*from  ww w.j ava 2  s. co m*/
 * This value will be cached for the given commit ID unless refresh is
 * specified. The return value will be the full name, e.g.
 * "refs/remotes/someBranch", "refs/tags/v.1.0"
 * <p>
 * Since this mapping is not unique, the following precedence rules are
 * used:
 * <ul>
 * <li>Tags take precedence over branches</li>
 * <li>Local branches take preference over remote branches</li>
 * <li>Newer references take precedence over older ones where time stamps
 * are available</li>
 * <li>If there are still ambiguities, the reference name with the highest
 * lexicographic value will be returned</li>
 * </ul>
 *
 * @param repository
 *            the {@link Repository}
 * @param commitId
 *            a commit
 * @param refresh
 *            if true, the cache will be invalidated
 * @return the symbolic reference, or <code>null</code> if no such reference
 *         can be found
 */
public String mapCommitToRef(Repository repository, String commitId, boolean refresh) {
    synchronized (commitMappingCache) {

        if (!ObjectId.isId(commitId)) {
            return null;
        }

        Map<String, String> cacheEntry = commitMappingCache.get(repository.getDirectory().toString());
        if (!refresh && cacheEntry != null && cacheEntry.containsKey(commitId)) {
            // this may be null in fact
            return cacheEntry.get(commitId);
        }
        if (cacheEntry == null) {
            cacheEntry = new HashMap<String, String>();
            commitMappingCache.put(repository.getDirectory().getPath(), cacheEntry);
        } else {
            cacheEntry.clear();
        }

        Map<String, Date> tagMap = new HashMap<String, Date>();
        try {
            RevWalk rw = new RevWalk(repository);
            Map<String, Ref> tags = repository.getRefDatabase().getRefs(Constants.R_TAGS);
            for (Ref tagRef : tags.values()) {
                RevTag tag = rw.parseTag(repository.resolve(tagRef.getName()));
                if (tag.getObject().name().equals(commitId)) {
                    Date timestamp;
                    if (tag.getTaggerIdent() != null) {
                        timestamp = tag.getTaggerIdent().getWhen();
                    } else {
                        timestamp = null;
                    }
                    tagMap.put(tagRef.getName(), timestamp);
                }
            }
        } catch (IOException e) {
            // ignore here
        }

        String cacheValue = null;

        if (!tagMap.isEmpty()) {
            // we try to obtain the "latest" tag
            Date compareDate = new Date(0);
            for (Map.Entry<String, Date> tagEntry : tagMap.entrySet()) {
                if (tagEntry.getValue() != null && tagEntry.getValue().after(compareDate)) {
                    compareDate = tagEntry.getValue();
                    cacheValue = tagEntry.getKey();
                }
            }
            // if we don't have time stamps, we sort
            if (cacheValue == null) {
                String compareString = ""; //$NON-NLS-1$
                for (String tagName : tagMap.keySet()) {
                    if (tagName.compareTo(compareString) >= 0) {
                        cacheValue = tagName;
                        compareString = tagName;
                    }
                }
            }
        }

        if (cacheValue == null) {
            // we didnt't find a tag, so let's look for local branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_HEADS);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
            } catch (IOException e) {
                // ignore here
            }
            if (!branchNames.isEmpty()) {
                // get the last (sorted) entry
                cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
            }
        }

        if (cacheValue == null) {
            // last try: remote branches
            Set<String> branchNames = new TreeSet<String>();
            // put this into a sorted set
            try {
                Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs(Constants.R_REMOTES);
                for (Ref branch : remoteBranches.values()) {
                    if (branch.getObjectId().name().equals(commitId)) {
                        branchNames.add(branch.getName());
                    }
                }
                if (!branchNames.isEmpty()) {
                    // get the last (sorted) entry
                    cacheValue = branchNames.toArray(new String[branchNames.size()])[branchNames.size() - 1];
                }
            } catch (IOException e) {
                // ignore here
            }
        }
        cacheEntry.put(commitId, cacheValue);
        return cacheValue;
    }
}

From source file:org.eclipse.egit.core.synchronize.StagedChangeCache.java

License:Open Source License

/**
 * @param repo/*  w  w w  .  j av a  2  s  .  c om*/
 *            repository which should be scanned
 * @return list of changes in git staging area
 */
public static Map<String, Change> build(Repository repo) {
    TreeWalk tw = new TreeWalk(repo);
    try {
        tw.addTree(new DirCacheIterator(repo.readDirCache()));
        ObjectId headId = repo.resolve(HEAD);
        RevCommit headCommit;
        if (headId != null)
            headCommit = new RevWalk(repo).parseCommit(headId);
        else
            headCommit = null;

        AbbreviatedObjectId commitId;
        if (headCommit != null) {
            tw.addTree(headCommit.getTree());
            commitId = AbbreviatedObjectId.fromObjectId(headCommit);
        } else {
            tw.addTree(new EmptyTreeIterator());
            commitId = AbbreviatedObjectId.fromObjectId(zeroId());
        }

        tw.setRecursive(true);
        headCommit = null;

        MutableObjectId idBuf = new MutableObjectId();
        Map<String, Change> result = new HashMap<String, Change>();
        while (tw.next()) {
            if (!shouldIncludeEntry(tw))
                continue;

            Change change = new Change();
            change.name = tw.getNameString();
            change.remoteCommitId = commitId;

            tw.getObjectId(idBuf, 0);
            change.objectId = AbbreviatedObjectId.fromObjectId(idBuf);
            tw.getObjectId(idBuf, 1);
            change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf);

            calculateAndSetChangeKind(RIGHT, change);

            result.put(tw.getPathString(), change);
        }
        tw.release();

        return result;
    } catch (IOException e) {
        Activator.error(e.getMessage(), e);
        return new HashMap<String, Change>(0);
    }
}

From source file:org.eclipse.egit.gitflow.op.AbstractDualRepositoryTestCase.java

License:Open Source License

protected RevCommit findHead(Repository repo) {
    try (RevWalk walk = new RevWalk(repo)) {
        try {/*from   ww  w  .ja  v a 2  s.  co m*/
            ObjectId head = repo.resolve(HEAD);
            return walk.parseCommit(head);
        } catch (RevisionSyntaxException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.eclipse.egit.gitflow.op.FeatureRebaseOperationTest.java

License:Open Source License

@Test
public void testFeatureRebase() throws Exception {
    Repository repository = testRepository.getRepository();
    GitFlowRepository gfRepo = init("testFeatureRebase\n\nfirst commit\n");
    RevCommit initialCommit = gfRepo.findHead();

    new FeatureStartOperation(gfRepo, MY_FEATURE).execute(null);
    String branchCommitMessage = "adding first file on feature branch";
    addFileAndCommit("theFile.txt", branchCommitMessage);

    testRepository.checkoutBranch(gfRepo.getConfig().getDevelop());
    RevCommit developCommit = addFileAndCommit("theOtherFile.txt", "adding second file on develop branch");

    new FeatureCheckoutOperation(gfRepo, MY_FEATURE).execute(null);
    assertEquals(initialCommit, gfRepo.findHead().getParent(0));
    FeatureRebaseOperation featureRebaseOperation = new FeatureRebaseOperation(gfRepo);
    featureRebaseOperation.execute(null);

    RebaseResult res = featureRebaseOperation.getOperationResult();
    assertEquals(RebaseResult.Status.OK, res.getStatus());

    assertEquals(branchCommitMessage, gfRepo.findHead().getShortMessage());
    assertEquals(developCommit, parseCommit(repository, repository.resolve("HEAD^")));
}

From source file:org.eclipse.egit.internal.relengtools.GitCopyrightAdapter.java

License:Open Source License

@Override
public int getLastModifiedYear(IFile file, IProgressMonitor monitor) throws CoreException {
    try {/*  ww w.  j  a  va  2  s .c o m*/
        monitor.beginTask("Fetching logs from Git", 100); //$NON-NLS-1$
        final RepositoryMapping mapping = RepositoryMapping.getMapping(file);
        if (mapping != null) {
            final Repository repo = mapping.getRepository();
            if (repo != null) {
                RevWalk walk = null;
                try {
                    final ObjectId start = repo.resolve(Constants.HEAD);
                    walk = new RevWalk(repo);
                    walk.setTreeFilter(PathFilter.create(mapping.getRepoRelativePath(file)));
                    walk.markStart(walk.lookupCommit(start));
                    final RevCommit commit = walk.next();
                    if (commit != null) {
                        if (filterString != null
                                && commit.getFullMessage().toLowerCase().indexOf(filterString) != -1) {
                            // the last update was a copyright checkin -
                            // ignore
                            return 0;
                        }
                        final Calendar calendar = Calendar.getInstance();
                        calendar.setTimeInMillis(0);
                        calendar.add(Calendar.SECOND, commit.getCommitTime());
                        return calendar.get(Calendar.YEAR);
                    }
                } catch (final IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.egit.relengtools", 0,
                            NLS.bind("An error occured when processing {0}", file.getName()), e));
                } finally {
                    if (walk != null)
                        walk.release();
                }
            }
        }
    } finally {
        monitor.done();
    }

    return -1;
}

From source file:org.eclipse.egit.internal.relengtools.ReleaseWizard.java

License:Open Source License

private void tagProject(IProject project, IProgressMonitor monitor) throws Exception {
    monitor = new SubProgressMonitor(monitor, 1);
    monitor.beginTask("Tagging " + project.getName(), 1);

    final boolean shouldMoveTag = tagPage.isMoveButtonSelected();
    final RepositoryMapping rm = RepositoryMapping.getMapping(project);
    final Repository repository = rm.getRepository();

    final RevWalk rw = new RevWalk(repository);
    final RevObject target = rw.parseAny(repository.resolve(Constants.HEAD));

    final PersonIdent personIdent = new PersonIdent(repository);
    final String tagName = tagPage.getTagString();
    final TagBuilder tag = new TagBuilder();
    tag.setTag(tagName);//from   ww  w . j  a  v  a2  s  .c  o  m
    tag.setTagger(personIdent);
    tag.setObjectId(target);

    final TagOperation operation = new TagOperation(repository, tag, shouldMoveTag);

    operation.execute(monitor);
    monitor.done();
}

From source file:org.eclipse.egit.internal.relengtools.ShowInfoHandler.java

License:Open Source License

public static RevCommit getLatestCommitFor(RepositoryMapping mapping, Repository repo, IProject project)
        throws Exception {
    final RevWalk walk = new RevWalk(repo);
    walk.reset();/*  www.  ja v  a 2s .co  m*/
    walk.sort(RevSort.TOPO, true);
    walk.sort(RevSort.COMMIT_TIME_DESC, true);
    walk.setTreeFilter(
            AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.create(mapping.getRepoRelativePath(project))));
    final ObjectId start = repo.resolve(Constants.HEAD);
    walk.markStart(walk.parseCommit(start));

    // I should only be able to see commits that contain files
    // where project is a path prefix
    final RevCommit commit = walk.next();
    return commit;
}

From source file:org.eclipse.egit.internal.relengtools.ShowInfoHandler.java

License:Open Source License

public static RevCommit getCommit(Repository repo, String name) throws Exception {
    final RevWalk walk = new RevWalk(repo);
    final ObjectId id = repo.resolve(name);
    return walk.parseCommit(id);
}