Example usage for org.eclipse.jgit.lib Constants HEAD

List of usage examples for org.eclipse.jgit.lib Constants HEAD

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants HEAD.

Prototype

String HEAD

To view the source code for org.eclipse.jgit.lib Constants HEAD.

Click Source Link

Document

Special name for the "HEAD" symbolic-ref.

Usage

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 . j a v a 2  s  . c  o  m
        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.merge.GitMergeEditorInput.java

License:Open Source License

private void fileToDiffNode(final IFile file, String gitPath, RepositoryMapping map, IDiffContainer root,
        RevCommit rightCommit, RevCommit headCommit, RevCommit ancestorCommit, RevWalk rw,
        IProgressMonitor monitor) throws IOException, InterruptedException {

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

    TreeWalk tw = new TreeWalk(map.getRepository());

    List<String> paths = new ArrayList<String>();
    paths.add(map.getRepoRelativePath(file));
    tw.setFilter(PathFilterGroup.createFromStrings(paths));

    int dcindex = tw.addTree(new DirCacheIterator(map.getRepository().readDirCache()));
    int ftindex = tw.addTree(new FileTreeIterator(map.getRepository()));
    int rtindex = tw.addTree(rw.parseTree(map.getRepository().resolve(Constants.HEAD)));

    tw.setRecursive(tw.getFilter().shouldBeRecursive());
    tw.next();//  ww w.j  a va  2s . c  o m

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

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

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

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

    FileTreeIterator fit = tw.getTree(ftindex, FileTreeIterator.class);
    if (fit != null && fit.isEntryIgnored())
        return;
    // compare local file against HEAD to see if it was modified
    boolean modified = fit != null && rt != null && !fit.getEntryObjectId().equals(rt.getEntryObjectId());

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

    ITypedElement right;
    if (conflicting)
        right = CompareUtils.getFileRevisionTypedElement(gitPath, rightCommit, map.getRepository());
    else
        right = CompareUtils.getFileRevisionTypedElement(gitPath, headCommit, map.getRepository());

    // can this really happen?
    if (right instanceof EmptyTypedElement)
        return;

    IFileRevision rev;
    // if the file is not conflicting (as it was auto-merged)
    // we will show the auto-merged (local) version
    if (!conflicting || useWorkspace)
        rev = new LocalFileRevision(file);
    else
        rev = GitFileRevision.inCommit(map.getRepository(), headCommit, gitPath, null);

    EditableRevision leftEditable = new EditableRevision(rev) {
        @Override
        public void setContent(final byte[] newContent) {
            try {
                run(false, false, new IRunnableWithProgress() {
                    public void run(IProgressMonitor myMonitor)
                            throws InvocationTargetException, InterruptedException {
                        try {
                            file.setContents(new ByteArrayInputStream(newContent), false, true, myMonitor);
                        } catch (CoreException e) {
                            throw new InvocationTargetException(e);
                        }
                    }
                });
            } catch (InvocationTargetException e) {
                Activator.handleError(e.getTargetException().getMessage(), e.getTargetException(), true);
            } catch (InterruptedException e) {
                // ignore here
            }
        }
    };
    // 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;

    DiffNode fileParent = getFileParent(root, file);

    ITypedElement anc;
    if (ancestorCommit != null)
        anc = CompareUtils.getFileRevisionTypedElement(gitPath, ancestorCommit, map.getRepository());
    else
        anc = null;
    // create the node as child
    new DiffNode(fileParent, kind, anc, leftEditable, right);
}

From source file:org.eclipse.egit.ui.internal.pull.PullWizardPage.java

License:Open Source License

/**
 * Create the page.//w  w w.  j  av a  2s.  c  o  m
 *
 * @param repository
 */
public PullWizardPage(Repository repository) {
    super(UIText.PullWizardPage_PageName);
    setTitle(UIText.PullWizardPage_PageTitle);
    setMessage(UIText.PullWizardPage_PageMessage);
    setImageDescriptor(UIIcons.WIZBAN_PULL);
    this.repository = repository;
    try {
        this.head = repository.findRef(Constants.HEAD);
        this.fullBranch = repository.getFullBranch();
    } catch (IOException ex) {
        Activator.logError(ex.getMessage(), ex);
    }
}

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

License:Open Source License

@Test
public void pushHeadToExistingRemote() throws Exception {
    try (Git git = new Git(repository)) {
        AnyObjectId head = repository.resolve(Constants.HEAD);
        git.checkout().setName(head.name()).call();
    }/*from w  w w. j a  v  a  2  s . co  m*/

    PushBranchWizardTester wizard = PushBranchWizardTester.startWizard(selectProject(), Constants.HEAD);
    wizard.selectRemote("fetch");
    wizard.enterBranchName("foo");
    wizard.next();
    wizard.finish();

    assertBranchPushed("foo", remoteRepository);
}

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

License:Open Source License

public static PushBranchWizardTester startWizard(SWTBotTree projectTree, String branchName) {
    String pushBranchMenu = branchName.equals(Constants.HEAD) ? UIText.PushMenu_PushHEAD
            : NLS.bind(UIText.PushMenu_PushBranch, branchName);
    ContextMenuHelper.clickContextMenu(projectTree, "Team", pushBranchMenu);
    return forBranchName(branchName);
}

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

License:Open Source License

public static PushBranchWizardTester forBranchName(String branchName) {
    SWTWorkbenchBot bot = new SWTWorkbenchBot();
    String title = branchName.equals(Constants.HEAD) ? UIText.PushCommitHandler_pushCommitTitle
            : MessageFormat.format(UIText.PushBranchWizard_WindowTitle, branchName);
    SWTBot wizard = bot.shell(title).bot();
    return new PushBranchWizardTester(wizard);
}

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

License:Open Source License

void doPush(IProgressMonitor monitor) {
    try {//from www .  j a  v  a 2  s .  c  o m
        int timeout = Activator.getDefault().getPreferenceStore()
                .getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
        URIish uri = new URIish(uriCombo.getText());
        Ref currentHead = repository.getRef(Constants.HEAD);
        RemoteRefUpdate update = new RemoteRefUpdate(repository, currentHead,
                prefixCombo.getItem(prefixCombo.getSelectionIndex()) + branchText.getText(), false, null, null);
        PushOperationSpecification spec = new PushOperationSpecification();

        spec.addURIRefUpdates(uri, Arrays.asList(update));
        PushOperationUI op = new PushOperationUI(repository, spec, timeout, false);
        op.setCredentialsProvider(new EGitCredentialsProvider());
        PushOperationResult result = op.execute(monitor);
        PushResultDialog dlg = new PushResultDialog(getShell(), repository, result, op.getDestinationString());
        dlg.showConfigureButton(false);
        dlg.open();
        storeLastUsedUri(uriCombo.getText());
        storeLastUsedBranch(branchText.getText());
    } catch (CoreException e) {
        Activator.handleError(e.getMessage(), e, true);
    } catch (URISyntaxException e) {
        Activator.handleError(e.getMessage(), e, true);
    } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, true);
    }
}

From source file:org.eclipse.egit.ui.internal.reflog.ReflogView.java

License:Open Source License

/**
 * Defines the repository for the reflog to show.
 *
 * @param repository
 */
private void showReflogFor(Repository repository) {
    showReflogFor(repository, Constants.HEAD);
}

From source file:org.eclipse.egit.ui.internal.reflog.RefSelectionDialog.java

License:Open Source License

@Override
protected void createCustomArea(Composite parent) {
    branchTree.addFilter(new ViewerFilter() {

        public boolean select(Viewer viewer, Object parentElement, Object element) {
            if (element instanceof AdditionalRefNode) {
                AdditionalRefNode ref = (AdditionalRefNode) element;
                return Constants.HEAD.equals(ref.getObject().getName());
            }//from   www. jav  a 2s  .co m
            return true;
        }
    });
}

From source file:org.eclipse.egit.ui.internal.repository.RepositoriesViewLabelProvider.java

License:Open Source License

private Image decorateImage(final Image image, Object element) {

    RepositoryTreeNode node = (RepositoryTreeNode) element;
    switch (node.getType()) {

    case TAG://from w  w w  .ja  va  2s.c o  m
        // fall through
    case ADDITIONALREF:
        // fall through
    case REF:
        // if the branch or tag is checked out,
        // we want to decorate the corresponding
        // node with a little check indicator
        String refName = ((Ref) node.getObject()).getName();
        Ref leaf = ((Ref) node.getObject()).getLeaf();

        String branchName;
        String compareString;

        try {
            branchName = node.getRepository().getFullBranch();
            if (branchName == null)
                return image;
            if (refName.startsWith(Constants.R_HEADS)) {
                // local branch: HEAD would be on the branch
                compareString = refName;
            } else if (refName.startsWith(Constants.R_TAGS)) {
                // tag: HEAD would be on the commit id to which the tag is
                // pointing
                ObjectId id = node.getRepository().resolve(refName);
                if (id == null)
                    return image;
                RevWalk rw = new RevWalk(node.getRepository());
                RevTag tag = rw.parseTag(id);
                compareString = tag.getObject().name();

            } else if (refName.startsWith(Constants.R_REMOTES)) {
                // remote branch: HEAD would be on the commit id to which
                // the branch is pointing
                ObjectId id = node.getRepository().resolve(refName);
                if (id == null)
                    return image;
                RevWalk rw = new RevWalk(node.getRepository());
                RevCommit commit = rw.parseCommit(id);
                compareString = commit.getId().name();
            } else if (refName.equals(Constants.HEAD))
                return getDecoratedImage(image);
            else {
                String leafname = leaf.getName();
                if (leafname.startsWith(Constants.R_REFS)
                        && leafname.equals(node.getRepository().getFullBranch()))
                    return getDecoratedImage(image);
                else if (leaf.getObjectId().equals(node.getRepository().resolve(Constants.HEAD)))
                    return getDecoratedImage(image);
                // some other symbolic reference
                return image;
            }
        } catch (IOException e1) {
            return image;
        }

        if (compareString.equals(branchName)) {
            return getDecoratedImage(image);
        }

        return image;

    default:
        return image;
    }
}