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.core.op.BranchOperation.java

License:Open Source License

private void updateHeadRef() throws TeamException {
    boolean detach = false;
    // in case of a non-local branch or a tag,
    // we "detach" HEAD, i.e. point it to the
    // underlying commit instead of to the Ref
    if (refName == null || !refName.startsWith(Constants.R_HEADS))
        detach = true;/*  w  w w  .j  a  va  2  s.  c o m*/
    try {
        RefUpdate u = repository.updateRef(Constants.HEAD, detach);
        Result res;
        if (detach) {
            u.setNewObjectId(newCommit.getId());
            // using forceUpdate instead of update avoids
            // the merge tests which would otherwise make
            // this fail
            u.setRefLogMessage(NLS.bind(CoreText.BranchOperation_checkoutMovingTo, newCommit.getId().name()),
                    false);
            res = u.forceUpdate();
        } else {
            u.setRefLogMessage(NLS.bind(CoreText.BranchOperation_checkoutMovingTo, refName), false);
            res = u.link(refName);
        }
        switch (res) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            break;
        default:
            throw new IOException(u.getResult().name());
        }
    } catch (IOException e) {
        throw new TeamException(NLS.bind(CoreText.BranchOperation_updatingHeadToRef, refName), e);
    }
}

From source file:org.eclipse.egit.core.op.BranchOperation.java

License:Open Source License

private void lookupRefs() throws TeamException {
    RevWalk walk = new RevWalk(repository);
    try {//from  w  ww  .  j a v  a2  s  . c  o  m
        if (refName != null) {
            newCommit = walk.parseCommit(repository.resolve(refName));
        }
        if (commitId != null) {
            newCommit = walk.parseCommit(commitId);
        }
    } catch (IOException e) {
        throw new TeamException(NLS.bind(CoreText.BranchOperation_mappingCommit, refName), e);
    }

    try {
        oldCommit = walk.parseCommit(repository.resolve(Constants.HEAD));
    } catch (IOException e) {
        throw new TeamException(CoreText.BranchOperation_mappingCommitHead, e);
    }
}

From source file:org.eclipse.egit.core.op.CloneOperation.java

License:Open Source License

private void doInit(final IProgressMonitor monitor) throws URISyntaxException, IOException {
    monitor.setTaskName(CoreText.CloneOperation_initializingRepository);

    local = new FileRepository(gitdir);
    local.create();/*from  www.  j a va 2 s  . co m*/

    final RefUpdate head = local.updateRef(Constants.HEAD);
    head.disableRefLog();
    head.link(branch);

    remoteConfig = new RemoteConfig(local.getConfig(), remoteName);
    remoteConfig.addURI(uri);

    final String dst = Constants.R_REMOTES + remoteConfig.getName();
    RefSpec wcrs = new RefSpec();
    wcrs = wcrs.setForceUpdate(true);
    wcrs = wcrs.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$

    if (allSelected) {
        remoteConfig.addFetchRefSpec(wcrs);
    } else {
        for (final Ref ref : selectedBranches)
            if (wcrs.matchSource(ref))
                remoteConfig.addFetchRefSpec(wcrs.expandFromSource(ref));
    }

    // we're setting up for a clone with a checkout
    local.getConfig().setBoolean("core", null, "bare", false); //$NON-NLS-1$ //$NON-NLS-2$

    remoteConfig.update(local.getConfig());

    // branch is like 'Constants.R_HEADS + branchName', we need only
    // the 'branchName' part
    String branchName = branch.substring(Constants.R_HEADS.length());

    // setup the default remote branch for branchName
    local.getConfig().setString("branch", branchName, "remote", remoteName); //$NON-NLS-1$ //$NON-NLS-2$
    local.getConfig().setString("branch", branchName, "merge", branch); //$NON-NLS-1$ //$NON-NLS-2$

    local.getConfig().save();
}

From source file:org.eclipse.egit.core.op.CloneOperation.java

License:Open Source License

private void doCheckout(final IProgressMonitor monitor) throws IOException {
    final Ref head = fetchResult.getAdvertisedRef(branch);
    if (head == null || head.getObjectId() == null)
        return;/*w w w.  ja  v  a 2 s.c  o  m*/

    final RevWalk rw = new RevWalk(local);
    final RevCommit mapCommit;
    try {
        mapCommit = rw.parseCommit(head.getObjectId());
    } finally {
        rw.release();
    }

    final RefUpdate u;

    u = local.updateRef(Constants.HEAD);
    u.setNewObjectId(mapCommit.getId());
    u.forceUpdate();

    monitor.setTaskName(CoreText.CloneOperation_checkingOutFiles);
    DirCacheCheckout dirCacheCheckout = new DirCacheCheckout(local, null, local.lockDirCache(),
            mapCommit.getTree());
    dirCacheCheckout.setFailOnConflict(true);
    boolean result = dirCacheCheckout.checkout();
    if (!result)
        // this should never happen when writing in an empty folder
        throw new IOException("Internal error occured on checking out files"); //$NON-NLS-1$
    monitor.setTaskName(CoreText.CloneOperation_writingIndex);
}

From source file:org.eclipse.egit.core.op.CommitOperation.java

License:Open Source License

private boolean prepareTrees(IFile[] selectedItems, HashMap<Repository, Tree> treeMap, IProgressMonitor monitor)
        throws IOException, UnsupportedEncodingException {
    if (selectedItems.length == 0) {
        // amending commit - need to put something into the map
        for (Repository repo : repos) {
            treeMap.put(repo, repo.mapTree(Constants.HEAD));
        }//  w  ww.  jav a  2s  . c o  m
    }

    for (IFile file : selectedItems) {

        if (monitor.isCanceled())
            return false;
        monitor.worked(1);

        IProject project = file.getProject();
        RepositoryMapping repositoryMapping = RepositoryMapping.getMapping(project);
        Repository repository = repositoryMapping.getRepository();
        Tree projTree = treeMap.get(repository);
        if (projTree == null) {
            projTree = repository.mapTree(Constants.HEAD);
            if (projTree == null)
                projTree = new Tree(repository);
            treeMap.put(repository, projTree);
            // TODO is this the right Location?
            if (GitTraceLocation.CORE.isActive())
                GitTraceLocation.getTrace().trace(GitTraceLocation.CORE.getLocation(),
                        "Orig tree id: " + projTree.getId()); //$NON-NLS-1$
        }
        GitIndex index = repository.getIndex();
        String repoRelativePath = repositoryMapping.getRepoRelativePath(file);
        String string = repoRelativePath;

        TreeEntry treeMember = projTree.findBlobMember(repoRelativePath);
        // we always want to delete it from the current tree, since if it's
        // updated, we'll add it again
        if (treeMember != null)
            treeMember.delete();

        Entry idxEntry = index.getEntry(string);
        if (notIndexed.contains(file)) {
            File thisfile = new File(repositoryMapping.getWorkTree(), idxEntry.getName());
            if (!thisfile.isFile()) {
                index.remove(repositoryMapping.getWorkTree(), thisfile);
                // TODO is this the right Location?
                if (GitTraceLocation.CORE.isActive())
                    GitTraceLocation.getTrace().trace(GitTraceLocation.CORE.getLocation(),
                            "Phantom file, so removing from index"); //$NON-NLS-1$
                continue;
            } else {
                idxEntry.update(thisfile);
            }
        }
        if (notTracked.contains(file)) {
            idxEntry = index.add(repositoryMapping.getWorkTree(),
                    new File(repositoryMapping.getWorkTree(), repoRelativePath));

        }

        if (idxEntry != null) {
            projTree.addFile(repoRelativePath);
            TreeEntry newMember = projTree.findBlobMember(repoRelativePath);

            newMember.setId(idxEntry.getObjectId());
            // TODO is this the right Location?
            if (GitTraceLocation.CORE.isActive())
                GitTraceLocation.getTrace().trace(GitTraceLocation.CORE.getLocation(),
                        "New member id for " + repoRelativePath //$NON-NLS-1$
                                + ": " + newMember.getId() + " idx id: " //$NON-NLS-1$ //$NON-NLS-2$
                                + idxEntry.getObjectId());
        }
    }
    return true;
}

From source file:org.eclipse.egit.core.op.CommitOperation.java

License:Open Source License

private void doCommits(String actMessage, HashMap<Repository, Tree> treeMap) throws IOException, TeamException {

    String commitMessage = actMessage;
    final Date commitDate = new Date();
    final TimeZone timeZone = TimeZone.getDefault();

    final PersonIdent authorIdent = RawParseUtils.parsePersonIdent(author);
    final PersonIdent committerIdent = RawParseUtils.parsePersonIdent(committer);

    for (java.util.Map.Entry<Repository, Tree> entry : treeMap.entrySet()) {
        Tree tree = entry.getValue();/*from   w  ww. j  a  v  a 2 s.  c o m*/
        Repository repo = tree.getRepository();
        repo.getIndex().write();
        writeTreeWithSubTrees(tree);

        ObjectId currentHeadId = repo.resolve(Constants.HEAD);
        ObjectId[] parentIds;
        if (amending) {
            RevCommit[] parents = previousCommit.getParents();
            parentIds = new ObjectId[parents.length];
            for (int i = 0; i < parents.length; i++)
                parentIds[i] = parents[i].getId();
        } else {
            if (currentHeadId != null)
                parentIds = new ObjectId[] { currentHeadId };
            else
                parentIds = new ObjectId[0];
        }
        if (createChangeId) {
            ObjectId parentId;
            if (parentIds.length > 0)
                parentId = parentIds[0];
            else
                parentId = null;
            ObjectId changeId = ChangeIdUtil.computeChangeId(tree.getId(), parentId, authorIdent,
                    committerIdent, commitMessage);
            commitMessage = ChangeIdUtil.insertId(commitMessage, changeId);
            if (changeId != null)
                commitMessage = commitMessage.replaceAll(
                        "\nChange-Id: I0000000000000000000000000000000000000000\n", //$NON-NLS-1$
                        "\nChange-Id: I" + changeId.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(tree.getTreeId());
        commit.setParentIds(parentIds);
        commit.setMessage(commitMessage);
        commit.setAuthor(new PersonIdent(authorIdent, commitDate, timeZone));
        commit.setCommitter(new PersonIdent(committerIdent, commitDate, timeZone));

        ObjectInserter inserter = repo.newObjectInserter();
        ObjectId commitId;
        try {
            commitId = inserter.insert(commit);
            inserter.flush();
        } finally {
            inserter.release();
        }

        final RefUpdate ru = repo.updateRef(Constants.HEAD);
        ru.setNewObjectId(commitId);
        ru.setRefLogMessage(buildReflogMessage(commitMessage), false);
        if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
            throw new TeamException(NLS.bind(CoreText.CommitOperation_failedToUpdate, ru.getName(), commitId));
        }
    }
}

From source file:org.eclipse.egit.core.op.ResetOperation.java

License:Open Source License

private void writeRef() throws TeamException {
    try {//from w  w  w . j a  v a2s.c o  m
        final RefUpdate ru = repository.updateRef(Constants.HEAD);
        ru.setNewObjectId(commit.getId());
        String name = refName;
        if (name.startsWith("refs/heads/")) //$NON-NLS-1$
            name = name.substring(11);
        if (name.startsWith("refs/remotes/")) //$NON-NLS-1$
            name = name.substring(13);
        String message = "reset --" //$NON-NLS-1$
                + type.toString().toLowerCase() + " " + name; //$NON-NLS-1$
        ru.setRefLogMessage(message, false);
        if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE)
            throw new TeamException(NLS.bind(CoreText.ResetOperation_cantUpdate, ru.getName()));
    } catch (IOException e) {
        throw new TeamException(NLS.bind(CoreText.ResetOperation_updatingFailed, Constants.HEAD), e);
    }
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantComparatorTest.java

License:Open Source License

/**
 * When comparing file that don't exist in base, but exists in remote
 * compare method should return false.//from  ww  w.  j a  v  a2s  .  c  o m
 *
 * @throws Exception
 */
@Test
public void shouldReturnFalseWhenBaseDoesntExist() throws Exception {
    // when
    GitResourceVariantComparator grvc = new GitResourceVariantComparator(null);

    // given
    RevCommit baseCommit = testRepo.createInitialCommit("initial commit");
    testRepo.createAndCheckoutBranch(Constants.HEAD, Constants.R_HEADS + "test");
    File file = testRepo.createFile(iProject, "test-file");
    RevCommit remoteCommit = testRepo.addAndCommit(iProject, file, "second commit");
    String path = Repository.stripWorkDir(repo.getWorkTree(), file);

    GitBlobResourceVariant base = new GitBlobResourceVariant(repo, null, baseCommit.getTree(), path);
    GitBlobResourceVariant remote = new GitBlobResourceVariant(repo, null, remoteCommit.getTree(), path);

    // then
    assertFalse(grvc.compare(base, remote));
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantComparatorTest.java

License:Open Source License

/**
 * Compare() should return false when remote file does not exists, but
 * equivalent local file exist./*from   w  w  w.  j a  v  a  2s  . c  om*/
 *
 * @throws Exception
 */
@Test
public void shouldReturnFalseWhenRemoteVariantDoesntExist() throws Exception {
    // when
    GitResourceVariantComparator grvc = new GitResourceVariantComparator(null);

    // given
    RevCommit remoteCommit = testRepo.createInitialCommit("initial commit");
    testRepo.createAndCheckoutBranch(Constants.HEAD, Constants.R_HEADS + "test");
    File file = testRepo.createFile(iProject, "test-file");
    RevCommit baseCommit = testRepo.addAndCommit(iProject, file, "second commit");
    String path = Repository.stripWorkDir(repo.getWorkTree(), file);

    GitBlobResourceVariant base = new GitBlobResourceVariant(repo, null, baseCommit.getTree(), path);
    GitBlobResourceVariant remote = new GitBlobResourceVariant(repo, null, remoteCommit.getTree(), path);

    // then
    assertFalse(grvc.compare(base, remote));
}

From source file:org.eclipse.egit.core.synchronize.GitResourceVariantTreeSubscriberTest.java

License:Open Source License

/**
 * This test simulates that user work and made some changes on branch 'test'
 * and then try to synchronize "test" and 'master' branch.
 *
 * @throws Exception/* w  ww . j av a2s .  co m*/
 */
@Test
public void shouldReturnSrcBranchAsBase() throws Exception {
    // when
    String fileName = "Main.java";
    File file = testRepo.createFile(iProject, fileName);
    RevCommit commit = testRepo.appendContentAndCommit(iProject, file, "class Main {}", "initial commit");
    IFile mainJava = testRepo.getIFile(iProject, file);
    testRepo.createAndCheckoutBranch(Constants.HEAD, Constants.R_HEADS + "test");
    testRepo.appendContentAndCommit(iProject, file, "// test1", "secont commit");

    // given
    GitResourceVariantTreeSubscriber grvts = createGitResourceVariantTreeSubscriber(Constants.HEAD,
            Constants.R_HEADS + Constants.MASTER);
    grvts.getBaseTree();
    IResourceVariantTree baseTree = grvts.getBaseTree();

    // then
    IResourceVariant actual = commonAssertionsForBaseTree(baseTree, mainJava);
    assertEquals(commit.abbreviate(7).name() + "...", actual.getContentIdentifier());
}