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.microsoft.gittf.core.util.RepositoryUtil.java

License:Open Source License

public static void fixFileAttributes(final Repository repository) throws IOException {
    if (Platform.isCurrentPlatform(Platform.GENERIC_UNIX)) {
        final TreeWalk treeWalk = new NameConflictTreeWalk(repository);
        final Ref headReference = repository.getRef(Constants.HEAD);
        final RevCommit headCommit = new RevWalk(repository).parseCommit(headReference.getObjectId());

        treeWalk.setRecursive(true);//from ww w .j ava  2  s.c om
        treeWalk.addTree(headCommit.getTree().getId());
        treeWalk.setFilter(TreeFilter.ANY_DIFF);

        final File workingDirectory = repository.getWorkTree();

        while (treeWalk.next()) {
            final FileMode fileMode = treeWalk.getFileMode(0);

            if (FileMode.EXECUTABLE_FILE == fileMode) {
                final File file = new File(workingDirectory, treeWalk.getPathString());
                log.debug("Executable: " + file.getAbsolutePath());

                final FileSystemAttributes attr = FileSystemUtils.getInstance().getAttributes(file);

                attr.setExecutable(true);
                FileSystemUtils.getInstance().setAttributes(file, attr);
            }
        }

        treeWalk.reset();
    }
}

From source file:com.microsoft.gittf.core.util.StashUtil.java

License:Open Source License

/**
 * Creates a stash/* w  ww .j a  v a  2  s  .  c  om*/
 * 
 * @param repository
 *        the git repository
 * @param repositoryInserter
 *        the repository inserter object to use
 * @param rootBaseTree
 *        the tree id for the base commit of the stash
 * @param rootStashTree
 *        the tree id for the commit of the stash
 * @param rootIndexTree
 *        the tree id for the index commit of the stash
 * @param baseParentId
 *        the parent of the base tree commit
 * @param ownerDisplayName
 *        the owner display name of the stash
 * @param ownerName
 *        the owner name of the stash
 * @param stashComment
 *        the comment used to for the stash
 * @param stashName
 *        the stash name
 * @return
 * @throws IOException
 */
public static final ObjectId create(final Repository repository, final ObjectInserter repositoryInserter,
        final ObjectId rootBaseTree, final ObjectId rootStashTree, final ObjectId rootIndexTree,
        final ObjectId baseParentId, final String ownerDisplayName, final String ownerName,
        final String stashComment, final String stashName) throws IOException {
    Check.notNull(repository, "repository"); //$NON-NLS-1$
    Check.notNull(repositoryInserter, "repositoryInserter"); //$NON-NLS-1$
    Check.notNull(rootBaseTree, "rootBaseTree"); //$NON-NLS-1$
    Check.notNull(rootStashTree, "rootStashTree"); //$NON-NLS-1$
    Check.notNull(rootIndexTree, "rootIndexTree"); //$NON-NLS-1$

    /* identifies the head and the branch we are creating the stash for */
    Ref headReference = repository.getRef(Constants.HEAD);
    RevCommit headCommit = new RevWalk(repository).parseCommit(headReference.getObjectId());
    String currentBranchName = Repository.shortenRefName(headReference.getTarget().getName());

    PersonIdent author = new PersonIdent(ownerDisplayName, ownerName);

    /* create the base commit */
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(rootBaseTree);
    if (baseParentId != null) {
        commitBuilder.setParentId(baseParentId);
    }
    commitBuilder.setMessage(stashComment);
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId baseCommit = repositoryInserter.insert(commitBuilder);

    /* create the index commit */
    commitBuilder.setTreeId(rootIndexTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.setMessage(MessageFormat.format(STASH_INDEX_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName));
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId indexCommit = repositoryInserter.insert(commitBuilder);

    /* create the stash commit */
    commitBuilder.setTreeId(rootStashTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.addParentId(indexCommit);

    String stashRefLogComment = MessageFormat.format(STASH_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName);
    commitBuilder.setMessage(stashRefLogComment);

    ObjectId stashCommit = repositoryInserter.insert(commitBuilder);

    repositoryInserter.flush();

    /* Update the stash reference and ref log */
    RefUpdate stashReferenceUpdate = repository.updateRef(Constants.R_STASH);
    stashReferenceUpdate.setNewObjectId(stashCommit);
    stashReferenceUpdate.setRefLogIdent(author);
    stashReferenceUpdate.setRefLogMessage(stashRefLogComment, false);

    Ref currentStashRef = repository.getRef(Constants.R_STASH);
    if (currentStashRef != null) {
        stashReferenceUpdate.setExpectedOldObjectId(currentStashRef.getObjectId());
    } else {
        stashReferenceUpdate.setExpectedOldObjectId(ObjectId.zeroId());
    }

    stashReferenceUpdate.forceUpdate();

    return stashCommit;
}

From source file:com.mycila.maven.plugin.license.git.GitLookup.java

License:Apache License

/**
 * Returns the year of the last change of the given {@code file} based on the history of the present git branch. The
 * year is taken either from the committer date or from the author identity depending on how {@link #dateSource} was
 * initialized.//w  ww  . ja  v  a 2  s  .c om
 * <p>
 * See also the note on time zones in {@link #GitLookup(File, DateSource, TimeZone, int)}.
 *
 * @param file
 * @return
 * @throws NoHeadException
 * @throws GitAPIException
 * @throws IOException
 */
public int getYearOfLastChange(File file) throws NoHeadException, GitAPIException, IOException {
    String repoRelativePath = pathResolver.relativize(file);

    Status status = new Git(repository).status().addPath(repoRelativePath).call();
    if (!status.isClean()) {
        /* Return the current year for modified and unstaged files */
        return toYear(System.currentTimeMillis(), timeZone != null ? timeZone : DEFAULT_ZONE);
    }

    RevWalk walk = new RevWalk(repository);
    walk.markStart(walk.parseCommit(repository.resolve(Constants.HEAD)));
    walk.setTreeFilter(AndTreeFilter.create(PathFilter.create(repoRelativePath), TreeFilter.ANY_DIFF));
    walk.setRevFilter(MaxCountRevFilter.create(checkCommitsCount));
    walk.setRetainBody(false);

    int commitYear = 0;
    for (RevCommit commit : walk) {
        int y;
        switch (dateSource) {
        case COMMITER:
            int epochSeconds = commit.getCommitTime();
            y = toYear(epochSeconds * 1000L, timeZone);
            break;
        case AUTHOR:
            PersonIdent id = commit.getAuthorIdent();
            Date date = id.getWhen();
            y = toYear(date.getTime(), id.getTimeZone());
            break;
        default:
            throw new IllegalStateException("Unexpected " + DateSource.class.getName() + " " + dateSource);
        }
        if (y > commitYear) {
            commitYear = y;
        }
    }
    walk.dispose();
    return commitYear;
}

From source file:com.nlbhub.nlb.vcs.GitAdapter.java

License:Open Source License

private List<String> listRepositoryContents() throws IOException, NLBVCSException {
    List<String> result = new ArrayList<>();
    Ref head = m_localRepo.getRef(Constants.HEAD);
    // head can be null if repo is broken (for example, .git directory was deleted)
    if (head == null) {
        throw new NLBVCSException(
                "Your Git repository is broken.\nPlease either properly clone it (using 'git clone' command) or use 'runlight' command to run the program.");
    }//from   w w  w .  jav a 2s.  c  o  m

    // head.getObjectId() can be null, for example, if repository was never committed.
    final ObjectId objectId = head.getObjectId();
    if (objectId != null) {
        // a RevWalk allows to walk over commits based on some filtering that is defined
        RevWalk walk = new RevWalk(m_localRepo);

        RevCommit commit = walk.parseCommit(objectId);
        RevTree tree = commit.getTree();

        // now use a TreeWalk to iterate over all files in the Tree recursively
        // you can set Filters to narrow down the results if needed
        TreeWalk treeWalk = new TreeWalk(m_localRepo);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(false);
        while (treeWalk.next()) {
            if (treeWalk.isSubtree()) {
                //System.out.println("dir: " + treeWalk.getPathString());
                treeWalk.enterSubtree();
            } else {
                //System.out.println("file: " + treeWalk.getPathString());
                result.add(treeWalk.getPathString());
            }
        }
    }

    return result;
}

From source file:com.nlbhub.nlb.vcs.GitAdapter.java

License:Open Source License

@Override
public void reset(String path) throws NLBVCSException {
    try {/*ww  w . j a va  2  s. c o m*/
        Status status = getStatus(path);
        m_git.reset().addPath(path).setRef(Constants.HEAD).call();
        switch (status) {
        case Added:
            m_statuses.put(path, Status.Unknown);
            break;
        case Removed:
        case Modified:
        case Missing:
        case Clean:
            m_statuses.put(path, Status.Clean);
            break;
        case Unknown:
        case Ignored:
            throw new NLBVCSException("Cannot issue reset command for file with path = " + path
                    + ", because its status was " + status);
        }
    } catch (GitAPIException e) {
        throw new NLBVCSException("Error while adding to the Git repository", e);
    }
}

From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java

License:Open Source License

public static void getLastRevision(Git git, String base, String name, String rev, OutputStream out, String ext)
        throws WsSrvException, IOException {

    checkFile(base, name, ext);/*  w ww . j  ava2s.c  o m*/
    String fp = getLocalPath(name);

    // find the HEAD
    ObjectId lastCommitId = git.getRepository().resolve(Constants.HEAD);

    // a RevWalk allows to walk over commits based on 
    //                            some filtering that is defined
    RevWalk revWalk = new RevWalk(git.getRepository());
    RevCommit commit = revWalk.parseCommit(lastCommitId);
    // and using commit's tree find the path
    RevTree tree = commit.getTree();
    System.out.println("Having tree: " + tree);

    // now try to find a specific file
    TreeWalk treeWalk = new TreeWalk(git.getRepository());
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.create(fp));

    if (!treeWalk.next()) {
        throw new IllegalStateException("Did not find expected file 'README.md'");
    }

    ObjectId objectId = treeWalk.getObjectId(0);
    System.out.println("ObjectId: " + objectId.toString());
    ObjectLoader loader = git.getRepository().open(objectId);

    // and then one can the loader to read the file
    loader.copyTo(System.out);

    revWalk.dispose();

}

From source file:com.peergreen.configuration.git.GitManager.java

License:Apache License

public ObjectId getHead() throws RepositoryException {
    try {/*from w  w w .jav  a2  s .  co  m*/
        return repository.resolve(Constants.HEAD);
    } catch (IOException e) {
        throw new RepositoryException("Cannot get HEAD reference", e);
    }
}

From source file:com.pieceof8.gradle.snapshot.GitScmProvider.java

License:Apache License

/** {@inheritDoc} */
@Override//from  www.j  a  v a  2 s.com
@SneakyThrows(IOException.class)
public Commit getCommit() {
    if (repoDir == null) {
        throw new IllegalArgumentException("'repoDir' must not be null");
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    @Cleanup
    Repository repo = builder.setGitDir(repoDir).readEnvironment().findGitDir().build();
    StoredConfig conf = repo.getConfig();

    int abbrev = Commit.ABBREV_LENGTH;
    if (conf != null) {
        abbrev = conf.getInt("core", "abbrev", abbrev);
    }

    val sdf = new SimpleDateFormat(extension.getDateFormat());

    val HEAD = repo.getRef(Constants.HEAD);
    if (HEAD == null) {
        val msg = "Could not get HEAD Ref, the repository may be corrupt.";
        throw new RuntimeException(msg);
    }

    RevWalk revWalk = new RevWalk(repo);
    if (HEAD.getObjectId() == null) {
        val msg = "Could not find any commits from HEAD ref.";
        throw new RuntimeException(msg);
    }
    RevCommit commit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(commit);

    try {
        // git commit time in sec and java datetime is in ms
        val commitTime = new Date(commit.getCommitTime() * 1000L);
        val ident = commit.getAuthorIdent();

        return new Commit(sdf.format(new Date()), // build time
                conf.getString("user", null, "name"), conf.getString("user", null, "email"), repo.getBranch(),
                commit.getName(), sdf.format(commitTime), ident.getName(), ident.getEmailAddress(),
                commit.getFullMessage().trim());
    } finally {
        revWalk.dispose();
    }
}

From source file:com.puppycrawl.tools.checkstyle.CommitValidationTest.java

License:Open Source License

private static RevCommitsPair resolveRevCommitsPair(Repository repo) {
    RevCommitsPair revCommitIteratorPair;
    try {/*  w w w .j  a  v a  2 s.co  m*/
        Iterator<RevCommit> first;
        Iterator<RevCommit> second;

        RevWalk revWalk = new RevWalk(repo);

        ObjectId headId = repo.resolve(Constants.HEAD);
        RevCommit headCommit = revWalk.parseCommit(headId);

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

            first = new Git(repo).log().add(firstParent).call().iterator();
            second = new Git(repo).log().add(secondParent).call().iterator();
        } else {
            first = new Git(repo).log().call().iterator();
            second = Collections.emptyIterator();
        }

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

    return revCommitIteratorPair;
}

From source file:com.rimerosolutions.ant.git.tasks.CurrentBranchTask.java

License:Apache License

@Override
protected void doExecute() {
    try {//from   ww  w .  j av  a 2 s.c  o  m
        Repository repository = git.getRepository();
        String branch = repository.getBranch();
        // Backward compatibility
        getProject().setProperty(outputProperty, branch);

        ObjectId objectId = repository.getRef(Constants.HEAD).getObjectId();
        // Extended (nested) properties
        if (objectId != null) {
            getProject().setProperty(outputProperty + ".name", branch);
            getProject().setProperty(outputProperty + ".id", objectId.name());
            getProject().setProperty(outputProperty + ".shortId", objectId.abbreviate(8).name());
        }
    } catch (IOException e) {
        throw new GitBuildException("Could not query the current branch.", e);
    }
}