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.view.repositories.GitRepositoriesViewTest.java

License:Open Source License

 /**
 * Checks for the Symbolic Reference node
 * // ww w  . j ava 2 s  .  com
 * @throws Exception
 */
@Test
public void testExpandSymbolicRef() throws Exception {
   SWTBotTree tree = getOrOpenView().bot().tree();
   SWTBotTreeItem item = myRepoViewUtil.getSymbolicRefsItem(tree,
         repositoryFile).expand();
   List<String> children = item.getNodes();
   boolean found = false;
   for (String child : children)
      if (child.contains(Constants.HEAD))
         found = true;
   assertTrue(found);
}

From source file:org.eclipse.egit.ui.view.synchronize.SynchronizeViewPushTest.java

License:Open Source License

@Test
public void shouldUpdateTrackingBranchOnPush() throws Exception {
    makeChangesAndCommit(PROJ1);//ww w. j  av  a2 s .c  o  m
    FileRepository repository = lookupRepository(repositoryFile);
    ObjectId headId = repository.resolve(Constants.HEAD);

    String trackingBranch = Constants.R_REMOTES + "origin/master";
    launchSynchronization(Constants.HEAD, trackingBranch, false);

    SWTBotView viewBot = bot.viewByTitle("Synchronize");
    SWTBotToolbarButton pushButton = viewBot.toolbarButton(UIText.GitActionContributor_Push);
    JobJoiner jobJoiner = JobJoiner.startListening(JobFamilies.PUSH, 30, TimeUnit.SECONDS);
    pushButton.click();
    jobJoiner.join();

    String destinationString = repositoryFile.getParentFile().getName() + " - " + "origin";
    SWTBotShell resultDialog = bot.shell(NLS.bind(UIText.ResultDialog_title, destinationString));
    resultDialog.close();

    FileRepository remoteRepository = lookupRepository(childRepositoryFile);
    ObjectId masterOnRemote = remoteRepository.resolve("master");
    assertThat("Expected push to update branch on remote repository", masterOnRemote, is(headId));

    ObjectId trackingId = repository.resolve(trackingBranch);
    assertThat("Expected tracking branch to be updated", trackingId, is(headId));
}

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 {/* w ww.  j  a  v a 2  s  .co  m*/
        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 www. j  a  v a  2  s.  c o  m*/
        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.emf.compare.git.pgm.internal.app.LogicalMergeApplication.java

License:Open Source License

/**
 * {@inheritDoc}.//from  w w  w . ja va2s  . co  m
 */
@Override
protected Integer performGitCommand() throws Die {

    try {
        MergeOperation merge = new MergeOperation(repo, commit.getName());
        if (message != null) {
            merge.setMessage(message);
        }
        merge.execute(new NullProgressMonitor());
        MergeResult result = merge.getResult();
        Ref oldHead = repo.getRef(Constants.HEAD);

        return handleResult(result, oldHead, MergeStrategy.RECURSIVE);
    } catch (Exception e) {
        progressPageLog.log(e);
        throw new DiesOn(DeathType.FATAL).duedTo(e).ready();
    }

}

From source file:org.eclipse.mylyn.internal.git.core.GitConnector.java

License:Open Source License

private String resolveObject(FileRepository repo, String repoRelativePath)
        throws AmbiguousObjectException, IOException {
    //Validate/*from   ww  w  .j  a  va 2s.  com*/
    if (repo == null || repoRelativePath == null) {
        return null;
    }

    ObjectId headCommitId = repo.resolve(Constants.HEAD);
    String id = null;
    if (headCommitId != null) {
        // Not an empty repo
        RevWalk revWalk = new RevWalk(repo);
        RevCommit headCommit = revWalk.parseCommit(headCommitId);
        RevTree headTree = headCommit.getTree();
        TreeWalk resourceInRepo = TreeWalk.forPath(repo, repoRelativePath, headTree);
        if (resourceInRepo != null) {
            ObjectId objId = resourceInRepo.getObjectId(0);
            id = objId.getName();
        }
        revWalk.dispose();
    }

    return id;
}

From source file:org.eclipse.orion.server.git.BranchToJSONConverter.java

License:Open Source License

public static JSONObject toJSON(Ref ref, Repository db, URI baseLocation, int segmentsToRemove)
        throws JSONException, URISyntaxException, IOException, CoreException {
    JSONObject result = new JSONObject();
    String shortName = Repository.shortenRefName(ref.getName());
    result.put(ProtocolConstants.KEY_NAME, shortName);
    result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_BRANCH_NAME);

    IPath basePath = new Path(baseLocation.getPath());
    IPath newPath = new Path(GitServlet.GIT_URI).append(GitConstants.BRANCH_RESOURCE).append(shortName)
            .append(basePath.removeFirstSegments(segmentsToRemove));
    URI location = new URI(baseLocation.getScheme(), baseLocation.getUserInfo(), baseLocation.getHost(),
            baseLocation.getPort(), newPath.toString(), baseLocation.getQuery(), baseLocation.getFragment());
    result.put(ProtocolConstants.KEY_LOCATION, location);

    // add Git Clone URI
    result.put(GitConstants.KEY_CLONE,/*w ww .j  a va 2s .  co  m*/
            BaseToCloneConverter.getCloneLocation(location, BaseToCloneConverter.BRANCH));

    // add Git Commit URI
    result.put(GitConstants.KEY_COMMIT,
            BaseToCommitConverter.getCommitLocation(location, shortName, BaseToCommitConverter.REMOVE_FIRST_3));

    result.put(GitConstants.KEY_REMOTE, BaseToRemoteConverter.getRemoteBranchLocation(location, shortName, db,
            BaseToRemoteConverter.REMOVE_FIRST_3));
    result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(location, Constants.HEAD,
            BaseToCommitConverter.REMOVE_FIRST_3));
    result.put(GitConstants.KEY_BRANCH_CURRENT, shortName.equals(db.getBranch()));

    return result;
}

From source file:org.eclipse.orion.server.git.GitFileDecorator.java

License:Open Source License

private void addGitLinks(URI location, JSONObject representation)
        throws URISyntaxException, JSONException, CoreException, IOException {
    JSONObject gitSection = new JSONObject();
    IPath targetPath = new Path(location.getPath());

    File gitDir = GitUtils.getGitDir(targetPath);
    Repository db = new FileRepository(gitDir);

    // add Git Diff URI
    IPath path = new Path(
            GitServlet.GIT_URI + '/' + GitConstants.DIFF_RESOURCE + '/' + GitConstants.KEY_DIFF_DEFAULT)
                    .append(targetPath);
    URI link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_DIFF, link);

    // add Git Status URI
    path = new Path(GitServlet.GIT_URI + '/' + GitConstants.STATUS_RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_STATUS, link);

    // add Git Index URI
    path = new Path(GitServlet.GIT_URI + '/' + GitConstants.INDEX_RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_INDEX, link);

    // add Git HEAD URI
    path = new Path(GitServlet.GIT_URI + '/' + GitConstants.COMMIT_RESOURCE).append(Constants.HEAD)
            .append(targetPath);//w  w  w . j  ava 2  s  .  com
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_HEAD, link);

    // add Git Commit URI
    path = new Path(GitServlet.GIT_URI + '/' + GitConstants.COMMIT_RESOURCE).append(db.getBranch())
            .append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_COMMIT, link);

    // add Git Remote URI
    path = new Path(GitServlet.GIT_URI + '/' + GitConstants.REMOTE_RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_REMOTE, link);

    // add Git Clone Config URI
    path = new Path(GitServlet.GIT_URI + '/' + GitConstants.CONFIG_RESOURCE + '/' + GitConstants.CLONE_RESOURCE)
            .append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_CONFIG, link);

    // add Git Default Remote Branch URI
    gitSection.put(GitConstants.KEY_DEFAULT_REMOTE_BRANCH, BaseToRemoteConverter
            .getRemoteBranchLocation(location, db.getBranch(), db, BaseToRemoteConverter.FILE));

    // add Git Tag URI
    path = new Path(GitServlet.GIT_URI + '/' + GitConstants.TAG_RESOURCE).append(targetPath);
    link = new URI(location.getScheme(), location.getAuthority(), path.toString(), null, null);
    gitSection.put(GitConstants.KEY_TAG, link);

    // add Git Clone URI
    gitSection.put(GitConstants.KEY_CLONE,
            BaseToCloneConverter.getCloneLocation(location, BaseToCloneConverter.FILE));

    representation.put(GitConstants.KEY_GIT, gitSection);
}

From source file:org.eclipse.orion.server.git.jobs.LogCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Log} command with all the options and parameters collected by the setter methods (e.g. {@link #add(AnyObjectId)},
 * {@link #not(AnyObjectId)}, ..) of this class. Each instance of this class should only be used for one invocation of the command. Don't call this method
 * twice on an instance.//from  w ww  .j  a v  a  2s .c om
 *
 * @return an iteration over RevCommits
 * @throws NoHeadException
 *             of the references ref cannot be resolved
 */
@Override
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException {
    checkCallable();
    ArrayList<RevFilter> filters = new ArrayList<RevFilter>();

    if (pathFilters.size() > 0)
        walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF));

    if (msgFilter != null)
        filters.add(msgFilter);
    if (authorFilter != null)
        filters.add(authorFilter);
    if (committerFilter != null)
        filters.add(committerFilter);
    if (sha1Filter != null)
        filters.add(sha1Filter);
    if (dateFilter != null)
        filters.add(dateFilter);
    if (skip > -1)
        filters.add(SkipRevFilter.create(skip));
    if (maxCount > -1)
        filters.add(MaxCountRevFilter.create(maxCount));
    RevFilter filter = null;
    if (filters.size() > 1) {
        filter = AndRevFilter.create(filters);
    } else if (filters.size() == 1) {
        filter = filters.get(0);
    }

    if (filter != null)
        walk.setRevFilter(filter);

    if (!startSpecified) {
        try {
            ObjectId headId = repo.resolve(Constants.HEAD);
            if (headId == null)
                throw new NoHeadException(JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified);
            add(headId);
        } catch (IOException e) {
            // all exceptions thrown by add() shouldn't occur and represent
            // severe low-level exception which are therefore wrapped
            throw new JGitInternalException(JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e);
        }
    }
    setCallable(false);
    return walk;
}

From source file:org.eclipse.orion.server.git.jobs.StashApplyCommand.java

License:Eclipse Distribution License

/**
 * Apply the changes in a stashed commit to the working directory and index
 *
 * @return id of stashed commit that was applied TODO: Does anyone depend on this, or could we make it more like Merge/CherryPick/Revert?
 * @throws GitAPIException/* w w  w. j a  v a2s.  c o  m*/
 * @throws WrongRepositoryStateException
 * @throws NoHeadException
 * @throws StashApplyFailureException
 */
@Override
public ObjectId call()
        throws GitAPIException, WrongRepositoryStateException, NoHeadException, StashApplyFailureException {
    checkCallable();

    if (!ignoreRepositoryState && repo.getRepositoryState() != RepositoryState.SAFE)
        throw new WrongRepositoryStateException(
                MessageFormat.format(JGitText.get().stashApplyOnUnsafeRepository, repo.getRepositoryState()));

    ObjectReader reader = repo.newObjectReader();
    try {
        RevWalk revWalk = new RevWalk(reader);

        ObjectId headCommit = repo.resolve(Constants.HEAD);
        if (headCommit == null)
            throw new NoHeadException(JGitText.get().stashApplyWithoutHead);

        final ObjectId stashId = getStashId();
        RevCommit stashCommit = revWalk.parseCommit(stashId);
        if (stashCommit.getParentCount() < 2 || stashCommit.getParentCount() > 3)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().stashCommitIncorrectNumberOfParents, stashId.name(),
                            Integer.valueOf(stashCommit.getParentCount())));

        ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
        ObjectId stashIndexCommit = revWalk.parseCommit(stashCommit.getParent(1));
        ObjectId stashHeadCommit = stashCommit.getParent(0);
        ObjectId untrackedCommit = null;
        if (applyUntracked && stashCommit.getParentCount() == 3)
            untrackedCommit = revWalk.parseCommit(stashCommit.getParent(2));

        ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
        merger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stash" });
        merger.setBase(stashHeadCommit);
        merger.setWorkingTreeIterator(new FileTreeIterator(repo));
        if (merger.merge(headCommit, stashCommit)) {
            DirCache dc = repo.lockDirCache();
            DirCacheCheckout dco = new DirCacheCheckout(repo, headTree, dc, merger.getResultTreeId());
            dco.setFailOnConflict(true);
            dco.checkout(); // Ignoring failed deletes....
            if (applyIndex) {
                ResolveMerger ixMerger = (ResolveMerger) strategy.newMerger(repo, true);
                ixMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stashed index" });
                ixMerger.setBase(stashHeadCommit);
                boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
                if (ok) {
                    resetIndex(revWalk.parseTree(ixMerger.getResultTreeId()));
                } else {
                    throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
                }
            }

            if (untrackedCommit != null) {
                ResolveMerger untrackedMerger = (ResolveMerger) strategy.newMerger(repo, true);
                untrackedMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "untracked files" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                untrackedMerger.setBase(stashHeadCommit);
                boolean ok = untrackedMerger.merge(stashHeadCommit, untrackedCommit);
                if (ok)
                    try {
                        RevTree untrackedTree = revWalk.parseTree(untrackedMerger.getResultTreeId());
                        resetUntracked(untrackedTree);
                    } catch (CheckoutConflictException e) {
                        throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
                    }
                else
                    throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
            }
        } else {
            throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
        }
        return stashId;

    } catch (JGitInternalException e) {
        throw e;
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
    } finally {
        reader.release();
    }
}