Example usage for org.eclipse.jgit.lib Repository resolve

List of usage examples for org.eclipse.jgit.lib Repository resolve

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository resolve.

Prototype

@Nullable
public ObjectId resolve(String revstr)
        throws AmbiguousObjectException, IncorrectObjectTypeException, RevisionSyntaxException, IOException 

Source Link

Document

Parse a git revision string and return an object id.

Usage

From source file:com.gitblit.servlet.BranchGraphServlet.java

License:Eclipse Distribution License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream is = null;//from ww  w .j ava2 s . com
    Repository r = null;
    PlotWalk rw = null;
    try {
        String repository = request.getParameter("r");
        if (StringUtils.isEmpty(repository)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().append("Bad request");
            return;
        }
        String objectId = request.getParameter("h");
        String length = request.getParameter("l");

        r = repositoryManager.getRepository(repository);
        if (r == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().append("Bad request");
            return;
        }

        rw = new PlotWalk(r);
        if (StringUtils.isEmpty(objectId)) {
            objectId = JGitUtils.getHEADRef(r);
        }

        ObjectId id = r.resolve(objectId);
        if (id == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().append("Bad request");
            return;
        }
        rw.markStart(rw.lookupCommit(id));

        // default to the items-per-page setting, unless specified
        int maxCommits = settings.getInteger(Keys.web.itemsPerPage, 50);
        int requestedCommits = maxCommits;
        if (!StringUtils.isEmpty(length)) {
            int l = Integer.parseInt(length);
            if (l > 0) {
                requestedCommits = l;
            }
        }

        // fetch the requested commits plus some extra so that the last
        // commit displayed *likely* has correct lane assignments
        CommitList commitList = new CommitList();
        commitList.source(rw);
        commitList.fillTo(2 * Math.max(requestedCommits, maxCommits));

        // determine the appropriate width for the image
        int numLanes = 1;
        int numCommits = Math.min(requestedCommits, commitList.size());
        if (numCommits > 1) {
            // determine graph width
            Set<String> parents = new TreeSet<String>();
            for (int i = 0; i < commitList.size(); i++) {
                PlotCommit<Lane> commit = commitList.get(i);
                boolean checkLane = false;

                if (i < numCommits) {
                    // commit in visible list
                    checkLane = true;

                    // remember parents
                    for (RevCommit p : commit.getParents()) {
                        parents.add(p.getName());
                    }
                } else if (parents.contains(commit.getName())) {
                    // commit outside visible list, but it is a parent of a
                    // commit in the visible list so we need to know it's lane
                    // assignment
                    checkLane = true;
                }

                if (checkLane) {
                    int pos = commit.getLane().getPosition();
                    numLanes = Math.max(numLanes, pos + 1);
                }
            }
        }

        int graphWidth = numLanes * LANE_WIDTH + RIGHT_PAD;
        int rowHeight = ROW_HEIGHT;

        // create an image buffer and render the lanes
        BufferedImage image = new BufferedImage(graphWidth, rowHeight * numCommits,
                BufferedImage.TYPE_INT_ARGB);

        Graphics2D g = null;
        try {
            g = image.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            LanesRenderer renderer = new LanesRenderer();
            for (int i = 0; i < commitList.size(); i++) {
                PlotCommit<Lane> commit = commitList.get(i);
                Graphics row = g.create(0, i * rowHeight, graphWidth, rowHeight);
                try {
                    renderer.paint(row, commit, rowHeight, graphWidth);
                } finally {
                    row.dispose();
                    row = null;
                }
            }
        } finally {
            if (g != null) {
                g.dispose();
                g = null;
            }
        }

        // write the image buffer to the client
        response.setContentType("image/png");
        if (numCommits > 1) {
            response.setHeader("Cache-Control", "public, max-age=60, must-revalidate");
            response.setDateHeader("Last-Modified", JGitUtils.getCommitDate(commitList.get(0)).getTime());
        }
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
        os.flush();
        image.flush();
        image = null;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            is.close();
            is = null;
        }
        if (rw != null) {
            rw.dispose();
            rw = null;
        }
        if (r != null) {
            r.close();
            r = null;
        }
    }
}

From source file:com.gitblit.tickets.BranchTicketService.java

License:Apache License

/**
 * Reads a file from the tickets branch.
 *
 * @param db/*from  w w w  .j a va2 s.  c  o m*/
 * @param file
 * @return the file content or null
 */
private String readTicketsFile(Repository db, String file) {
    RevWalk rw = null;
    try {
        ObjectId treeId = db.resolve(BRANCH + "^{tree}");
        if (treeId == null) {
            return null;
        }
        rw = new RevWalk(db);
        RevTree tree = rw.lookupTree(treeId);
        if (tree != null) {
            return JGitUtils.getStringContent(db, tree, file, Constants.ENCODING);
        }
    } catch (IOException e) {
        log.error("failed to read " + file, e);
    } finally {
        if (rw != null) {
            rw.close();
        }
    }
    return null;
}

From source file:com.gitblit.tickets.BranchTicketService.java

License:Apache License

/**
 * Deletes a ticket from the repository.
 *
 * @param ticket/*from w  w  w .  j  a  v  a 2s .com*/
 * @return true if successful
 */
@Override
protected synchronized boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket,
        String deletedBy) {
    if (ticket == null) {
        throw new RuntimeException("must specify a ticket!");
    }

    boolean success = false;
    Repository db = repositoryManager.getRepository(ticket.repository);
    try {
        RefModel ticketsBranch = getTicketsBranch(db);

        if (ticketsBranch == null) {
            throw new RuntimeException(BRANCH + " does not exist!");
        }
        String ticketPath = toTicketPath(ticket.number);

        TreeWalk treeWalk = null;
        try {
            ObjectId treeId = db.resolve(BRANCH + "^{tree}");

            // Create the in-memory index of the new/updated ticket
            DirCache index = DirCache.newInCore();
            DirCacheBuilder builder = index.builder();

            // Traverse HEAD to add all other paths
            treeWalk = new TreeWalk(db);
            int hIdx = -1;
            if (treeId != null) {
                hIdx = treeWalk.addTree(treeId);
            }
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1) {
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                }
                if (!path.startsWith(ticketPath)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        final DirCacheEntry entry = new DirCacheEntry(path);
                        entry.setObjectId(hTree.getEntryObjectId());
                        entry.setFileMode(hTree.getEntryFileMode());

                        // add to temporary in-core index
                        builder.add(entry);
                    }
                }
            }

            // finish temporary in-core index used for this commit
            builder.finish();

            success = commitIndex(db, index, deletedBy, "- " + ticket.number);

        } catch (Throwable t) {
            log.error(MessageFormat.format("Failed to delete ticket {0,number,0} from {1}", ticket.number,
                    db.getDirectory()), t);
        } finally {
            // release the treewalk
            if (treeWalk != null) {
                treeWalk.close();
            }
        }
    } finally {
        db.close();
    }
    return success;
}

From source file:com.gitblit.tickets.BranchTicketService.java

License:Apache License

private boolean commitIndex(Repository db, DirCache index, String author, String message)
        throws IOException, ConcurrentRefUpdateException {
    final boolean forceCommit = true;
    boolean success = false;

    ObjectId headId = db.resolve(BRANCH + "^{commit}");
    if (headId == null) {
        // create the branch
        createTicketsBranch(db);//from   w ww  . j  a  va 2s .  c  o  m
    }

    success = JGitUtils.commitIndex(db, BRANCH, index, headId, forceCommit, author, "gitblit@localhost",
            message);

    return success;
}

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

License:Apache License

/**
 * Returns the diffstat between the two commits for the specified file or folder.
 *
 * @param repository//from w w w .  j ava2s  . c  o  m
 * @param base
 *            if base commit is unspecified, the diffstat is generated against
 *            the primary parent of the specified tip.
 * @param tip
 * @param path
 *            if path is specified, the diffstat is generated only for the
 *            specified file or folder. if unspecified, the diffstat is
 *            generated for the entire diff between the two commits.
 * @return patch as a string
 */
public static DiffStat getDiffStat(Repository repository, String base, String tip) {
    RevCommit baseCommit = null;
    RevCommit tipCommit = null;
    RevWalk revWalk = new RevWalk(repository);
    try {
        tipCommit = revWalk.parseCommit(repository.resolve(tip));
        if (!StringUtils.isEmpty(base)) {
            baseCommit = revWalk.parseCommit(repository.resolve(base));
        }
        return getDiffStat(repository, baseCommit, tipCommit, null);
    } catch (Exception e) {
        LOGGER.error("failed to generate diffstat!", e);
    } finally {
        revWalk.dispose();
    }
    return null;
}

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

License:Apache License

/**
 * Returns the list of lines in the specified source file annotated with the
 * source commit metadata./* w  w  w  . j  a  v  a  2  s  .c  o m*/
 *
 * @param repository
 * @param blobPath
 * @param objectId
 * @return list of annotated lines
 */
public static List<AnnotatedLine> blame(Repository repository, String blobPath, String objectId) {
    List<AnnotatedLine> lines = new ArrayList<AnnotatedLine>();
    try {
        ObjectId object;
        if (StringUtils.isEmpty(objectId)) {
            object = JGitUtils.getDefaultBranch(repository);
        } else {
            object = repository.resolve(objectId);
        }
        BlameCommand blameCommand = new BlameCommand(repository);
        blameCommand.setFilePath(blobPath);
        blameCommand.setStartCommit(object);
        BlameResult blameResult = blameCommand.call();
        RawText rawText = blameResult.getResultContents();
        int length = rawText.size();
        for (int i = 0; i < length; i++) {
            RevCommit commit = blameResult.getSourceCommit(i);
            AnnotatedLine line = new AnnotatedLine(commit, i + 1, rawText.getString(i));
            lines.add(line);
        }
    } catch (Throwable t) {
        LOGGER.error(MessageFormat.format("failed to generate blame for {0} {1}!", blobPath, objectId), t);
    }
    return lines;
}

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

License:Apache License

/**
 * Returns all the issues in the repository. Querying issues from the
 * repository requires deserializing all changes for all issues. This is an
 * expensive process and not recommended. Issues should be indexed by Lucene
 * and queries should be executed against that index.
 * /*from ww  w .  j  a  va 2s .  c  om*/
 * @param repository
 * @param filter
 *            optional issue filter to only return matching results
 * @return a list of issues
 */
public static List<IssueModel> getIssues(Repository repository, IssueFilter filter) {
    List<IssueModel> list = new ArrayList<IssueModel>();
    RefModel issuesBranch = getIssuesBranch(repository);
    if (issuesBranch == null) {
        return list;
    }

    // Collect the set of all issue paths
    Set<String> issuePaths = new HashSet<String>();
    final TreeWalk tw = new TreeWalk(repository);
    try {
        RevCommit head = JGitUtils.getCommit(repository, GB_ISSUES);
        tw.addTree(head.getTree());
        tw.setRecursive(false);
        while (tw.next()) {
            if (tw.getDepth() < 2 && tw.isSubtree()) {
                tw.enterSubtree();
                if (tw.getDepth() == 2) {
                    issuePaths.add(tw.getPathString());
                }
            }
        }
    } catch (IOException e) {
        error(e, repository, "{0} failed to query issues");
    } finally {
        tw.release();
    }

    // Build each issue and optionally filter out unwanted issues

    for (String issuePath : issuePaths) {
        RevWalk rw = new RevWalk(repository);
        try {
            RevCommit start = rw.parseCommit(repository.resolve(GB_ISSUES));
            rw.markStart(start);
        } catch (Exception e) {
            error(e, repository, "Failed to find {1} in {0}", GB_ISSUES);
        }
        TreeFilter treeFilter = AndTreeFilter.create(PathFilterGroup.createFromStrings(issuePath),
                TreeFilter.ANY_DIFF);
        rw.setTreeFilter(treeFilter);
        Iterator<RevCommit> revlog = rw.iterator();

        List<RevCommit> commits = new ArrayList<RevCommit>();
        while (revlog.hasNext()) {
            commits.add(revlog.next());
        }

        // release the revwalk
        rw.release();

        if (commits.size() == 0) {
            LOGGER.warn("Failed to find changes for issue " + issuePath);
            continue;
        }

        // sort by commit order, first commit first
        Collections.reverse(commits);

        StringBuilder sb = new StringBuilder("[");
        boolean first = true;
        for (RevCommit commit : commits) {
            if (!first) {
                sb.append(',');
            }
            String message = commit.getFullMessage();
            // commit message is formatted: C ISSUEID\n\nJSON
            // C is an single char commit code
            // ISSUEID is an SHA-1 hash
            String json = message.substring(43);
            sb.append(json);
            first = false;
        }
        sb.append(']');

        // Deserialize the JSON array as a Collection<Change>, this seems
        // slightly faster than deserializing each change by itself.
        Collection<Change> changes = JsonUtils.fromJsonString(sb.toString(),
                new TypeToken<Collection<Change>>() {
                }.getType());

        // create an issue object form the changes
        IssueModel issue = buildIssue(changes, true);

        // add the issue, conditionally, to the list
        if (filter == null) {
            list.add(issue);
        } else {
            if (filter.accept(issue)) {
                list.add(issue);
            }
        }
    }

    // sort the issues by creation
    Collections.sort(list);
    return list;
}

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

License:Apache License

/**
 * Deletes an issue from the repository.
 * /*from   w w w.  j  ava 2s  .c  o m*/
 * @param repository
 * @param issueId
 * @return true if successful
 */
public static boolean deleteIssue(Repository repository, String issueId, String author) {
    boolean success = false;
    RefModel issuesBranch = getIssuesBranch(repository);

    if (issuesBranch == null) {
        throw new RuntimeException("gb-issues branch does not exist!");
    }

    if (StringUtils.isEmpty(issueId)) {
        throw new RuntimeException("must specify an issue id!");
    }

    String issuePath = getIssuePath(issueId);

    String message = "- " + issueId;
    try {
        ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue
            DirCache index = DirCache.newInCore();
            DirCacheBuilder dcBuilder = index.builder();
            // Traverse HEAD to add all other paths
            TreeWalk treeWalk = new TreeWalk(repository);
            int hIdx = -1;
            if (headId != null)
                hIdx = treeWalk.addTree(new RevWalk(repository).parseTree(headId));
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1)
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                if (!path.startsWith(issuePath)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        // create a new DirCacheEntry with data retrieved
                        // from HEAD
                        final DirCacheEntry dcEntry = new DirCacheEntry(path);
                        dcEntry.setObjectId(hTree.getEntryObjectId());
                        dcEntry.setFileMode(hTree.getEntryFileMode());

                        // add to temporary in-core index
                        dcBuilder.add(dcEntry);
                    }
                }
            }

            // release the treewalk
            treeWalk.release();

            // finish temporary in-core index used for this commit
            dcBuilder.finish();

            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent ident = new PersonIdent(author, "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(GB_ISSUES);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            GB_ISSUES, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to delete issue {1} to {0}", issueId);
    }
    return success;
}

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

License:Apache License

/**
 * Commit a change to the repository. Each issue is composed on changes.
 * Issues are built from applying the changes in the order they were
 * committed to the repository. The changes are actually specified in the
 * commit messages and not in the RevTrees which allows for clean,
 * distributed merging./*from   w w w .jav  a2s  .  c  om*/
 * 
 * @param repository
 * @param issueId
 * @param change
 * @return true, if the change was committed
 */
private static boolean commit(Repository repository, String issueId, Change change) {
    boolean success = false;

    try {
        // assign ids to new attachments
        // attachments are stored by an SHA1 id
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                if (!ArrayUtils.isEmpty(attachment.content)) {
                    byte[] prefix = (change.created.toString() + change.author).getBytes();
                    byte[] bytes = new byte[prefix.length + attachment.content.length];
                    System.arraycopy(prefix, 0, bytes, 0, prefix.length);
                    System.arraycopy(attachment.content, 0, bytes, prefix.length, attachment.content.length);
                    attachment.id = "attachment-" + StringUtils.getSHA1(bytes);
                }
            }
        }

        // serialize the change as json
        // exclude any attachment from json serialization
        Gson gson = JsonUtils.gson(new ExcludeField("com.gitblit.models.IssueModel$Attachment.content"));
        String json = gson.toJson(change);

        // include the json change in the commit message
        String issuePath = getIssuePath(issueId);
        String message = change.code + " " + issueId + "\n\n" + json;

        // Create a commit file. This is required for a proper commit and
        // ensures we can retrieve the commit log of the issue path.
        //
        // This file is NOT serialized as part of the Change object.
        switch (change.code) {
        case '+': {
            // New Issue.
            Attachment placeholder = new Attachment("issue");
            placeholder.id = placeholder.name;
            placeholder.content = "DO NOT REMOVE".getBytes(Constants.CHARACTER_ENCODING);
            change.addAttachment(placeholder);
            break;
        }
        default: {
            // Update Issue.
            String changeId = StringUtils.getSHA1(json);
            Attachment placeholder = new Attachment("change-" + changeId);
            placeholder.id = placeholder.name;
            placeholder.content = "REMOVABLE".getBytes(Constants.CHARACTER_ENCODING);
            change.addAttachment(placeholder);
            break;
        }
        }

        ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue
            DirCache index = createIndex(repository, headId, issuePath, change);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent ident = new PersonIdent(change.author, "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(GB_ISSUES);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            GB_ISSUES, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to commit issue {1} to {0}", issueId);
    }
    return success;
}

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

License:Apache License

/**
 * Returns the first commit on a branch. If the repository does not exist or
 * is empty, null is returned./* ww w  . ja v a2s .com*/
 *
 * @param repository
 * @param branch
 *            if unspecified, HEAD is assumed.
 * @return RevCommit
 */
public static RevCommit getFirstCommit(Repository repository, String branch) {
    if (!hasCommits(repository)) {
        return null;
    }
    RevCommit commit = null;
    try {
        // resolve branch
        ObjectId branchObject;
        if (StringUtils.isEmpty(branch)) {
            branchObject = getDefaultBranch(repository);
        } else {
            branchObject = repository.resolve(branch);
        }

        RevWalk walk = new RevWalk(repository);
        walk.sort(RevSort.REVERSE);
        RevCommit head = walk.parseCommit(branchObject);
        walk.markStart(head);
        commit = walk.next();
        walk.dispose();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to determine first commit");
    }
    return commit;
}