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.ui.test.TestUtil.java

License:Open Source License

/**
 * verifies that repository contains exactly the given files.
 * @param repository/*w w  w  . j  a v a2  s . co  m*/
 * @param paths
 * @throws Exception
 */
public static void assertRepositoryContainsFiles(Repository repository, String[] paths) throws Exception {
    Set<String> expectedfiles = new HashSet<String>();
    for (String path : paths)
        expectedfiles.add(path);
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.addTree(repository.resolve("HEAD^{tree}"));
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
        String path = treeWalk.getPathString();
        if (!expectedfiles.contains(path))
            fail("Repository contains unexpected expected file " + path);
        expectedfiles.remove(path);
    }
    if (expectedfiles.size() > 0) {
        StringBuilder message = new StringBuilder("Repository does not contain expected files: ");
        for (String path : expectedfiles) {
            message.append(path);
            message.append(" ");
        }
        fail(message.toString());
    }
}

From source file:org.eclipse.egit.ui.test.TestUtil.java

License:Open Source License

/**
 * verifies that repository contains exactly the given files with the given
 * content. Usage example:<br>//from w w  w  .j a  v a2s.  co m
 *
 * <code>
 * assertRepositoryContainsFiles(repository, "foo/a.txt", "content of A",
 *                                           "foo/b.txt", "content of B")
 * </code>
 * @param repository
 * @param args
 * @throws Exception
 */
public static void assertRepositoryContainsFilesWithContent(Repository repository, String... args)
        throws Exception {
    HashMap<String, String> expectedfiles = mkmap(args);
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.addTree(repository.resolve("HEAD^{tree}"));
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
        String path = treeWalk.getPathString();
        assertTrue(expectedfiles.containsKey(path));
        ObjectId objectId = treeWalk.getObjectId(0);
        byte[] expectedContent = expectedfiles.get(path).getBytes();
        byte[] repoContent = treeWalk.getObjectReader().open(objectId).getBytes();
        if (!Arrays.equals(repoContent, expectedContent))
            fail("File " + path + " has repository content " + new String(repoContent)
                    + " instead of expected content " + new String(expectedContent));
        expectedfiles.remove(path);
    }
    if (expectedfiles.size() > 0) {
        StringBuilder message = new StringBuilder("Repository does not contain expected files: ");
        for (String path : expectedfiles.keySet()) {
            message.append(path);
            message.append(" ");
        }
        fail(message.toString());
    }
}

From source file:org.eclipse.egit.ui.test.TestUtil.java

License:Open Source License

public static RevCommit getHeadCommit(Repository repository) throws Exception {
    RevCommit headCommit = null;//from  w w  w  . j  a va2 s.  c  o m
    ObjectId parentId = repository.resolve(Constants.HEAD);
    if (parentId != null)
        headCommit = new RevWalk(repository).parseCommit(parentId);
    return headCommit;
}

From source file:org.eclipse.egit.ui.wizards.clone.GitCloneWizardTest.java

License:Open Source License

@Test
public void alteringSomeParametersDuringClone() throws Exception {
    File destRepo = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile(), "test2");

    importWizard.openWizard();/*from  w  w  w.  j  av a  2 s. c  om*/
    RepoPropertiesPage repoProperties = importWizard.openCloneWizard();
    RepoRemoteBranchesPage remoteBranches = repoProperties.nextToRemoteBranches(r.getUri());
    remoteBranches.deselectAllBranches();
    remoteBranches.assertErrorMessage("At least one branch must be selected.");
    remoteBranches.assertNextIsDisabled();

    remoteBranches.selectBranches(SampleTestRepository.FIX);
    remoteBranches.assertNextIsEnabled();

    WorkingCopyPage workingCopy = remoteBranches.nextToWorkingCopy();
    workingCopy.setDirectory(destRepo.toString());
    workingCopy.assertBranch(SampleTestRepository.FIX);
    workingCopy.setRemoteName("src");
    workingCopy.waitForCreate();

    // Some random sampling to see we got something. We do not test
    // the integrity of the repository here. Only a few basic properties
    // we'd expect from a clone made this way, that would possibly
    // not hold true given other parameters in the GUI.
    Repository repository = new FileRepository(new File(destRepo, Constants.DOT_GIT));
    assertNotNull(repository.resolve("src/" + SampleTestRepository.FIX));
    // we didn't clone that one
    assertNull(repository.resolve("src/master"));
    // and a local master initialized from origin/master (default!)
    assertEquals(repository.resolve("stable"), repository.resolve("src/stable"));
    // A well known tag
    assertNotNull(repository.resolve(Constants.R_TAGS + SampleTestRepository.v2_0_name).name());
    // lots of refs
    assertTrue(repository.getAllRefs().size() >= 4);
}

From source file:org.eclipse.egit.ui.wizards.clone.GitCloneWizardTestBase.java

License:Open Source License

protected void cloneRepo(File destRepo, RepoRemoteBranchesPage remoteBranches) throws Exception {
    remoteBranches.assertRemoteBranches(SampleTestRepository.FIX, Constants.MASTER);
    remoteBranches.selectBranches(SampleTestRepository.FIX, Constants.MASTER);

    WorkingCopyPage workingCopy = remoteBranches.nextToWorkingCopy();
    workingCopy.setDirectory(destRepo.toString());

    workingCopy.assertDirectory(destRepo.toString());
    workingCopy.assertBranch(Constants.MASTER);
    workingCopy.assertRemoteName(Constants.DEFAULT_REMOTE_NAME);
    workingCopy.waitForCreate();/*w ww . j  a  v a  2 s.  c o  m*/

    // Some random sampling to see we got something. We do not test
    // the integrity of the repository here. Only a few basic properties
    // we'd expect from a clone made this way, that would possibly
    // not hold true given other parameters in the GUI.
    Repository repository = new FileRepository(new File(destRepo, Constants.DOT_GIT));
    // we always have an origin/master
    assertNotNull(repository.resolve("origin/master"));
    // and a local master initialized from origin/master (default!)
    assertEquals(repository.resolve("master"), repository.resolve("origin/master"));
    // A well known tag
    assertNotNull(repository.resolve(Constants.R_TAGS + SampleTestRepository.v1_0_name).name());
    // lots of refs
    int refs = repository.getAllRefs().size();
    assertTrue(refs >= 4);
    // and a known file in the working dir
    assertTrue(new File(destRepo, SampleTestRepository.A_txt_name).exists());
    DirCacheEntry fileEntry = null;
    DirCache dc = repository.lockDirCache();
    fileEntry = dc.getEntry(SampleTestRepository.A_txt_name);
    dc.unlock();
    // check that we have the file in the index
    assertNotNull(fileEntry);
    // No project has been imported
    assertEquals(0, ResourcesPlugin.getWorkspace().getRoot().getProjects().length);
}

From source file:org.eclipse.emf.compare.egit.ui.internal.merge.ModelGitMergeEditorInput.java

License:Open Source License

private RevCommit getRightCommit(RevWalk revWalk, Repository repository) throws InvocationTargetException {
    try {//  w ww .j  a  v a 2 s  .c o m
        String target;
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            target = Constants.MERGE_HEAD;
        } else if (repository.getRepositoryState().equals(RepositoryState.CHERRY_PICKING)) {
            target = Constants.CHERRY_PICK_HEAD;
        } else if (repository.getRepositoryState().equals(RepositoryState.REBASING_INTERACTIVE)) {
            target = readFile(repository.getDirectory(),
                    RebaseCommand.REBASE_MERGE + File.separatorChar + RebaseCommand.STOPPED_SHA);
        } else {
            target = Constants.ORIG_HEAD;
        }
        ObjectId mergeHead = repository.resolve(target);
        if (mergeHead == null) {
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, target));
        }
        return revWalk.parseCommit(mergeHead);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
}

From source file:org.eclipse.emf.compare.egit.ui.internal.merge.ModelGitMergeEditorInput.java

License:Open Source License

private RevCommit getLeftCommit(RevWalk revWalk, Repository repository) throws InvocationTargetException {
    try {//www .j  av  a 2  s . c om
        ObjectId head = repository.resolve(Constants.HEAD);
        if (head == null) {
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, Constants.HEAD));
        }
        return revWalk.parseCommit(head);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
}

From source file:org.eclipse.emf.compare.egit.ui.internal.merge.ModelGitMergeEditorInput.java

License:Open Source License

private IDiffContainer buildDiffContainer(Repository repository, RevCommit headCommit, RevCommit ancestorCommit,
        List<String> filterPaths, RevWalk rw, IProgressMonitor monitor)
        throws IOException, InterruptedException {

    monitor.setTaskName(UIText.GitMergeEditorInput_CalculatingDiffTaskName);
    IDiffContainer result = new DiffNode(Differencer.CONFLICTING);

    TreeWalk tw = new TreeWalk(repository);
    try {//from  w w  w. j a  va  2 s. c om
        int dirCacheIndex = tw.addTree(new DirCacheIterator(repository.readDirCache()));
        int fileTreeIndex = tw.addTree(new FileTreeIterator(repository));
        int repositoryTreeIndex = tw.addTree(rw.parseTree(repository.resolve(Constants.HEAD)));

        // skip ignored resources
        NotIgnoredFilter notIgnoredFilter = new NotIgnoredFilter(fileTreeIndex);
        // filter by selected resources
        if (filterPaths.size() > 1) {
            List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
            for (String filterPath : filterPaths) {
                suffixFilters.add(PathFilter.create(filterPath));
            }
            TreeFilter otf = OrTreeFilter.create(suffixFilters);
            tw.setFilter(AndTreeFilter.create(otf, notIgnoredFilter));
        } else if (filterPaths.size() > 0) {
            String path = filterPaths.get(0);
            if (path.length() == 0) {
                tw.setFilter(notIgnoredFilter);
            } else {
                tw.setFilter(AndTreeFilter.create(PathFilter.create(path), notIgnoredFilter));
            }
        } else {
            tw.setFilter(notIgnoredFilter);
        }

        tw.setRecursive(true);

        while (tw.next()) {
            if (monitor.isCanceled()) {
                throw new InterruptedException();
            }
            String gitPath = tw.getPathString();
            monitor.setTaskName(gitPath);

            FileTreeIterator fit = tw.getTree(fileTreeIndex, FileTreeIterator.class);
            if (fit == null) {
                continue;
            }

            DirCacheIterator dit = tw.getTree(dirCacheIndex, DirCacheIterator.class);

            final DirCacheEntry dirCacheEntry = dit == null ? null : dit.getDirCacheEntry();

            boolean conflicting = dirCacheEntry != null && dirCacheEntry.getStage() > 0;

            AbstractTreeIterator rt = tw.getTree(repositoryTreeIndex, AbstractTreeIterator.class);

            // compare local file against HEAD to see if it was modified
            boolean modified = rt != null && !fit.getEntryObjectId().equals(rt.getEntryObjectId());

            // if this is neither conflicting nor changed, we skip it
            if (!conflicting && !modified) {
                continue;
            }

            ITypedElement right;
            if (conflicting) {
                GitFileRevision revision = GitFileRevision.inIndex(repository, gitPath, DirCacheEntry.STAGE_3);
                String encoding = CompareCoreUtils.getResourceEncoding(repository, gitPath);
                right = new FileRevisionTypedElement(revision, encoding);
            } else {
                right = CompareUtils.getFileRevisionTypedElement(gitPath, headCommit, repository);
            }

            // can this really happen?
            if (right instanceof EmptyTypedElement) {
                continue;
            }

            IFileRevision rev;
            // if the file is not conflicting (as it was auto-merged)
            // we will show the auto-merged (local) version

            Path repositoryPath = new Path(repository.getWorkTree().getAbsolutePath());
            IPath location = repositoryPath.append(fit.getEntryPathString());
            IFile file = ResourceUtil.getFileForLocation(location, false);
            if (!conflicting || useWorkspace) {
                if (file != null) {
                    rev = new LocalFileRevision(file);
                } else {
                    rev = new WorkingTreeFileRevision(location.toFile());
                }
            } else {
                rev = GitFileRevision.inIndex(repository, gitPath, DirCacheEntry.STAGE_2);
            }

            IRunnableContext runnableContext = getContainer();
            if (runnableContext == null) {
                runnableContext = PlatformUI.getWorkbench().getProgressService();
            }

            EditableRevision leftEditable;
            if (file != null) {
                leftEditable = new ResourceEditableRevision(rev, file, runnableContext);
            } else {
                leftEditable = new LocationEditableRevision(rev, location, runnableContext);
            }
            // make sure we don't need a round trip later
            try {
                leftEditable.cacheContents(monitor);
            } catch (CoreException e) {
                throw new IOException(e.getMessage());
            }

            int kind = Differencer.NO_CHANGE;
            if (conflicting) {
                kind = Differencer.CONFLICTING;
            } else if (modified) {
                kind = Differencer.PSEUDO_CONFLICT;
            }

            IDiffContainer fileParent = getFileParent(result, repositoryPath, file, location);

            ITypedElement anc;
            if (ancestorCommit != null) {
                anc = CompareUtils.getFileRevisionTypedElement(gitPath, ancestorCommit, repository);
            } else {
                anc = null;
            }
            // we get an ugly black icon if we have an EmptyTypedElement
            // instead of null
            if (anc instanceof EmptyTypedElement) {
                anc = null;
            }
            // create the node as child
            new DiffNode(fileParent, kind, anc, leftEditable, right);
        }
        return result;
    } finally {
        tw.close();
    }
}

From source file:org.eclipse.mylyn.internal.gerrit.ui.egit.EGitUiUtil.java

License:Open Source License

public static RevCommit getRevCommit(Repository repository, PatchSet target)
        throws AmbiguousObjectException, IOException, MissingObjectException, IncorrectObjectTypeException {
    ObjectId ref = repository.resolve(target.getRevision().get());
    RevWalk walker = new RevWalk(repository);
    RevCommit targetCommit = walker.parseCommit(ref);
    return targetCommit;
}

From source file:org.eclipse.mylyn.internal.github.ui.pr.CheckoutPullRequestHandler.java

License:Open Source License

private RevCommit getBase(Repository repo, PullRequest request) throws IOException {
    RevWalk walk = new RevWalk(repo);
    try {// w ww  .j  a  v a2  s  .co  m
        return walk.parseCommit(repo.resolve(request.getBase().getSha()));
    } finally {
        walk.release();
    }
}