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:playRepository.GitRepository.java

License:Apache License

@Override
public void setDefaultBranch(String target) throws IOException {
    Result result = repository.updateRef(Constants.HEAD).link(target);
    switch (result) {
    case NEW:/*from  ww  w .  ja  v a 2 s .  com*/
    case FORCED:
    case NO_CHANGE:
        break;
    default:
        throw new IOException("Failed to update symbolic ref, got: " + result);
    }
}

From source file:playRepository.GitRepository.java

License:Apache License

private ObjectId getObjectId(String revstr) throws IOException {
    if (revstr == null) {
        return repository.resolve(Constants.HEAD);
    } else {//from   w  w  w  . j av a 2s  .  c o m
        return repository.resolve(revstr);
    }
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

private byte[] getRawFile(Repository repository, String path) throws IOException {
    RevTree tree = new RevWalk(repository).parseTree(repository.resolve(Constants.HEAD));
    TreeWalk treeWalk = TreeWalk.forPath(repository, path, tree);
    if (treeWalk.isSubtree()) {
        return null;
    } else {//w w w .j  a v  a 2 s.  c  o  m
        return repository.open(treeWalk.getObjectId(0)).getBytes();
    }
}

From source file:se.lnu.cs.doris.git.GitRepository.java

License:Open Source License

/**
 * Method to do start mining a repository.
 * @throws Exception // ww  w  .  ja  va2 s.c o  m
 */
public void mine() throws Exception {
    //Fetch the bare .git file to continue working locally only.
    this.pullBare();
    RevWalk rw = this.getRevWalk();

    try {
        //Order all commits from first to last.
        AnyObjectId headId = this.m_headRepository.resolve(Constants.HEAD);
        int i = 0;
        rw.sort(RevSort.REVERSE);

        RevCommit root = rw.parseCommit(headId);
        rw.markStart(root);

        Iterator<RevCommit> revs = rw.iterator();

        RevCommit current = rw.parseCommit(revs.next());
        Boolean startFound = this.m_startPoint == null, stopFound = false, checkLimit = this.m_limit != 0;
        int limit = 0;

        while (true) {
            if (!stopFound && this.m_endPoint != null) {
                if (current.getName().toLowerCase().equals(this.m_endPoint.toLowerCase())) {
                    GlobalMessages.miningDone(this.m_repoName);
                    break;
                }
            }
            if (checkLimit && this.m_limit <= limit) {
                GlobalMessages.miningDone(this.m_repoName);
                break;
            }
            if (!startFound) {
                if (current.getName().toLowerCase().equals(this.m_startPoint.toLowerCase())) {
                    startFound = true;
                }
            }
            if (startFound) {
                //Should work, but not the most beautiful solution.
                while (this.m_runningThreads > MAX_NUMBER_OF_THREADS) {
                    try {
                        wait();
                    } catch (Exception e) {
                    }
                }
                String name = Integer.toString(i);
                File file = new File(this.m_target + "/" + name);

                //If the commit already have been mined we remove it in case it's
                //an older version or another program.
                if (file.exists()) {
                    Utilities.deleteDirectory(file);
                }

                new Cloner(current, name, i);

                if (!this.m_noLog) {
                    GitLogger.addNode(this.m_target, this.m_repoName, name, current);
                }
                this.m_runningThreads++;
                limit++;
            }
            if (revs.hasNext()) {
                current = rw.parseCommit(revs.next());
                i++;
            } else {
                //Ugly but working to clean up after multiple threads.
                while (this.m_runningThreads > 0) {
                    Thread.sleep(200);
                }
                GlobalMessages.miningDone(this.m_repoName);
                break;
            }
        }
    } catch (Exception e) {
        this.errorHandlingMining(e, null);
    }

    if (this.m_headRepository != null) {
        this.m_headRepository.close();
    }
}

From source file:uk.ac.cam.cl.dtg.segue.database.GitDb.java

License:Apache License

/**
 * Retrieve the SHA that is at the head of the repository (based on all fetched commits).
 * //w ww  .  jav  a 2  s  . c  o m
 * @return String of sha id
 */
public synchronized String getHeadSha() {
    String result = null;

    try {
        ObjectId fetchHead = gitHandle.getRepository().resolve("origin/master");
        if (null != fetchHead) {
            result = fetchHead.getName();
        } else {
            log.warn("Problem fetching head from remote. Providing local head instead.");
            result = gitHandle.getRepository().resolve(Constants.HEAD).getName();
        }

    } catch (RevisionSyntaxException | IOException e) {
        log.error("Error getting the head from the repository.", e);
    }
    return result;
}

From source file:uk.ac.cam.UROP.twentyfourteen.database.GitDb.java

/**
 * Retrieve the SHA that is at the head of the repository (based on all
 * fetched commits)//w w  w .j  av  a  2 s.c  o  m
 *
 * @return String of sha id
 */
public String getHeadSha() {
    String result = null;

    try {
        ObjectId fetchHead = gitHandle.getRepository().resolve(Constants.FETCH_HEAD);
        if (null != fetchHead) {
            result = fetchHead.getName();
        } else {
            log.warn("Problem fetching head from remote. Providing local head instead.");
            result = gitHandle.getRepository().resolve(Constants.HEAD).getName();
        }

    } catch (RevisionSyntaxException | IOException e) {
        e.printStackTrace();
        log.error("Error getting the head from the repository.");
    }
    return result;
}

From source file:util.ChkoutCmd.java

License:Eclipse Distribution License

/**
 * @throws RefAlreadyExistsException// ww  w  . j  a v  a 2  s.c  om
 *             when trying to create (without force) a branch with a name
 *             that already exists
 * @throws RefNotFoundException
 *             if the start point or branch can not be found
 * @throws InvalidRefNameException
 *             if the provided name is <code>null</code> or otherwise
 *             invalid
 * @throws CheckoutConflictException
 *             if the checkout results in a conflict
 * @return the newly created branch
 */
public Ref call() throws GitAPIException, RefAlreadyExistsException, RefNotFoundException,
        InvalidRefNameException, CheckoutConflictException {
    checkCallable();
    processOptions();
    try {
        if (checkoutAllPaths || !paths.isEmpty()) {
            checkoutPaths();
            status = new CheckoutResult(Status.OK, paths);
            setCallable(false);
            return null;
        }

        if (createBranch) {
            Git git = new Git(repo);
            CreateBranchCommand command = git.branchCreate();
            command.setName(name);
            command.setStartPoint(getStartPoint().name());
            if (upstreamMode != null)
                command.setUpstreamMode(upstreamMode);
            command.call();
        }

        Ref headRef = repo.getRef(Constants.HEAD);
        String shortHeadRef = getShortBranchName(headRef);
        String refLogMessage = "checkout: moving from " + shortHeadRef; //$NON-NLS-1$
        ObjectId branch = repo.resolve(name);
        if (branch == null)
            throw new RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved, name));

        RevWalk revWalk = new RevWalk(repo);
        AnyObjectId headId = headRef.getObjectId();
        RevCommit headCommit = headId == null ? null : revWalk.parseCommit(headId);
        RevCommit newCommit = revWalk.parseCommit(branch);
        RevTree headTree = headCommit == null ? null : headCommit.getTree();
        DirCacheCheckout dco;
        DirCache dc = repo.lockDirCache();
        try {
            dco = new DirCacheCheckout(repo, headTree, dc, newCommit.getTree());
            dco.setFailOnConflict(false);
            try {
                dco.checkout();
            } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
                status = new CheckoutResult(Status.CONFLICTS, dco.getConflicts());
                throw new CheckoutConflictException(dco.getConflicts(), e);
            }
        } finally {
            dc.unlock();
        }
        Ref ref = repo.getRef(name);
        if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
            ref = null;
        String toName = Repository.shortenRefName(name);
        RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
        refUpdate.setForceUpdate(force);
        refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false); //$NON-NLS-1$
        Result updateResult;
        if (ref != null)
            updateResult = refUpdate.link(ref.getName());
        else {
            refUpdate.setNewObjectId(newCommit);
            updateResult = refUpdate.forceUpdate();
        }

        setCallable(false);

        boolean ok = false;
        switch (updateResult) {
        case NEW:
            ok = true;
            break;
        case NO_CHANGE:
        case FAST_FORWARD:
        case FORCED:
            ok = true;
            break;
        default:
            break;
        }

        if (!ok)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().checkoutUnexpectedResult, updateResult.name()));

        if (!dco.getToBeDeleted().isEmpty()) {
            status = new CheckoutResult(Status.NONDELETED, dco.getToBeDeleted());
        } else
            status = new CheckoutResult(new ArrayList<String>(dco.getUpdated().keySet()), dco.getRemoved());

        return ref;
    } catch (IOException ioe) {
        throw new JGitInternalException(ioe.getMessage(), ioe);
    } finally {
        if (status == null)
            status = CheckoutResult.ERROR_RESULT;
    }
}

From source file:util.ChkoutCmd.java

License:Eclipse Distribution License

private ObjectId getStartPoint() throws AmbiguousObjectException, RefNotFoundException, IOException {
    if (startCommit != null)
        return startCommit.getId();
    ObjectId result = null;/* w w  w  . j a  v  a2 s. com*/
    try {
        result = repo.resolve((startPoint == null) ? Constants.HEAD : startPoint);
    } catch (AmbiguousObjectException e) {
        throw e;
    }
    if (result == null)
        throw new RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved,
                startPoint != null ? startPoint : Constants.HEAD));
    return result;
}

From source file:wherehows.common.utils.GitUtil.java

License:Open Source License

/**
 * Fetch all commit metadata from the repo
 * @param repoDir repository directory/*from w w  w  . ja  v a  2  s  .  c  o m*/
 * @return list of commit metadata
 * @throws IOException
 * @throws GitAPIException
 */
public static List<CommitMetadata> getRepoMetadata(String repoDir) throws IOException, GitAPIException {

    List<CommitMetadata> metadataList = new ArrayList<>();

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(repoDir, ".git")).readEnvironment().findGitDir().build();

    // Current branch may not be master. Instead of hard coding determine the current branch
    String currentBranch = repository.getBranch();
    Ref head = repository.getRef("refs/heads/" + currentBranch); // current branch may not be "master"
    if (head == null) {
        return metadataList;
    }

    Git git = new Git(repository);

    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(head.getObjectId());

    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.addTree(commit.getTree());
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
        String filePath = treeWalk.getPathString();
        Iterable<RevCommit> commitLog = git.log().add(repository.resolve(Constants.HEAD)).addPath(filePath)
                .call();
        for (RevCommit r : commitLog) {
            CommitMetadata metadata = new CommitMetadata(r.getName());
            metadata.setFilePath(filePath);
            metadata.setFileName(FilenameUtils.getName(filePath));
            metadata.setMessage(r.getShortMessage().trim());
            // Difference between committer and author
            // refer to: http://git-scm.com/book/ch2-3.html
            PersonIdent committer = r.getCommitterIdent();
            PersonIdent author = r.getAuthorIdent();
            metadata.setAuthor(author.getName());
            metadata.setAuthorEmail(author.getEmailAddress());
            metadata.setCommitter(committer.getName());
            metadata.setCommitterEmail(committer.getEmailAddress());
            metadata.setCommitTime(committer.getWhen());
            metadataList.add(metadata);
        }
    }
    git.close();
    return metadataList;
}