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

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

Introduction

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

Prototype

@NonNull
public ObjectInserter newObjectInserter() 

Source Link

Document

Create a new inserter to create objects in #getObjectDatabase() .

Usage

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

@Override
public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor)
        throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException {

    monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN);

    String repoFileURI = COMMENTS_FILE_URI;

    try {//from  w ww . java 2s. c om
        Git git = Git.open(new File(uri));
        Repository repository = git.getRepository();
        ObjectInserter objectInserter = repository.newObjectInserter();

        String commentRefName = getCommentRefName(modelReview);
        Ref commentRef = repository.exactRef(commentRefName);

        DirCache index = DirCache.newInCore();
        DirCacheBuilder dirCacheBuilder = index.builder();

        monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN);

        if (commentRef != null) {

            /*
             * The ref already exists so we have to copy the previous
             * RevTree to keep all already attached files
             */

            RevWalk revWalk = new RevWalk(repository);
            RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId());
            RevTree tree = prevCommit.getTree();

            List<String> ignoredFiles = new ArrayList<>();
            /*
             * add file path of the new file to the ignored file paths, as
             * we don't want any already existing old file in our new tree
             */
            ignoredFiles.add(repoFileURI);
            buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles);

            revWalk.close();
        }

        monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI));

        addCommentsToResource(modelReview, resource);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        resource.save(outputStream, null);

        // insert file as object
        byte[] content = outputStream.toByteArray();
        long length = content.length;
        InputStream inputStream = new ByteArrayInputStream(content);
        ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream);
        inputStream.close();

        // create tree entry
        DirCacheEntry entry = new DirCacheEntry(repoFileURI);
        entry.setFileMode(FileMode.REGULAR_FILE);
        entry.setLastModified(System.currentTimeMillis());
        entry.setLength(length);
        entry.setObjectId(objectId);
        dirCacheBuilder.add(entry);

        dirCacheBuilder.finish();

        // write new tree in database
        ObjectId indexTreeId = index.writeTree(objectInserter);

        monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN);

        // create commit
        CommitBuilder commitBuilder = new CommitBuilder();
        PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview");
        commitBuilder.setCommitter(personIdent);
        commitBuilder.setAuthor(personIdent);
        commitBuilder.setMessage(
                MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName()));

        if (commentRef != null) {
            commitBuilder.setParentId(commentRef.getObjectId());
        }
        commitBuilder.setTreeId(indexTreeId);

        // commit
        ObjectId commitId = objectInserter.insert(commitBuilder);
        objectInserter.flush();

        RefUpdate refUpdate = repository.updateRef(commentRefName);
        refUpdate.setNewObjectId(commitId);
        if (commentRef != null)
            refUpdate.setExpectedOldObjectId(commentRef.getObjectId());
        else
            refUpdate.setExpectedOldObjectId(ObjectId.zeroId());

        /*
         * TODO the result handling below is copied from the CommitCommand
         * class, I don't know if this is really necessary in our case
         */
        Result result = refUpdate.forceUpdate();
        switch (result) {
        case NEW:
        case FORCED:
        case FAST_FORWARD: {
            if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
                /*
                 * Commit was successful. Now delete the files used for
                 * merge commits
                 */
                repository.writeMergeCommitMsg(null);
                repository.writeMergeHeads(null);
            } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeCherryPickHead(null);
            } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeRevertHead(null);
            }
            break;
        }
        case REJECTED:
        case LOCK_FAILURE:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(),
                            refUpdate.getRef(), result));
        default:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            refUpdate.getRef().getName(), commitId.toString(), result)));
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    } finally {
        monitor.done();
    }

}

From source file:com.gitblit.build.BuildGhPages.java

License:Apache License

public static void main(String[] args) {
    Params params = new Params();
    JCommander jc = new JCommander(params);
    try {/*from  ww w .j a  va  2  s  . c o  m*/
        jc.parse(args);
    } catch (ParameterException t) {
        System.err.println(t.getMessage());
        jc.usage();
    }

    File source = new File(params.sourceFolder);
    String ghpages = "refs/heads/gh-pages";
    try {
        File gitDir = FileKey.resolve(new File(params.repositoryFolder), FS.DETECTED);
        Repository repository = new FileRepository(gitDir);

        RefModel issuesBranch = JGitUtils.getPagesBranch(repository);
        if (issuesBranch == null) {
            JGitUtils.createOrphanBranch(repository, "gh-pages", null);
        }

        System.out.println("Updating gh-pages branch...");
        ObjectId headId = repository.resolve(ghpages + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue.
            DirCache index = createIndex(repository, headId, source, params.obliterate);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent author = new PersonIdent("Gitblit", "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage("updated pages");
            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(ghpages);
                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:
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            ghpages, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
        System.out.println("gh-pages updated.");
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.gitblit.build.BuildGhPages.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * // w  w  w .  j av a  2s  .c om
 * @param repo
 * @param headId
 * @param sourceFolder
 * @param obliterate
 *            if true the source folder tree is used as the new tree for
 *            gh-pages and non-existent files are considered deleted
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, File sourceFolder, boolean obliterate)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    try {
        // Add all files to the temporary index
        Set<String> ignorePaths = new TreeSet<String>();
        List<File> files = listFiles(sourceFolder);
        for (File file : files) {
            // create an index entry for the file
            final DirCacheEntry dcEntry = new DirCacheEntry(
                    StringUtils.getRelativePath(sourceFolder.getPath(), file.getPath()));
            dcEntry.setLength(file.length());
            dcEntry.setLastModified(file.lastModified());
            dcEntry.setFileMode(FileMode.REGULAR_FILE);

            // add this entry to the ignore paths set
            ignorePaths.add(dcEntry.getPathString());

            // insert object
            InputStream inputStream = new FileInputStream(file);
            try {
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, file.length(), inputStream));
            } finally {
                inputStream.close();
            }

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

        if (!obliterate) {
            // Traverse HEAD to add all other paths
            TreeWalk treeWalk = new TreeWalk(repo);
            int hIdx = -1;
            if (headId != null)
                hIdx = treeWalk.addTree(new RevWalk(repo).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 (!ignorePaths.contains(path)) {
                    // 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();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

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

License:Apache License

/**
 * Writes a file to the tickets branch./*from   ww w  . j  a v a 2  s .c o m*/
 *
 * @param db
 * @param file
 * @param content
 * @param createdBy
 * @param msg
 */
private void writeTicketsFile(Repository db, String file, String content, String createdBy, String msg) {
    if (getTicketsBranch(db) == null) {
        createTicketsBranch(db);
    }

    DirCache newIndex = DirCache.newInCore();
    DirCacheBuilder builder = newIndex.builder();
    ObjectInserter inserter = db.newObjectInserter();

    try {
        // create an index entry for the revised index
        final DirCacheEntry idIndexEntry = new DirCacheEntry(file);
        idIndexEntry.setLength(content.length());
        idIndexEntry.setLastModified(System.currentTimeMillis());
        idIndexEntry.setFileMode(FileMode.REGULAR_FILE);

        // insert new ticket index
        idIndexEntry.setObjectId(
                inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes(Constants.ENCODING)));

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

        Set<String> ignorePaths = new HashSet<String>();
        ignorePaths.add(file);

        for (DirCacheEntry entry : JGitUtils.getTreeEntries(db, BRANCH, ignorePaths)) {
            builder.add(entry);
        }

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

        // commit the change
        commitIndex(db, newIndex, createdBy, msg);

    } catch (ConcurrentRefUpdateException e) {
        log.error("", e);
    } catch (IOException e) {
        log.error("", e);
    } finally {
        inserter.close();
    }
}

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

License:Apache License

/**
 * Creates an in-memory index of the ticket change.
 *
 * @param changeId/*from  w ww  . jav  a 2  s.co  m*/
 * @param change
 * @return an in-memory index
 * @throws IOException
 */
private DirCache createIndex(Repository db, long ticketId, Change change)
        throws IOException, ClassNotFoundException, NoSuchFieldException {

    String ticketPath = toTicketPath(ticketId);
    DirCache newIndex = DirCache.newInCore();
    DirCacheBuilder builder = newIndex.builder();
    ObjectInserter inserter = db.newObjectInserter();

    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // create/update the journal
        // exclude the attachment content
        List<Change> changes = getJournal(db, ticketId);
        changes.add(change);
        String journal = TicketSerializer.serializeJournal(changes).trim();

        byte[] journalBytes = journal.getBytes(Constants.ENCODING);
        String journalPath = ticketPath + "/" + JOURNAL;
        final DirCacheEntry journalEntry = new DirCacheEntry(journalPath);
        journalEntry.setLength(journalBytes.length);
        journalEntry.setLastModified(change.date.getTime());
        journalEntry.setFileMode(FileMode.REGULAR_FILE);
        journalEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, journalBytes));

        // add journal to index
        builder.add(journalEntry);
        ignorePaths.add(journalEntry.getPathString());

        // Add any attachments to the index
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                // build a path name for the attachment and mark as ignored
                String path = toAttachmentPath(ticketId, attachment.name);
                ignorePaths.add(path);

                // create an index entry for this attachment
                final DirCacheEntry entry = new DirCacheEntry(path);
                entry.setLength(attachment.content.length);
                entry.setLastModified(change.date.getTime());
                entry.setFileMode(FileMode.REGULAR_FILE);

                // insert object
                entry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, attachment.content));

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

        for (DirCacheEntry entry : JGitUtils.getTreeEntries(db, BRANCH, ignorePaths)) {
            builder.add(entry);
        }

        // finish the index
        builder.finish();
    } finally {
        inserter.close();
    }
    return newIndex;
}

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

License:Apache License

/**
 * Deletes an issue from the repository.
 * /*from w  ww  .  jav a  2 s. 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 ww.  j  a  v  a  2 s.c  o  m*/
 * 
 * @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.IssueUtils.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * //  w w  w .  ja  va 2  s  .  co  m
 * @param repo
 * @param headId
 * @param change
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, String issuePath, Change change)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // Add any attachments to the temporary index
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                // build a path name for the attachment and mark as ignored
                String path = issuePath + "/" + attachment.id;
                ignorePaths.add(path);

                // create an index entry for this attachment
                final DirCacheEntry dcEntry = new DirCacheEntry(path);
                dcEntry.setLength(attachment.content.length);
                dcEntry.setLastModified(change.created.getTime());
                dcEntry.setFileMode(FileMode.REGULAR_FILE);

                // insert object
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, attachment.content));

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

        // Traverse HEAD to add all other paths
        TreeWalk treeWalk = new TreeWalk(repo);
        int hIdx = -1;
        if (headId != null)
            hIdx = treeWalk.addTree(new RevWalk(repo).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 (!ignorePaths.contains(path)) {
                // 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();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

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

License:Apache License

/**
 * Create an orphaned branch in a repository.
 *
 * @param repository/*from  w w  w.ja v  a 2 s .co  m*/
 * @param branchName
 * @param author
 *            if unspecified, Gitblit will be the author of this new branch
 * @return true if successful
 */
public static boolean createOrphanBranch(Repository repository, String branchName, PersonIdent author) {
    boolean success = false;
    String message = "Created branch " + branchName;
    if (author == null) {
        author = new PersonIdent("Gitblit", "gitblit@localhost");
    }
    try {
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create a blob object to insert into a tree
            ObjectId blobId = odi.insert(Constants.OBJ_BLOB, message.getBytes(Constants.CHARACTER_ENCODING));

            // Create a tree object to reference from a commit
            TreeFormatter tree = new TreeFormatter();
            tree.append(".branch", FileMode.REGULAR_FILE, blobId);
            ObjectId treeId = odi.insert(tree);

            // Create a commit object
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setTreeId(treeId);

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

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                if (!branchName.startsWith("refs/")) {
                    branchName = "refs/heads/" + branchName;
                }
                RefUpdate ru = repository.updateRef(branchName);
                ru.setNewObjectId(commitId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                default:
                    success = false;
                }
            } finally {
                revWalk.close();
            }
        } finally {
            odi.close();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName);
    }
    return success;
}

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

License:Apache License

public static boolean commitIndex(Repository db, String branch, DirCache index, ObjectId parentId,
        boolean forceCommit, String author, String authorEmail, String message)
        throws IOException, ConcurrentRefUpdateException {
    boolean success = false;

    ObjectId headId = db.resolve(branch + "^{commit}");
    ObjectId baseId = parentId;/*from  ww w . j  ava  2  s  .c  om*/
    if (baseId == null || headId == null) {
        return false;
    }

    ObjectInserter odi = db.newObjectInserter();
    try {
        // Create the in-memory index of the new/updated ticket
        ObjectId indexTreeId = index.writeTree(odi);

        // Create a commit object
        PersonIdent ident = new PersonIdent(author, authorEmail);

        if (forceCommit == false) {
            ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
            merger.setObjectInserter(odi);
            merger.setBase(baseId);
            boolean mergeSuccess = merger.merge(indexTreeId, headId);

            if (mergeSuccess) {
                indexTreeId = merger.getResultTreeId();
            } else {
                //Manual merge required
                return false;
            }
        }

        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(ident);
        commit.setCommitter(ident);
        commit.setEncoding(com.gitblit.Constants.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(db);
        try {
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate ru = db.updateRef(branch);
            ru.setForceUpdate(forceCommit);
            ru.setNewObjectId(commitId);
            ru.setExpectedOldObjectId(headId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            Result rc = ru.update();

            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, branch,
                        commitId.toString(), rc));
            }
        } finally {
            revWalk.close();
        }
    } finally {
        odi.close();
    }
    return success;
}