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:com.madgag.agit.LogFragment.java

License:Open Source License

@Override
public Loader<List<RevCommit>> onCreateLoader(int id, Bundle args) {
    return new AsyncLoader<List<RevCommit>>(getActivity()) {
        public List<RevCommit> loadInBackground() {
            Stopwatch stopwatch = new Stopwatch().start();
            Bundle args = getArguments();
            try {
                Repository repo = new FileRepository(args.getString(GITDIR));

                LogCommand log = new Git(repo).log();
                List<String> untilRevs = getArguments().getStringArrayList(UNTIL_REVS);
                if (untilRevs == null || untilRevs.isEmpty()) {
                    log.all();/*from   w ww  .  ja  va  2 s  .co  m*/
                } else {
                    for (String untilRev : untilRevs) {
                        log.add(repo.resolve(untilRev));
                    }
                }

                List<RevCommit> sampleRevCommits = newArrayList(log.call());

                Log.d(TAG, "Found " + sampleRevCommits.size() + " commits " + stopwatch);

                return sampleRevCommits;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public String getBranchName() throws Exception {
    Repository repository = git.getRepository();
    if (ObjectId.isId(repository.getFullBranch())
            && repository.getFullBranch().equals(repository.resolve("HEAD").getName())) {
        RevWalk revs = null;/*from  w w  w  .  j a v  a2s  .com*/
        try {
            log.trace("Trying to resolve tagname: {}", repository.getFullBranch());
            ObjectId tagRef = ObjectId.fromString(repository.getFullBranch());
            revs = new RevWalk(repository);
            RevCommit commit = revs.parseCommit(tagRef);
            Map<String, Ref> allTags = repository.getTags();
            for (String key : allTags.keySet()) {
                Ref ref = allTags.get(key);
                RevTag tag = revs.parseTag(ref.getObjectId());
                log.trace("Checking ref {}, {}", commit.getName(), tag.getObject());
                if (tag.getObject().equals(commit)) {
                    return key;
                }
            }
        } catch (Exception e) {
            log.warn("Invalid id: {}", repository.getFullBranch(), e);
        } finally {
            revs.release();
        }
    }
    return repository.getBranch();
}

From source file:com.microsoft.gittf.core.util.CommitUtil.java

License:Open Source License

/**
 * Returns the commit object id that is pointed at by the ref specified
 * //from  ww  w .  jav a2 s . c  o m
 * @param repository
 *        the git repository
 * @param ref
 *        the reference name
 * @return
 * @throws Exception
 */
public static ObjectId getRefNameCommitID(final Repository repository, String ref) throws Exception {
    if (AbbreviatedObjectId.isId(ref) || ObjectId.isId(ref)) {
        return peelRef(repository, repository.resolve(ref));
    }

    return getCommitId(repository, ref);
}

From source file:com.mpdeimos.ct_tests.vcs.GitFileDiffTest.java

License:Apache License

@Test
public void testAddedFiles() {

    try {//  w w w .j a  v  a2  s.c  o  m
        //         ArrayList<RevCommit> commits = new ArrayList<RevCommit>();
        //         
        //         Repository repository = new FileRepository(gitDir);
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setWorkTree(useTestFile("diff1")).build();
        ObjectId head = repository.resolve("new");
        //         TreeWalk treeWalk = TreeUtils.diffWithParents(repository, head);
        //         scan = DiffEntry.scan(treeWalk);
        //         treeWalk.release();

        CommitFinder finder = new CommitFinder(repository);
        GitCommitListFilter filter = new GitCommitListFilter();
        finder.setFilter(filter);
        finder.findFrom(head);
        for (Commit commit : filter.getCommits()) {
            //            ResetCommand reset = new Git(repository).reset();
            //            reset.setMode(ResetType.HARD);
            //            reset.setRef(commit.getId());
            CheckoutCommand checkout = new Git(repository).checkout();
            checkout.setName(commit.getId());
            //            checkout.setStartPoint(commit.getId());
            //            checkout.addPath(".");
            try {
                //               Ref call = reset.call();
                checkout.call();
                System.out.println(checkout.getResult().getStatus() + " checked out " + commit.getMessage());
            } catch (Exception e) {
                fail(e.getMessage());
            }

            //            System.out.println(change.getCommit().getFullMessage());

        }

        //         head = repository.resolve("HEAD~1");
        //         RevWalk revWalk = new RevWalk(repository);
        //         RevCommit tip = revWalk.parseCommit(head);
        //         revWalk.markStart(tip);
        //         revWalk.
        //         TreeWalk treeWalk = new TreeWalk(repository);
        //         treeWalk.setRecursive(true);
        //         treeWalk.addTree(tip.getTree());
        //         

        //         revWalk.markStart(tip);

        //         GitFileDiff[] compute = GitFileDiff.compute(treeWalk, tip);

        //         System.out.println(compute);

    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:com.puppycrawl.tools.checkstyle.CommitValidationTest.java

License:Open Source License

private static RevCommitsPair resolveRevCommitsPair(Repository repo) {
    RevCommitsPair revCommitIteratorPair;
    try {//ww  w .  j  a  va  2s .c o  m
        Iterator<RevCommit> first;
        Iterator<RevCommit> second;

        RevWalk revWalk = new RevWalk(repo);

        ObjectId headId = repo.resolve(Constants.HEAD);
        RevCommit headCommit = revWalk.parseCommit(headId);

        if (isMergeCommit(headCommit)) {
            RevCommit firstParent = headCommit.getParent(0);
            RevCommit secondParent = headCommit.getParent(1);

            first = new Git(repo).log().add(firstParent).call().iterator();
            second = new Git(repo).log().add(secondParent).call().iterator();
        } else {
            first = new Git(repo).log().call().iterator();
            second = Collections.emptyIterator();
        }

        revCommitIteratorPair = new RevCommitsPair(new OmitMergeCommitsIterator(first),
                new OmitMergeCommitsIterator(second));
    } catch (GitAPIException | IOException e) {
        revCommitIteratorPair = new RevCommitsPair();
    }

    return revCommitIteratorPair;
}

From source file:com.searchcode.app.jobs.IndexGitRepoJob.java

private List<CodeOwner> getBlameInfo(int codeLinesSize, String repoName, String repoLocations,
        String fileName) {//  ww w  . ja v a  2s .c om
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);
    try {
        // The / part is required due to centos bug for version 1.1.1
        // This appears to be correct
        String repoLoc = repoLocations + "/" + repoName + "/.git";

        Repository localRepository = new FileRepository(new File(repoLoc));
        BlameCommand blamer = new BlameCommand(localRepository);

        ObjectId commitID = localRepository.resolve("HEAD");

        if (commitID == null) {
            Singleton.getLogger().info("getBlameInfo commitID is null for " + repoLoc + " " + fileName);
            return codeOwners;
        }

        BlameResult blame;

        // Somewhere in here appears to be wrong...
        blamer.setStartCommit(commitID);
        blamer.setFilePath(fileName);
        blame = blamer.call();

        // Hail mary attempt to solve issue on CentOS Attempt to set at all costs
        if (blame == null) { // This one appears to solve the issue so don't remove it
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath(String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }
        if (blame == null) {
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath("/" + String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }

        if (blame == null) {
            Singleton.getLogger().info("getBlameInfo blame is null for " + repoLoc + " " + fileName);
        }

        if (blame != null) {
            // Get all the owners their number of commits and most recent commit
            HashMap<String, CodeOwner> owners = new HashMap<>();
            RevCommit commit;
            PersonIdent authorIdent;

            try {
                for (int i = 0; i < codeLinesSize; i++) {
                    commit = blame.getSourceCommit(i);
                    authorIdent = commit.getAuthorIdent();

                    if (owners.containsKey(authorIdent.getName())) {
                        CodeOwner codeOwner = owners.get(authorIdent.getName());
                        codeOwner.incrementLines();

                        int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                        if (commit.getCommitTime() > timestamp) {
                            codeOwner.setMostRecentUnixCommitTimestamp(commit.getCommitTime());
                        }
                        owners.put(authorIdent.getName(), codeOwner);
                    } else {
                        owners.put(authorIdent.getName(),
                                new CodeOwner(authorIdent.getName(), 1, commit.getCommitTime()));
                    }
                }
            } catch (IndexOutOfBoundsException ex) {
                // Ignore this as its not really a problem or is it?
                Singleton.getLogger()
                        .info("IndexOutOfBoundsException when trying to get blame for " + repoName + fileName);
            }

            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }

    System.gc(); // Try to clean up
    return codeOwners;
}

From source file:com.searchcode.app.jobs.IndexGitRepoJob.java

private RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    try {/*from  w ww  .jav a  2s. co  m*/
        Repository localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");

        Git git = new Git(localRepository);
        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:com.searchcode.app.jobs.repository.IndexGitHistoryJob.java

public void getRevisionChanges(Repository localRepository, Git git, GitChangeSet oldRevison,
        GitChangeSet newRevision) throws IOException, GitAPIException {
    ObjectId oldHead = localRepository.resolve(oldRevison.getRevision() + "^{tree}");
    ObjectId newHead = localRepository.resolve(newRevision.getRevision() + "^{tree}");

    ObjectReader reader = localRepository.newObjectReader();

    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    oldTreeIter.reset(reader, oldHead);//from  w  w  w .ja  v  a  2  s .c om

    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset(reader, newHead);

    List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

    GitService gs = new GitService();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    for (DiffEntry entry : entries) {
        if ("DELETE".equals(entry.getChangeType().name())) {
            System.out.println("DEL " + entry.getOldPath());

            String contents = gs.fetchFileRevision(localRepository.getWorkTree().toString() + "/.git",
                    oldRevison.getRevision(), entry.getOldPath());

            CodeIndexDocument cd = new CodeIndexDocument(entry.getNewPath(), "thumbor", entry.getOldPath(),
                    entry.getOldPath(), entry.getOldPath(), "md5hash", "Java", contents.split("\\r?\\n").length,
                    contents, "", oldRevison.getAuthor());
            cd.setRevision(oldRevison.getRevision());
            cd.setYearMonthDay(sdf.format(oldRevison.getExpiry()));
            cd.setYearMonth(cd.getYearMonthDay().substring(0, 6));
            cd.setYear(cd.getYearMonthDay().substring(0, 4));
            cd.setMessage(oldRevison.getMessage());
            cd.setDeleted("TRUE");
            Singleton.getCodeIndexer().indexTimeDocument(cd);
        } else {
            System.out.println("ADD " + entry.getNewPath());
            String contents = gs.fetchFileRevision(localRepository.getWorkTree().toString() + "/.git",
                    newRevision.getRevision(), entry.getNewPath());

            CodeIndexDocument cd = new CodeIndexDocument(entry.getNewPath(), "thumbor", entry.getNewPath(),
                    entry.getNewPath(), entry.getNewPath(), "md5hash", "Java", contents.split("\\r?\\n").length,
                    contents, "", newRevision.getAuthor());
            cd.setRevision(newRevision.getRevision());
            cd.setYearMonthDay(sdf.format(oldRevison.getExpiry()));
            cd.setYearMonth(cd.getYearMonthDay().substring(0, 6));
            cd.setYear(cd.getYearMonthDay().substring(0, 4));
            cd.setMessage(newRevision.getMessage());
            cd.setDeleted("FALSE");
            Singleton.getCodeIndexer().indexTimeDocument(cd);
        }
    }
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

License:Open Source License

/**
 * Uses the inbuilt git//from  w w w. j  a v a2s  .c  o  m
 * TODO this method appears to leak memory like crazy... need to investigate
 * TODO lots of hairy bits in here need tests to capture issues
 */
public List<CodeOwner> getBlameInfo(int codeLinesSize, String repoName, String repoLocations, String fileName) {
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);
    try {
        // The / part is required due to centos bug for version 1.1.1
        // This appears to be correct
        String repoLoc = repoLocations + "/" + repoName + "/.git";

        Repository localRepository = new FileRepository(new File(repoLoc));
        BlameCommand blamer = new BlameCommand(localRepository);

        ObjectId commitID = localRepository.resolve("HEAD");

        if (commitID == null) {
            Singleton.getLogger().info("getBlameInfo commitID is null for " + repoLoc + " " + fileName);
            return codeOwners;
        }

        BlameResult blame;

        // Somewhere in here appears to be wrong...
        blamer.setStartCommit(commitID);
        blamer.setFilePath(fileName);
        blame = blamer.call();

        // Hail mary attempt to solve issue on CentOS Attempt to set at all costs
        if (blame == null) { // This one appears to solve the issue so don't remove it
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath(String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }
        if (blame == null) {
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath("/" + String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }

        if (blame == null) {
            Singleton.getLogger().info("getBlameInfo blame is null for " + repoLoc + " " + fileName);
        }

        if (blame != null) {
            // Get all the owners their number of commits and most recent commit
            HashMap<String, CodeOwner> owners = new HashMap<>();
            RevCommit commit;
            PersonIdent authorIdent;

            try {
                for (int i = 0; i < codeLinesSize; i++) {
                    commit = blame.getSourceCommit(i);
                    authorIdent = commit.getAuthorIdent();

                    if (owners.containsKey(authorIdent.getName())) {
                        CodeOwner codeOwner = owners.get(authorIdent.getName());
                        codeOwner.incrementLines();

                        int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                        if (commit.getCommitTime() > timestamp) {
                            codeOwner.setMostRecentUnixCommitTimestamp(commit.getCommitTime());
                        }
                        owners.put(authorIdent.getName(), codeOwner);
                    } else {
                        owners.put(authorIdent.getName(),
                                new CodeOwner(authorIdent.getName(), 1, commit.getCommitTime()));
                    }
                }
            } catch (IndexOutOfBoundsException ex) {
                // Ignore this as its not really a problem or is it?
                Singleton.getLogger().info(
                        "IndexOutOfBoundsException when trying to get blame for " + repoName + " " + fileName);
            }

            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException ex) {
        Singleton.getLogger().info("IOException getBlameInfo when trying to get blame for " + repoName + " "
                + fileName + " " + ex.toString());
    } catch (GitAPIException ex) {
        Singleton.getLogger().info("GitAPIException getBlameInfo when trying to get blame for " + repoName + " "
                + fileName + " " + ex.toString());
    } catch (IllegalArgumentException ex) {
        Singleton.getLogger().info("IllegalArgumentException getBlameInfo when trying to get blame for "
                + repoName + " " + fileName + " " + ex.toString());
    }

    System.gc(); // Try to clean up
    return codeOwners;
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

License:Open Source License

/**
 * Update a git repository and return if it has changed and the differences
 */// w w  w  . j  a  v  a  2s .co  m
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    Repository localRepository = null;
    Git git = null;

    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);

        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}