Example usage for org.eclipse.jgit.lib CommitBuilder setParentIds

List of usage examples for org.eclipse.jgit.lib CommitBuilder setParentIds

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib CommitBuilder setParentIds.

Prototype

public void setParentIds(List<? extends AnyObjectId> newParents) 

Source Link

Document

Set the parents of this commit.

Usage

From source file:com.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java

License:Open Source License

/**
 * Creates a merged notes commit.//from w  w  w. j a v  a 2 s  .  com
 */
private RevCommit createNotesCommit(NoteMap map, ObjectInserter inserter, RevWalk revWalk, String message,
        RevCommit... parents) throws IOException {
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(map.writeTree(inserter));
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);
    if (parents.length > 0) {
        commitBuilder.setParentIds(parents);
    }
    commitBuilder.setMessage(message);
    ObjectId commitId = inserter.insert(commitBuilder);
    inserter.flush();
    return revWalk.parseCommit(commitId);
}

From source file:com.google.appraise.eclipse.core.client.git.GitNoteWriter.java

License:Open Source License

private RevCommit createCommit(NoteMap map, PersonIdent author, String message, RevCommit... parents)
        throws IOException {
    CommitBuilder b = new CommitBuilder();
    b.setTreeId(map.writeTree(inserter));
    b.setAuthor(author);/*from w  ww  . j a v  a  2  s.co m*/
    b.setCommitter(author);
    if (parents.length > 0) {
        b.setParentIds(parents);
    }
    b.setMessage(message);
    ObjectId commitId = inserter.insert(b);
    inserter.flush();
    return revWalk.parseCommit(commitId);
}

From source file:com.google.gerrit.server.edit.ChangeEditModifier.java

License:Apache License

private ObjectId createCommit(IdentifiedUser me, ObjectInserter inserter, RevCommit revision, ObjectId tree,
        String msg) throws IOException {
    CommitBuilder builder = new CommitBuilder();
    builder.setTreeId(tree);//  w ww.  ja v  a 2 s .c  o m
    builder.setParentIds(revision.getParents());
    builder.setAuthor(revision.getAuthorIdent());
    builder.setCommitter(getCommitterIdent(me));
    builder.setMessage(msg);
    return inserter.insert(builder);
}

From source file:com.google.gerrit.server.git.CreateCodeReviewNotes.java

License:Apache License

private RevCommit createCommit(NoteMap map, PersonIdent author, String message, RevCommit... parents)
        throws IOException {
    CommitBuilder b = new CommitBuilder();
    b.setTreeId(map.writeTree(inserter));
    b.setAuthor(author != null ? author : gerritIdent);
    b.setCommitter(gerritIdent);/*from  w w  w  .  ja  v a 2 s  .  c  om*/
    if (parents.length > 0) {
        b.setParentIds(parents);
    }
    b.setMessage(message);
    ObjectId commitId = inserter.insert(b);
    inserter.flush();
    return revWalk.parseCommit(commitId);
}

From source file:com.google.gerrit.server.git.SubmoduleOp.java

License:Apache License

/**
 * Update the submodules in one branch of one repository.
 *
 * @param subscriber the branch of the repository which should be changed.
 * @param updates submodule updates which should be updated to.
 * @throws SubmoduleException//from www .  j  a va2  s  . c  o m
 */
private void updateGitlinks(ReviewDb db, Branch.NameKey subscriber, Collection<SubmoduleSubscription> updates)
        throws SubmoduleException {
    PersonIdent author = null;
    StringBuilder msgbuf = new StringBuilder("Updated git submodules\n\n");
    boolean sameAuthorForAll = true;

    try (Repository pdb = repoManager.openRepository(subscriber.getParentKey())) {
        if (pdb.getRef(subscriber.get()) == null) {
            throw new SubmoduleException("The branch was probably deleted from the subscriber repository");
        }

        DirCache dc = readTree(pdb, pdb.getRef(subscriber.get()));
        DirCacheEditor ed = dc.editor();

        for (SubmoduleSubscription s : updates) {
            try (Repository subrepo = repoManager.openRepository(s.getSubmodule().getParentKey());
                    RevWalk rw = CodeReviewCommit.newRevWalk(subrepo)) {
                Ref ref = subrepo.getRefDatabase().exactRef(s.getSubmodule().get());
                if (ref == null) {
                    ed.add(new DeletePath(s.getPath()));
                    continue;
                }

                final ObjectId updateTo = ref.getObjectId();
                RevCommit newCommit = rw.parseCommit(updateTo);

                if (author == null) {
                    author = newCommit.getAuthorIdent();
                } else if (!author.equals(newCommit.getAuthorIdent())) {
                    sameAuthorForAll = false;
                }

                DirCacheEntry dce = dc.getEntry(s.getPath());
                ObjectId oldId;
                if (dce != null) {
                    if (!dce.getFileMode().equals(FileMode.GITLINK)) {
                        log.error("Requested to update gitlink " + s.getPath() + " in "
                                + s.getSubmodule().getParentKey().get() + " but entry "
                                + "doesn't have gitlink file mode.");
                        continue;
                    }
                    oldId = dce.getObjectId();
                } else {
                    // This submodule did not exist before. We do not want to add
                    // the full submodule history to the commit message, so omit it.
                    oldId = updateTo;
                }

                ed.add(new PathEdit(s.getPath()) {
                    @Override
                    public void apply(DirCacheEntry ent) {
                        ent.setFileMode(FileMode.GITLINK);
                        ent.setObjectId(updateTo);
                    }
                });
                if (verboseSuperProject) {
                    msgbuf.append("Project: " + s.getSubmodule().getParentKey().get());
                    msgbuf.append(" " + s.getSubmodule().getShortName());
                    msgbuf.append(" " + updateTo.getName());
                    msgbuf.append("\n\n");

                    try {
                        rw.markStart(newCommit);
                        rw.markUninteresting(rw.parseCommit(oldId));
                        for (RevCommit c : rw) {
                            msgbuf.append(c.getFullMessage() + "\n\n");
                        }
                    } catch (IOException e) {
                        logAndThrowSubmoduleException(
                                "Could not perform a revwalk to " + "create superproject commit message", e);
                    }
                }
            }
        }
        ed.finish();

        if (!sameAuthorForAll || author == null) {
            author = myIdent;
        }

        ObjectInserter oi = pdb.newObjectInserter();
        ObjectId tree = dc.writeTree(oi);

        ObjectId currentCommitId = pdb.getRef(subscriber.get()).getObjectId();

        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(tree);
        commit.setParentIds(new ObjectId[] { currentCommitId });
        commit.setAuthor(author);
        commit.setCommitter(myIdent);
        commit.setMessage(msgbuf.toString());
        oi.insert(commit);
        oi.flush();

        ObjectId commitId = oi.idFor(Constants.OBJ_COMMIT, commit.build());

        final RefUpdate rfu = pdb.updateRef(subscriber.get());
        rfu.setForceUpdate(false);
        rfu.setNewObjectId(commitId);
        rfu.setExpectedOldObjectId(currentCommitId);
        rfu.setRefLogMessage("Submit to " + subscriber.getParentKey().get(), true);

        switch (rfu.update()) {
        case NEW:
        case FAST_FORWARD:
            gitRefUpdated.fire(subscriber.getParentKey(), rfu);
            changeHooks.doRefUpdatedHook(subscriber, rfu, account);
            // TODO since this is performed "in the background" no mail will be
            // sent to inform users about the updated branch
            break;

        default:
            throw new IOException(rfu.getResult().name());
        }
        // Recursive call: update subscribers of the subscriber
        updateSuperProjects(db, Sets.newHashSet(subscriber));
    } catch (IOException e) {
        throw new SubmoduleException("Cannot update gitlinks for " + subscriber.get(), e);
    }
}

From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java

/**
 * Executes the {@code commit} command with all the options and parameters
 * collected by the setter methods of this class. Each instance of this
 * class should only be used for one invocation of the command (means: one
 * call to {@link #call()})//  w  ww.  j a v a  2 s  .c  o m
 *
 * @return a {@link RevCommit} object representing the successful commit.
 * @throws NoHeadException
 *             when called on a git repo without a HEAD reference
 * @throws NoMessageException
 *             when called without specifying a commit message
 * @throws UnmergedPathsException
 *             when the current index contained unmerged paths (conflicts)
 * @throws ConcurrentRefUpdateException
 *             when HEAD or branch ref is updated concurrently by someone
 *             else
 * @throws WrongRepositoryStateException
 *             when repository is not in the right state for committing
 * @throws AbortedByHookException
 *             if there are either pre-commit or commit-msg hooks present in
 *             the repository and one of them rejects the commit.
 */
public RevCommit call() throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException,
        ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException {
    checkCallable();
    Collections.sort(only);

    try (RevWalk rw = new RevWalk(repo)) {
        RepositoryState state = repo.getRepositoryState();

        if (!noVerify) {
            Hooks.preCommit(repo, hookOutRedirect).call();
        }

        processOptions(state, rw);

        if (all && !repo.isBare()) {
            try (Git git = new Git(repo)) {
                git.add().addFilepattern(".") //$NON-NLS-1$
                        .setUpdate(true).call();
            } catch (NoFilepatternException e) {
                // should really not happen
                throw new JGitInternalException(e.getMessage(), e);
            }
        }

        Ref head = repo.findRef(Constants.HEAD);
        if (head == null) {
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
        }

        // determine the current HEAD and the commit it is referring to
        ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
        if (headId == null && amend)
            throw new WrongRepositoryStateException(JGitText.get().commitAmendOnInitialNotPossible);

        if (headId != null) {
            if (amend) {
                RevCommit previousCommit = rw.parseCommit(headId);
                for (RevCommit p : previousCommit.getParents())
                    parents.add(p.getId());
                if (author == null)
                    author = previousCommit.getAuthorIdent();
            } else {
                parents.add(0, headId);
            }
        }
        if (!noVerify) {
            message = Hooks.commitMsg(repo, hookOutRedirect).setCommitMessage(message).call();
        }

        // lock the index
        //         DirCache index = repo.lockDirCache();
        index.lock();
        try (ObjectInserter odi = repo.newObjectInserter()) {
            if (!only.isEmpty())
                index = createTemporaryIndex(headId, index, rw);

            // Write the index as tree to the object database. This may
            // fail for example when the index contains unmerged paths
            // (unresolved conflicts)
            ObjectId indexTreeId = index.writeTree(odi);

            if (insertChangeId)
                insertChangeId(indexTreeId);

            // Check for empty commits
            if (headId != null && !allowEmpty.booleanValue()) {
                RevCommit headCommit = rw.parseCommit(headId);
                headCommit.getTree();
                if (indexTreeId.equals(headCommit.getTree())) {
                    return null;
                }
            }

            // Create a Commit object, populate it and write it
            CommitBuilder commit = new CommitBuilder();
            commit.setCommitter(committer);
            commit.setAuthor(author);
            commit.setMessage(message);

            commit.setParentIds(parents);
            commit.setTreeId(indexTreeId);
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevCommit revCommit = rw.parseCommit(commitId);
            RefUpdate ru = repo.updateRef(Constants.HEAD);
            ru.setNewObjectId(commitId);
            if (reflogComment != null) {
                ru.setRefLogMessage(reflogComment, false);
            } else {
                String prefix = amend ? "commit (amend): " //$NON-NLS-1$
                        : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$
                                : "commit: "; //$NON-NLS-1$
                ru.setRefLogMessage(prefix + revCommit.getShortMessage(), false);
            }
            if (headId != null) {
                ru.setExpectedOldObjectId(headId);
            } else {
                ru.setExpectedOldObjectId(ObjectId.zeroId());
            }
            Result rc = ru.forceUpdate();
            switch (rc) {
            case NEW:
            case FORCED:
            case FAST_FORWARD: {
                setCallable(false);
                if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) {
                    // Commit was successful. Now delete the files
                    // used for merge commits
                    repo.writeMergeCommitMsg(null);
                    repo.writeMergeHeads(null);
                } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeCherryPickHead(null);
                } else if (state == RepositoryState.REVERTING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeRevertHead(null);
                }
                return revCommit;
            }
            case REJECTED:
            case LOCK_FAILURE:
                throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
            default:
                throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                        Constants.HEAD, commitId.toString(), rc));
            }
        } finally {
            index.unlock();
        }
    } catch (UnmergedPathException e) {
        throw new UnmergedPathsException(e);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
    }
}

From source file:org.eclipse.egit.core.op.CommitOperation.java

License:Open Source License

private void doCommits(String actMessage, HashMap<Repository, Tree> treeMap) throws IOException, TeamException {

    String commitMessage = actMessage;
    final Date commitDate = new Date();
    final TimeZone timeZone = TimeZone.getDefault();

    final PersonIdent authorIdent = RawParseUtils.parsePersonIdent(author);
    final PersonIdent committerIdent = RawParseUtils.parsePersonIdent(committer);

    for (java.util.Map.Entry<Repository, Tree> entry : treeMap.entrySet()) {
        Tree tree = entry.getValue();//from  w  ww.j  a  va 2 s . co  m
        Repository repo = tree.getRepository();
        repo.getIndex().write();
        writeTreeWithSubTrees(tree);

        ObjectId currentHeadId = repo.resolve(Constants.HEAD);
        ObjectId[] parentIds;
        if (amending) {
            RevCommit[] parents = previousCommit.getParents();
            parentIds = new ObjectId[parents.length];
            for (int i = 0; i < parents.length; i++)
                parentIds[i] = parents[i].getId();
        } else {
            if (currentHeadId != null)
                parentIds = new ObjectId[] { currentHeadId };
            else
                parentIds = new ObjectId[0];
        }
        if (createChangeId) {
            ObjectId parentId;
            if (parentIds.length > 0)
                parentId = parentIds[0];
            else
                parentId = null;
            ObjectId changeId = ChangeIdUtil.computeChangeId(tree.getId(), parentId, authorIdent,
                    committerIdent, commitMessage);
            commitMessage = ChangeIdUtil.insertId(commitMessage, changeId);
            if (changeId != null)
                commitMessage = commitMessage.replaceAll(
                        "\nChange-Id: I0000000000000000000000000000000000000000\n", //$NON-NLS-1$
                        "\nChange-Id: I" + changeId.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(tree.getTreeId());
        commit.setParentIds(parentIds);
        commit.setMessage(commitMessage);
        commit.setAuthor(new PersonIdent(authorIdent, commitDate, timeZone));
        commit.setCommitter(new PersonIdent(committerIdent, commitDate, timeZone));

        ObjectInserter inserter = repo.newObjectInserter();
        ObjectId commitId;
        try {
            commitId = inserter.insert(commit);
            inserter.flush();
        } finally {
            inserter.release();
        }

        final RefUpdate ru = repo.updateRef(Constants.HEAD);
        ru.setNewObjectId(commitId);
        ru.setRefLogMessage(buildReflogMessage(commitMessage), false);
        if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
            throw new TeamException(NLS.bind(CoreText.CommitOperation_failedToUpdate, ru.getName(), commitId));
        }
    }
}

From source file:org.kuali.student.git.cleaner.AbstractRepositoryCleaner.java

License:Educational Community License

@Override
public final void execute() throws IOException {

    onBeforeExecute();// w ww.ja v  a 2 s .c o  m

    inserter = getRepo().newObjectInserter();

    boolean localBranchSource = true;

    if (!getBranchRefSpec().equals(Constants.R_HEADS))
        localBranchSource = false;

    dateString = formatter.print(new DateTime());

    /*
     * Track the commits that are rewritten.
     * 
     * This is important so that we can update the grafts file to relate to
     * the current parent object ids.
     */
    PrintWriter objectTranslationWriter = new PrintWriter(
            "object-translations-" + getFileNameSuffix() + "-" + dateString + ".txt");

    branchHeads = getRepo().getRefDatabase().getRefs(getBranchRefSpec());

    commitToBranchMap = new HashMap<ObjectId, Set<Ref>>();

    walkRepo = new RevWalk(getRepo());

    for (Ref branchRef : branchHeads.values()) {

        ObjectId branchObjectId = branchRef.getObjectId();

        Set<Ref> refs = commitToBranchMap.get(branchObjectId);

        if (refs == null) {
            refs = new HashSet<>();
            commitToBranchMap.put(branchObjectId, refs);
        }

        refs.add(branchRef);

        walkRepo.markStart(walkRepo.parseCommit(branchObjectId));

        onBranchHead(branchRef, branchObjectId);

    }

    if (includeTagsInRevWalk()) {

        tagHeads = getRepo().getRefDatabase().getRefs(Constants.R_TAGS);
    } else {
        tagHeads = new HashMap<String, Ref>();
    }

    commitToTagMap = new HashMap<ObjectId, Set<Ref>>();

    for (Ref tagRef : tagHeads.values()) {

        RevTag tag = walkRepo.parseTag(tagRef.getObjectId());

        ObjectId commitId = tag.getObject().getId();

        Set<Ref> refs = commitToTagMap.get(commitId);

        if (refs == null) {
            refs = new HashSet<>();
            commitToTagMap.put(commitId, refs);
        }

        refs.add(tagRef);

        walkRepo.markStart(walkRepo.parseCommit(commitId));

        onTag(tag.getId(), commitId);
    }

    onBeforeRevWalk();

    walkRepo.sort(RevSort.TOPO, true);
    walkRepo.sort(RevSort.REVERSE, true);

    Iterator<RevCommit> it = provideRevCommitIterator(walkRepo.iterator());

    deferredReferenceDeletes = new LinkedList<>();
    deferredReferenceCreates = new LinkedList<>();

    objectTranslationWriter.println("# new-object-id <space> original-object-id");

    originalCommitIdToNewCommitIdMap = new HashMap<>();

    GitTreeProcessor treeProcessor = new GitTreeProcessor(getRepo());

    processedCommits = new HashSet<ObjectId>();

    while (it.hasNext()) {

        RevCommit commit = it.next();

        boolean recreateCommitByTranslatedParent = determineIfRecreateByTranslatedParent(commit);

        GitTreeData tree = treeProcessor.extractExistingTreeDataFromCommit(commit.getId());

        boolean recreate = processCommitTree(commit, tree);

        if (!recreateCommitByTranslatedParent && !recreate) {
            processedCommits.add(commit.getId());
            continue;
        }

        /*
         * Process in reverse order from old to new.
         */
        CommitBuilder builder = new CommitBuilder();

        builder.setAuthor(commit.getAuthorIdent());
        builder.setMessage(commit.getFullMessage());

        builder.setCommitter(commit.getCommitterIdent());

        if (tree.isTreeDirty()) {

            ObjectId newTreeId = tree.buildTree(inserter);

            builder.setTreeId(newTreeId);
        } else {
            builder.setTreeId(commit.getTree().getId());
        }

        builder.setEncoding("UTF-8");

        Set<ObjectId> newParents = processParents(commit);

        builder.setParentIds(new ArrayList<>(newParents));

        ObjectId newCommitId = inserter.insert(builder);

        onNewCommit(commit, newCommitId);

        originalCommitIdToNewCommitIdMap.put(commit.getId(), newCommitId);

        objectTranslationWriter.println(newCommitId.name() + " " + commit.getId().getName());

        RevWalk commitWalk = new RevWalk(getRepo());

        RevCommit newCommit = commitWalk.parseCommit(newCommitId);

        processedCommits.add(newCommitId);

        // check if any tags need to be moved
        if (commitToTagMap.containsKey(commit.getId())) {

            Set<Ref> tags = commitToTagMap.get(commit.getId());

            Set<TagBuilder> newTagSet = new HashSet<>();

            for (Ref tagRef : tags) {

                RevTag tag = commitWalk.parseTag(tagRef.getObjectId());

                TagBuilder tb = new TagBuilder();

                tb.setMessage(tag.getFullMessage());
                tb.setObjectId(newCommit);
                tb.setTag(tag.getTagName());
                tb.setTagger(tag.getTaggerIdent());

                newTagSet.add(tb);

                deferDelete(tagRef.getName(), tagRef.getObjectId());

            }

            for (TagBuilder tagBuilder : newTagSet) {

                ObjectId tagId = inserter.insert(tagBuilder);

                String tagName = Constants.R_TAGS + tagBuilder.getTag();

                deferCreate(tagName, tagId);

                onTagRefCreate(tagName, tagId);

            }

        }

        // check if any branches need to be moved
        if (commitToBranchMap.containsKey(commit.getId())) {

            Set<Ref> refs = commitToBranchMap.get(commit.getId());

            for (Ref branchRef : refs) {

                if (localBranchSource) {

                    deferDelete(branchRef.getName(), branchRef.getObjectId());

                }

                String adjustedBranchName = Constants.R_HEADS
                        + branchRef.getName().substring(getBranchRefSpec().length());

                deferCreate(adjustedBranchName, newCommitId);

                onBranchRefCreate(adjustedBranchName, newCommitId);

            }

        }

        commitWalk.release();
    }

    inserter.flush();

    getRepo().getRefDatabase().refresh();

    log.info("Applying updates: " + deferredReferenceDeletes.size() + " deletes, "
            + deferredReferenceCreates.size() + " creates.");

    if (getExternalGitCommandPath() != null) {
        ExternalGitUtils.batchRefUpdate(getExternalGitCommandPath(), getRepo(), deferredReferenceDeletes,
                System.out);
    } else {
        GitRefUtils.batchRefUpdate(getRepo(), deferredReferenceDeletes, NullProgressMonitor.INSTANCE);
    }

    getRepo().getRefDatabase().refresh();

    if (getExternalGitCommandPath() != null) {
        ExternalGitUtils.batchRefUpdate(getExternalGitCommandPath(), getRepo(), deferredReferenceCreates,
                System.out);
    } else {

        GitRefUtils.batchRefUpdate(getRepo(), deferredReferenceCreates, NullProgressMonitor.INSTANCE);

    }

    log.info("Completed.");

    walkRepo.release();

    inserter.release();

    close();

    objectTranslationWriter.close();

}

From source file:org.kuali.student.git.importer.GitImporterParseOptions.java

License:Educational Community License

private void flushPendingBranchCommits() {

    try {/*from  ww w .  j ava 2 s  .c o  m*/

        RevWalk rw = new RevWalk(repo);

        List<GitBranchData> externalsAwareOrdering = ExternalsUtils
                .computeExternalsAwareOrdering(knownBranchMap.values());

        for (GitBranchData data : externalsAwareOrdering) {

            String branchName = data.getBranchName();

            if (data.getExternals().size() > 0) {
                ObjectInserter objectInserter = repo.newObjectInserter();

                String fusionPluginDataString = ExternalModuleUtils.createFusionMavenPluginDataFileString(
                        currentRevision, repo, data.getExternals(), revisionMapper);

                ObjectId id = objectInserter.insert(Constants.OBJ_BLOB, fusionPluginDataString.getBytes());

                try {
                    data.addBlob(data.getBranchPath() + "/" + "fusion-maven-plugin.dat", id, blobLog);
                } catch (VetoBranchException e) {
                    // should never happen
                    log.error("failed to add fusion-maven-plugin.dat to the branch skipping. branchName = "
                            + data.getBranchName(), e);
                }

                objectInserter.flush();
                objectInserter.release();
            } else {
                // check for and remove if present.
                ObjectId blobId = data.findPath(repo, "fusion-maven-plugin.dat");

                if (blobId != null)
                    data.deletePath(data.getBranchPath() + "/" + "fusion-maven-plugin.dat", currentRevision);
            }

            Set<ObjectId> parentSet = new HashSet<ObjectId>();

            ObjectId parentId = data.getParentId();

            if (parentId != null)
                parentSet.add(parentId);

            parentSet.addAll(computeSvnMergeInfoParentIds(currentRevision, data));

            parentSet.addAll(data.getMergeParentIds());

            if (data.getBlobsAdded() == 0 && !data.isBlobsDeleted() && !data.isCreated()
                    && !data.isTreeDirty()) {

                // check the parentId is the same
                Ref existingRef = repo.getRef(Constants.R_HEADS + data.getBranchName());

                if (existingRef != null) {

                    if (parentSet.size() > 0 && parentSet.contains(existingRef.getObjectId())) {
                        /*
                         * Directory changes can cause a branch data object
                         * to be created but we really only want to save it
                         * if blob's have been added or deleted.
                         */
                        log.info("skipped commit on branch " + branchName + " at " + currentRevision
                                + " due to no blob changes present.");
                        continue;
                    }

                } else {
                    // existing Ref is null
                    if (parentSet.size() == 0) {
                        log.info("skipped commit on branch " + branchName + " at " + currentRevision
                                + " due to no blob changes present.");
                        continue;
                    }

                    // else fall through
                }

                // else fall through

            }

            // only flush if the branch has data to
            // commit for the current revision
            log.debug("branch = " + branchName + " has data to commit");

            // create the commit
            CommitBuilder commitBuilder = new CommitBuilder();

            ObjectInserter inserter = repo.newObjectInserter();

            // create the tree

            ObjectId treeId = data.buildTree(inserter);

            log.debug("create new tree id = " + treeId.name());

            commitBuilder.setTreeId(treeId);

            commitBuilder.setParentIds(Arrays.asList(parentSet.toArray(new ObjectId[] {})));

            commitBuilder.setAuthor(commitData.getPersonIdent());

            commitBuilder.setCommitter(commitData.getPersonIdent());

            if (printGitSvnIds) {
                StringBuilder commitMessageBuilder = new StringBuilder();

                commitMessageBuilder.append(commitData.getCommitMessage());

                appendGitSvnId(commitMessageBuilder, repositoryBaseUrl, data.getBranchPath(), currentRevision,
                        repositoryUUID);

                commitBuilder.setMessage(commitMessageBuilder.toString());
            } else {
                // just the commit message
                commitBuilder.setMessage(commitData.getCommitMessage());
            }

            ObjectId commitId = inserter.insert(commitBuilder);

            inserter.flush();

            inserter.release();

            // post commit update the branch reference.

            // create the branch in git

            String fullBranchNameReference = Constants.R_HEADS + data.getBranchName();

            if (fullBranchNameReference.length() >= GitBranchUtils.FILE_SYSTEM_NAME_LIMIT) {

                fullBranchNameReference = Constants.R_HEADS
                        + revisionMapper.storeLargeBranchName(fullBranchNameReference, currentRevision);
            }

            if (repo.getRefDatabase().isNameConflicting(fullBranchNameReference)) {
                log.warn(fullBranchNameReference + " is conflicting with an existing reference.");
            }

            Ref ref = GitRefUtils.createOrUpdateBranch(repo, fullBranchNameReference, commitId);

            ObjectId refObjectId = ref.getObjectId();

            log.info(String.format("updated %s to %s", fullBranchNameReference, commitId.name()));

            if (!commitId.equals(refObjectId)) {
                log.warn("failed to update ref for " + branchName);
            }

            List<BranchMergeInfo> accumulatedMergeData = data.getAccumulatedBranchMergeData();

            if (accumulatedMergeData.size() > 0)
                revisionMapper.createMergeData(currentRevision, data.getBranchPath(), accumulatedMergeData);

            repo.getRefDatabase().refresh();

        }

        Map<String, Ref> headRefs = repo.getRefDatabase().getRefs(Constants.R_HEADS);

        List<Ref> refs = new ArrayList<Ref>(headRefs.values());

        revisionMapper.createRevisionMap(currentRevision, refs);

        knownBranchMap.clear();

        rw.release();

    } catch (IOException e) {
        throw new RuntimeException("flushPendingBranchCommits failed on rev = " + currentRevision, e);
    }
}

From source file:org.kuali.student.git.importer.ModuleMergeToolMain.java

License:Educational Community License

/**
 * @param args/*from  w  w  w  .j  a  v a  2 s.  c o  m*/
 */
public static void main(String[] args) {

    if (args.length != 6 && args.length != 7) {
        System.err.println(
                "USAGE: <git repository> <mode> <bare> <object id> <svn:externals containing file> <svn revision> [<ref prefix>]");
        System.err.println("\t<mode> : commit or branch");
        System.err.println("\t<bare> : 0 (false) or 1 (true)");
        System.err.println("\t<object id> : the sha1 of the commit or the name of the branch in branch mode");
        System.err.println(
                "\t<svn:externals file> : contains the content of the svn:externals property for the target");

        System.err.println("\t<ref prefix> : refs/heads (default) or say refs/remotes/origin (test clone)");
        System.exit(-1);
    }

    boolean bare = false;

    if (args[2].trim().equals("1")) {
        bare = true;
    }

    boolean branchMode = false;
    boolean commitMode = false;

    if (args[1].equals("branch"))
        branchMode = true;
    else if (args[1].equals("commit"))
        commitMode = true;

    String reference = args[3].trim();

    String svnExternalsDataFile = args[4].trim();

    Long svnRevision = Long.parseLong(args[5].trim());

    String refPrefix = Constants.R_HEADS;

    if (args.length == 7)
        refPrefix = args[6].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[0]).getAbsoluteFile(), false,
                bare);

        SvnRevisionMapper revisionMapper = new SvnRevisionMapper(repo);

        if (commitMode) {

            /*
             * 
             */

            List<ExternalModuleInfo> externals = ExternalModuleUtils
                    .extractExternalModuleInfoFromSvnExternalsInputStream(svnRevision,
                            "https://svn.kuali.org/repos/student", new FileInputStream(svnExternalsDataFile));

            /*
             * Take the existing content of the commit pointed at and then materialize the externals within it.
             */

            RevWalk rw = new RevWalk(repo);

            ObjectInserter inserter = repo.newObjectInserter();

            RevCommit commit = rw.parseCommit(ObjectId.fromString(reference));

            TreeWalk tw = new TreeWalk(repo);

            tw.setRecursive(false);

            while (tw.next()) {

                if (tw.getNameString().equals("fusion-maven-plugin.dat")) {
                    ObjectId blobId = tw.getObjectId(0);

                    ObjectLoader loader = repo.newObjectReader().open(blobId, Constants.OBJ_BLOB);

                    List<String> lines = IOUtils.readLines(loader.openStream());

                    // pull out and use the sha1's from the stream to fuse the externals.

                }
            }
            CommitBuilder commitBuilder = new CommitBuilder();

            ObjectReader or;
            commitBuilder.setTreeId(ExternalModuleUtils.createFusedTree(or = repo.newObjectReader(), inserter,
                    rw, commit, externals));

            List<ObjectId> parentIds = new LinkedList<>();

            for (int i = 0; i < commit.getParentCount(); i++) {

                RevCommit parent = commit.getParent(i);

                parentIds.add(parent.getId());

            }

            commitBuilder.setParentIds(parentIds);

            commitBuilder.setAuthor(commit.getAuthorIdent());

            commitBuilder.setCommitter(commit.getCommitterIdent());

            commitBuilder.setMessage(commit.getFullMessage());

            ObjectId commitId = inserter.insert(commitBuilder);

            log.info("new commit id = " + commitId);

            rw.release();

            inserter.release();

            or.release();
        }

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}