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.internal.history.GitHistoryPage.java

License:Open Source License

void initAndStartRevWalk(boolean forceNewWalk) throws IllegalStateException {
    try {//  w  w  w . j av a 2  s  .c  om
        if (trace)
            GitTraceLocation.getTrace().traceEntry(GitTraceLocation.HISTORYVIEW.getLocation());

        cancelRefreshJob();
        Repository db = input.getRepository();
        AnyObjectId headId;
        try {
            headId = db.resolve(Constants.HEAD);
        } catch (IOException e) {
            throw new IllegalStateException(NLS.bind(UIText.GitHistoryPage_errorParsingHead,
                    Activator.getDefault().getRepositoryUtil().getRepositoryName(db)));
        }
        if (headId == null)
            throw new IllegalStateException(NLS.bind(UIText.GitHistoryPage_errorParsingHead,
                    Activator.getDefault().getRepositoryUtil().getRepositoryName(db)));

        List<String> paths = buildFilterPaths(input.getItems(), input.getFileList(), db);

        if (forceNewWalk || pathChange(pathFilters, paths) || currentWalk == null
                || !headId.equals(currentHeadId)) {
            // TODO Do not dispose SWTWalk just because HEAD changed
            // In theory we should be able to update the graph and
            // not dispose of the SWTWalk, even if HEAD was reset to
            // HEAD^1 and the old HEAD commit should not be visible.
            //
            currentHeadId = headId;
            if (currentWalk != null)
                currentWalk.release();
            currentWalk = new SWTWalk(db);
            currentWalk.sort(RevSort.COMMIT_TIME_DESC, true);
            currentWalk.sort(RevSort.BOUNDARY, true);
            highlightFlag = currentWalk.newFlag("highlight"); //$NON-NLS-1$
        } else {
            currentWalk.reset();
        }

        try {
            if (store.getBoolean(UIPreferences.RESOURCEHISTORY_SHOW_ALL_BRANCHES)) {
                markStartAllRefs(Constants.R_HEADS);
                markStartAllRefs(Constants.R_REMOTES);
            } else
                currentWalk.markStart(currentWalk.parseCommit(headId));
        } catch (IOException e) {
            throw new IllegalStateException(NLS.bind(UIText.GitHistoryPage_errorReadingHeadCommit, headId,
                    db.getDirectory().getAbsolutePath()), e);
        }

        final TreeWalk fileWalker = new TreeWalk(db);
        fileWalker.setRecursive(true);
        if (paths.size() > 0) {
            pathFilters = paths;
            currentWalk.setTreeFilter(
                    AndTreeFilter.create(PathFilterGroup.createFromStrings(paths), TreeFilter.ANY_DIFF));
            fileWalker.setFilter(currentWalk.getTreeFilter().clone());

        } else {
            pathFilters = null;
            currentWalk.setTreeFilter(TreeFilter.ALL);
            fileWalker.setFilter(TreeFilter.ANY_DIFF);
        }
        fileViewer.setTreeWalk(db, fileWalker);
        fileViewer.refresh();
        fileViewer.addSelectionChangedListener(commentViewer);
        commentViewer.setTreeWalk(fileWalker);
        commentViewer.setDb(db);
        commentViewer.refresh();

        final SWTCommitList list;
        list = new SWTCommitList(graph.getControl().getDisplay());
        list.source(currentWalk);
        final GenerateHistoryJob rj = new GenerateHistoryJob(this, list);
        rj.addJobChangeListener(new JobChangeAdapter() {
            @Override
            public void done(final IJobChangeEvent event) {
                final Control graphctl = graph.getControl();
                if (job != rj || graphctl.isDisposed())
                    return;
                graphctl.getDisplay().asyncExec(new Runnable() {
                    public void run() {
                        if (job == rj)
                            job = null;
                    }
                });
            }
        });
        job = rj;
        if (trace)
            GitTraceLocation.getTrace().trace(GitTraceLocation.HISTORYVIEW.getLocation(),
                    "Scheduling GenerateHistoryJob"); //$NON-NLS-1$
        schedule(rj);
    } finally {
        if (trace)
            GitTraceLocation.getTrace().traceExit(GitTraceLocation.HISTORYVIEW.getLocation());

    }
}

From source file:org.eclipse.egit.ui.internal.merge.GitMergeEditorInput.java

License:Open Source License

@Override
protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    final Set<IFile> files = new HashSet<IFile>();
    List<IContainer> folders = new ArrayList<IContainer>();
    Set<IProject> projects = new HashSet<IProject>();

    // collect all projects and sort the selected
    // resources into files and folders; skip
    // ignored resources
    for (IResource res : resources) {
        projects.add(res.getProject());/*from   ww  w.  jav a2 s  . com*/
        if (Team.isIgnoredHint(res))
            continue;
        if (res.getType() == IResource.FILE)
            files.add((IFile) res);
        else
            folders.add((IContainer) res);
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // make sure all resources belong to the same repository
    Repository repo = null;
    for (IProject project : projects) {
        RepositoryMapping map = RepositoryMapping.getMapping(project);
        if (repo != null && repo != map.getRepository())
            throw new InvocationTargetException(
                    new IllegalStateException(UIText.AbstractHistoryCommanndHandler_NoUniqueRepository));
        repo = map.getRepository();
    }

    if (repo == null)
        throw new InvocationTargetException(
                new IllegalStateException(UIText.AbstractHistoryCommanndHandler_NoUniqueRepository));

    if (monitor.isCanceled())
        throw new InterruptedException();

    // collect all file children of the selected folders
    IResourceVisitor fileCollector = new IResourceVisitor() {
        public boolean visit(IResource resource) throws CoreException {
            if (Team.isIgnoredHint(resource))
                return false;
            if (resource.getType() == IResource.FILE) {
                files.add((IFile) resource);
            }
            return true;
        }
    };

    for (IContainer cont : folders) {
        try {
            cont.accept(fileCollector);
        } catch (CoreException e) {
            // ignore here
        }
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // our root node
    this.compareResult = new DiffNode(Differencer.CONFLICTING);

    final RevWalk rw = new RevWalk(repo);

    // get the "right" side (MERGE_HEAD for merge, ORIG_HEAD for rebase)
    final RevCommit rightCommit;
    try {
        String target;
        if (repo.getRepositoryState().equals(RepositoryState.MERGING))
            target = Constants.MERGE_HEAD;
        else if (repo.getRepositoryState().equals(RepositoryState.REBASING_INTERACTIVE))
            target = readFile(repo.getDirectory(),
                    RebaseCommand.REBASE_MERGE + File.separatorChar + RebaseCommand.STOPPED_SHA);
        else
            target = Constants.ORIG_HEAD;
        ObjectId mergeHead = repo.resolve(target);
        if (mergeHead == null)
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, target));
        rightCommit = rw.parseCommit(mergeHead);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    // we need the HEAD, also to determine the common
    // ancestor
    final RevCommit headCommit;
    try {
        ObjectId head = repo.resolve(Constants.HEAD);
        if (head == null)
            throw new IOException(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, Constants.HEAD));
        headCommit = rw.parseCommit(head);
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    final String fullBranch;
    try {
        fullBranch = repo.getFullBranch();
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }

    // try to obtain the common ancestor
    List<RevCommit> startPoints = new ArrayList<RevCommit>();
    rw.setRevFilter(RevFilter.MERGE_BASE);
    startPoints.add(rightCommit);
    startPoints.add(headCommit);
    RevCommit ancestorCommit;
    try {
        rw.markStart(startPoints);
        ancestorCommit = rw.next();
    } catch (Exception e) {
        ancestorCommit = null;
    }

    if (monitor.isCanceled())
        throw new InterruptedException();

    // set the labels
    CompareConfiguration config = getCompareConfiguration();
    config.setRightLabel(NLS.bind(LABELPATTERN, rightCommit.getShortMessage(), rightCommit.name()));

    if (!useWorkspace)
        config.setLeftLabel(NLS.bind(LABELPATTERN, headCommit.getShortMessage(), headCommit.name()));
    else
        config.setLeftLabel(UIText.GitMergeEditorInput_WorkspaceHeader);

    if (ancestorCommit != null)
        config.setAncestorLabel(
                NLS.bind(LABELPATTERN, ancestorCommit.getShortMessage(), ancestorCommit.name()));

    // set title and icon
    setTitle(NLS.bind(UIText.GitMergeEditorInput_MergeEditorTitle,
            new Object[] { Activator.getDefault().getRepositoryUtil().getRepositoryName(repo),
                    rightCommit.getShortMessage(), fullBranch }));

    // now we calculate the nodes containing the compare information
    try {
        for (IFile file : files) {
            if (monitor.isCanceled())
                throw new InterruptedException();

            monitor.setTaskName(file.getFullPath().toString());

            RepositoryMapping map = RepositoryMapping.getMapping(file);
            String gitPath = map.getRepoRelativePath(file);
            if (gitPath == null)
                continue;

            // ignore everything in .git
            if (gitPath.startsWith(Constants.DOT_GIT))
                continue;

            fileToDiffNode(file, gitPath, map, this.compareResult, rightCommit, headCommit, ancestorCommit, rw,
                    monitor);
        }
    } catch (IOException e) {
        throw new InvocationTargetException(e);
    }
    return compareResult;
}

From source file:org.eclipse.egit.ui.internal.preferences.GitProjectPropertyPage.java

License:Open Source License

private void fillValues(Repository repository) throws IOException {
    gitDir.setText(repository.getDirectory().getAbsolutePath());
    branch.setText(repository.getBranch());
    workDir.setText(repository.getWorkTree().getAbsolutePath());

    state.setText(repository.getRepositoryState().getDescription());

    final ObjectId objectId = repository.resolve(repository.getFullBranch());
    if (objectId == null) {
        if (repository.getAllRefs().size() == 0)
            id.setText(UIText.GitProjectPropertyPage_ValueEmptyRepository);
        else//from  w  w w .  ja  v a 2  s .  c  o m
            id.setText(UIText.GitProjectPropertyPage_ValueUnbornBranch);
    } else
        id.setText(objectId.name());
}

From source file:org.eclipse.egit.ui.internal.push.PushBranchWizardTest.java

License:Open Source License

private void assertBranchPushed(String branchName, Repository remoteRepo) throws Exception {
    ObjectId pushed = remoteRepo.resolve(branchName);
    assertNotNull("Expected '" + branchName + "' to resolve to non-null ObjectId on remote repository", pushed);
    ObjectId local = repository.resolve(branchName);
    assertEquals("Expected local branch to be the same as branch on remote after pushing", local, pushed);
}

From source file:org.eclipse.egit.ui.internal.push.PushTagsWizardTest.java

License:Open Source License

private void assertTagPushed(String tagName, Repository remoteRepo) throws Exception {
    ObjectId pushed = remoteRepo.resolve(tagName);
    assertNotNull("Expected '" + tagName + "' to resolve to non-null ObjectId on remote repository", pushed);
    ObjectId local = repository.resolve(tagName);
    assertEquals("Expected local tag to be the same as tag on remote after pushing", local, pushed);
}

From source file:org.eclipse.egit.ui.internal.repository.tree.command.CreateTagCommand.java

License:Open Source License

private RevObject getTagTarget(ObjectId objectId, Repository repo) throws ExecutionException {
    try {// www .j  av a  2  s  .c  o m
        RevWalk rw = new RevWalk(repo);
        try {
            if (objectId == null) {
                return rw.parseAny(repo.resolve(Constants.HEAD));

            } else {
                return rw.parseAny(objectId);
            }
        } finally {
            rw.release();
        }
    } catch (IOException e) {
        throw new ExecutionException(UIText.TagAction_unableToResolveHeadObjectId, e);
    }
}

From source file:org.eclipse.egit.ui.internal.search.CommitSearchQuery.java

License:Open Source License

private void walkRepository(Repository repository, Pattern pattern, IProgressMonitor monitor)
        throws IOException {
    RevWalk walk = new RevWalk(repository);
    try {/*from  www .j a  v  a 2 s.c om*/
        walk.setRetainBody(true);
        List<RevCommit> commits = new LinkedList<RevCommit>();
        if (this.settings.isAllBranches()) {
            for (Ref ref : repository.getRefDatabase().getRefs(Constants.R_HEADS).values())
                if (!ref.isSymbolic())
                    commits.add(walk.parseCommit(ref.getObjectId()));
            for (Ref ref : repository.getRefDatabase().getRefs(Constants.R_REMOTES).values())
                if (!ref.isSymbolic())
                    commits.add(walk.parseCommit(ref.getObjectId()));
        } else {
            ObjectId headCommit = repository.resolve(Constants.HEAD);
            if (headCommit != null)
                commits.add(walk.parseCommit(headCommit));
        }

        if (!commits.isEmpty()) {
            walk.markStart(commits);
            for (RevCommit commit : walk) {
                if (monitor.isCanceled())
                    throw new OperationCanceledException();
                for (SearchMatcher matcher : this.matchers)
                    if (matcher.matches(pattern, commit)) {
                        result.addResult(new RepositoryCommit(repository, commit));
                        break;
                    }
            }
        }
    } finally {
        walk.dispose();
    }
}

From source file:org.eclipse.egit.ui.internal.synchronize.model.GitModelTestCase.java

License:Open Source License

protected Commit getCommit(File repoFile, String rev) throws Exception {
    Repository repo = lookupRepository(repoFile);
    ObjectId revId = repo.resolve(rev);

    Commit commit = mock(Commit.class);
    Mockito.when(commit.getId()).thenReturn(AbbreviatedObjectId.fromObjectId(revId));

    return commit;
}

From source file:org.eclipse.egit.ui.internal.ValidationUtils.java

License:Open Source License

/**
 * Creates and returns input validator for refNames
 *
 * @param repo/*from  w w w  .  j  a  v  a  2s.c  o m*/
 * @param refPrefix
 * @param errorOnEmptyName
 * @return input validator for refNames
 */
public static IInputValidator getRefNameInputValidator(final Repository repo, final String refPrefix,
        final boolean errorOnEmptyName) {
    return new IInputValidator() {
        public String isValid(String newText) {
            if (newText.length() == 0) {
                if (errorOnEmptyName)
                    return UIText.ValidationUtils_PleaseEnterNameMessage;
                else
                    // ignore this
                    return null;
            }
            String testFor = refPrefix + newText;
            try {
                if (repo.resolve(testFor) != null)
                    return NLS.bind(UIText.ValidationUtils_RefAlreadyExistsMessage, testFor);
            } catch (IOException e1) {
                Activator.logError(NLS.bind(UIText.ValidationUtils_CanNotResolveRefMessage, testFor), e1);
                return e1.getMessage();
            }
            if (!Repository.isValidRefName(testFor))
                return NLS.bind(UIText.ValidationUtils_InvalidRefNameMessage, testFor);
            return null;
        }
    };
}

From source file:org.eclipse.egit.ui.test.history.HistoryViewTest.java

License:Open Source License

@Test
public void testAddBranch() throws Exception {
    Repository repo = lookupRepository(repoFile);
    assertNull(repo.resolve(Constants.R_HEADS + "NewBranch"));
    SWTBotTable table = getHistoryViewTable(PROJ1);
    SWTBotTableItem item = table.getTableItem(0);
    item.select();//w w w  . ja  va 2 s  . com
    ContextMenuHelper.clickContextMenu(table, UIText.GitHistoryPage_CreateBranchMenuLabel);
    SWTBotShell dialog = bot.shell(UIText.CreateBranchWizard_NewBranchTitle);
    dialog.bot().textWithId("BranchName").setText("NewBranch");
    // for some reason, checkboxwithlabel doesn't seem to work
    dialog.bot().checkBox().deselect();
    dialog.bot().button(IDialogConstants.FINISH_LABEL).click();
    assertNotNull(repo.resolve(Constants.R_HEADS + "NewBranch"));
}