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:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Returns the default branch to use for a repository. Normally returns
 * whatever branch HEAD points to, but if HEAD points to nothing it returns
 * the most recently updated branch./*  w ww.  ja va 2  s  .  co  m*/
 *
 * @param repository
 * @return the objectid of a branch
 * @throws Exception
 */
public static ObjectId getDefaultBranch(Repository repository) throws Exception {
    ObjectId object = repository.resolve(Constants.HEAD);
    if (object == null) {
        // no HEAD
        // perhaps non-standard repository, try local branches
        List<RefModel> branchModels = getLocalBranches(repository, true, -1);
        if (branchModels.size() > 0) {
            // use most recently updated branch
            RefModel branch = null;
            Date lastDate = new Date(0);
            for (RefModel branchModel : branchModels) {
                if (branchModel.getDate().after(lastDate)) {
                    branch = branchModel;
                    lastDate = branch.getDate();
                }
            }
            object = branch.getReferencedObjectId();
        }
    }
    return object;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Sets the symbolic ref HEAD to the specified target ref. The
 * HEAD will be detached if the target ref is not a branch.
 *
 * @param repository//from   w w w. j  ava2s  .c  o  m
 * @param targetRef
 * @return true if successful
 */
public static boolean setHEADtoRef(Repository repository, String targetRef) {
    try {
        // detach HEAD if target ref is not a branch
        boolean detach = !targetRef.startsWith(Constants.R_HEADS);
        RefUpdate.Result result;
        RefUpdate head = repository.updateRef(Constants.HEAD, detach);
        if (detach) { // Tag
            RevCommit commit = getCommit(repository, targetRef);
            head.setNewObjectId(commit.getId());
            result = head.forceUpdate();
        } else {
            result = head.link(targetRef);
        }
        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return true;
        default:
            LOGGER.error(MessageFormat.format("{0} HEAD update to {1} returned result {2}",
                    repository.getDirectory().getAbsolutePath(), targetRef, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to set HEAD to {1}", targetRef);
    }
    return false;
}

From source file:com.gitblit.wicket.pages.MarkdownPage.java

License:Apache License

public MarkdownPage(PageParameters params) {
    super(params);

    final String markdownPath = WicketUtils.getPath(params);

    Repository r = getRepository();/*from  w w  w. ja  va  2 s . c o m*/
    RevCommit commit = JGitUtils.getCommit(r, objectId);
    String[] encodings = GitBlit.getEncodings();

    // markdown page links
    add(new BookmarkablePageLink<Void>("blameLink", BlamePage.class,
            WicketUtils.newPathParameter(repositoryName, objectId, markdownPath)));
    add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class,
            WicketUtils.newPathParameter(repositoryName, objectId, markdownPath)));
    add(new BookmarkablePageLink<Void>("rawLink", RawPage.class,
            WicketUtils.newPathParameter(repositoryName, objectId, markdownPath)));
    add(new BookmarkablePageLink<Void>("headLink", MarkdownPage.class,
            WicketUtils.newPathParameter(repositoryName, Constants.HEAD, markdownPath)));

    // Read raw markdown content and transform it to html
    String markdownText = JGitUtils.getStringContent(r, commit.getTree(), markdownPath, encodings);
    String htmlText;
    try {
        htmlText = MarkdownUtils.transformMarkdown(markdownText);
    } catch (ParseException p) {
        markdownText = MessageFormat.format(
                "<div class=\"alert alert-error\"><strong>{0}:</strong> {1}</div>{2}", getString("gb.error"),
                getString("gb.markdownFailure"), markdownText);
        htmlText = StringUtils.breakLinesForHtml(markdownText);
    }

    // Add the html to the page
    add(new Label("markdownText", htmlText).setEscapeModelStrings(false));
}

From source file:com.github.checkstyle.regression.internal.CommitValidationTest.java

License:Open Source License

private static RevCommitsPair resolveRevCommitsPair(Repository repo) {
    RevCommitsPair revCommitIteratorPair;

    try (RevWalk revWalk = new RevWalk(repo)) {
        final Iterator<RevCommit> first;
        final Iterator<RevCommit> second;
        final ObjectId headId = repo.resolve(Constants.HEAD);
        final RevCommit headCommit = revWalk.parseCommit(headId);

        if (isMergeCommit(headCommit)) {
            final RevCommit firstParent = headCommit.getParent(0);
            final RevCommit secondParent = headCommit.getParent(1);

            try (Git git = new Git(repo)) {
                first = git.log().add(firstParent).call().iterator();
                second = git.log().add(secondParent).call().iterator();
            }//from   ww w  .  ja va  2  s  .co m
        } else {
            try (Git git = new Git(repo)) {
                first = git.log().call().iterator();
            }
            second = Collections.emptyIterator();
        }

        revCommitIteratorPair = new RevCommitsPair(new OmitMergeCommitsIterator(first),
                new OmitMergeCommitsIterator(second));
    } catch (GitAPIException | IOException ex) {
        revCommitIteratorPair = new RevCommitsPair();
    }

    return revCommitIteratorPair;
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloneFunction.java

License:Open Source License

private boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }//  w ww. j  a  v a2  s  . com
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloner.java

License:Open Source License

private static boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }//  w  w  w  .  j a  v a 2s .  c om
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.google.gerrit.acceptance.git.GitUtil.java

License:Apache License

private static ObjectId computeChangeId(Git git, PersonIdent i, String msg) throws IOException {
    RevWalk rw = new RevWalk(git.getRepository());
    try {//from   w  w w .ja v  a  2  s. c  o  m
        Ref head = git.getRepository().getRef(Constants.HEAD);
        if (head.getObjectId() != null) {
            RevCommit parent = rw.lookupCommit(head.getObjectId());
            return ChangeIdUtil.computeChangeId(parent.getTree(), parent.getId(), i, i, msg);
        } else {
            return ChangeIdUtil.computeChangeId(null, null, i, i, msg);
        }
    } finally {
        rw.release();
    }
}

From source file:com.google.gerrit.acceptance.git.ssh.GitUtil.java

License:Apache License

private static ObjectId computeChangeId(Git git, PersonIdent i, String msg) throws IOException {
    RevWalk rw = new RevWalk(git.getRepository());
    try {//from w w w .j a v  a 2  s . c om
        RevCommit parent = rw.lookupCommit(git.getRepository().getRef(Constants.HEAD).getObjectId());
        return ChangeIdUtil.computeChangeId(parent.getTree(), parent.getId(), i, i, msg);
    } finally {
        rw.release();
    }
}

From source file:com.google.gerrit.acceptance.rest.project.CreateProjectIT.java

License:Apache License

private void assertHead(String projectName, String expectedRef)
        throws RepositoryNotFoundException, IOException {
    try (Repository repo = repoManager.openRepository(new Project.NameKey(projectName))) {
        assertThat(repo.getRef(Constants.HEAD).getTarget().getName()).isEqualTo(expectedRef);
    }/*from  w w w  . ja v  a  2 s  .  co m*/
}

From source file:com.google.gerrit.httpd.rpc.project.ListBranches.java

License:Apache License

@Override
public ListBranchesResult call() throws NoSuchProjectException {
    final ProjectControl pctl = projectControlFactory.validateFor( //
            projectName, //
            ProjectControl.OWNER | ProjectControl.VISIBLE);

    final List<Branch> branches = new ArrayList<Branch>();
    Branch headBranch = null;//from  w w  w  .  jav a 2s.c  om
    final Set<String> targets = new HashSet<String>();

    final Repository db;
    try {
        db = repoManager.openRepository(projectName);
    } catch (RepositoryNotFoundException noGitRepository) {
        return new ListBranchesResult(branches, false, true);
    }
    try {
        final Map<String, Ref> all = db.getAllRefs();

        if (!all.containsKey(Constants.HEAD)) {
            // The branch pointed to by HEAD doesn't exist yet, so getAllRefs
            // filtered it out. If we ask for it individually we can find the
            // underlying target and put it into the map anyway.
            //
            try {
                Ref head = db.getRef(Constants.HEAD);
                if (head != null) {
                    all.put(Constants.HEAD, head);
                }
            } catch (IOException e) {
                // Ignore the failure reading HEAD.
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                targets.add(ref.getTarget().getName());
            }
        }

        for (final Ref ref : all.values()) {
            if (ref.isSymbolic()) {
                // A symbolic reference to another branch, instead of
                // showing the resolved value, show the name it references.
                //
                String target = ref.getTarget().getName();
                RefControl targetRefControl = pctl.controlForRef(target);
                if (!targetRefControl.isVisible()) {
                    continue;
                }
                if (target.startsWith(Constants.R_HEADS)) {
                    target = target.substring(Constants.R_HEADS.length());
                }

                Branch b = createBranch(ref.getName());
                b.setRevision(new RevId(target));

                if (Constants.HEAD.equals(ref.getName())) {
                    b.setCanDelete(false);
                    headBranch = b;
                } else {
                    b.setCanDelete(targetRefControl.canDelete());
                    branches.add(b);
                }
                continue;
            }

            RefControl refControl = pctl.controlForRef(ref.getName());

            if (ref.getName().startsWith(Constants.R_HEADS) && refControl.isVisible()) {
                final Branch b = createBranch(ref.getName());
                if (ref.getObjectId() != null) {
                    b.setRevision(new RevId(ref.getObjectId().name()));
                }

                b.setCanDelete(!targets.contains(ref.getName()) && refControl.canDelete());

                branches.add(b);
            }
        }
    } finally {
        db.close();
    }
    Collections.sort(branches, new Comparator<Branch>() {
        @Override
        public int compare(final Branch a, final Branch b) {
            return a.getName().compareTo(b.getName());
        }
    });
    if (headBranch != null) {
        branches.add(0, headBranch);
    }
    return new ListBranchesResult(branches, pctl.canAddRefs(), false);
}