Example usage for org.eclipse.jgit.dircache DirCacheEditor finish

List of usage examples for org.eclipse.jgit.dircache DirCacheEditor finish

Introduction

In this page you can find the example usage for org.eclipse.jgit.dircache DirCacheEditor finish.

Prototype

@Override
public void finish() 

Source Link

Usage

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

License:Apache License

private static ObjectId writeNewTree(TreeOperation op, RevWalk rw, ObjectInserter ins, RevCommit prevEdit,
        ObjectReader reader, String fileName, @Nullable String newFile, @Nullable final ObjectId content)
        throws IOException {
    DirCache newTree = readTree(reader, prevEdit);
    DirCacheEditor dce = newTree.editor();
    switch (op) {
    case DELETE_ENTRY:
        dce.add(new DeletePath(fileName));
        break;//from   w  w w  .j a  v  a  2s.c o  m

    case RENAME_ENTRY:
        rw.parseHeaders(prevEdit);
        TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), fileName, prevEdit.getTree());
        if (tw != null) {
            dce.add(new DeletePath(fileName));
            addFileToCommit(newFile, dce, tw);
        }
        break;

    case CHANGE_ENTRY:
        checkNotNull(content, "new content required");
        dce.add(new PathEdit(fileName) {
            @Override
            public void apply(DirCacheEntry ent) {
                if (ent.getRawMode() == 0) {
                    ent.setFileMode(FileMode.REGULAR_FILE);
                }
                ent.setObjectId(content);
            }
        });
        break;

    case RESTORE_ENTRY:
        if (prevEdit.getParentCount() == 0) {
            dce.add(new DeletePath(fileName));
            break;
        }

        RevCommit base = prevEdit.getParent(0);
        rw.parseHeaders(base);
        tw = TreeWalk.forPath(rw.getObjectReader(), fileName, base.getTree());
        if (tw == null) {
            dce.add(new DeletePath(fileName));
            break;
        }

        addFileToCommit(fileName, dce, tw);
        break;
    }
    dce.finish();
    return newTree.writeTree(ins);
}

From source file:com.google.gerrit.server.edit.tree.TreeCreator.java

License:Apache License

private static void applyPathEdits(DirCache tree, List<DirCacheEditor.PathEdit> pathEdits) {
    DirCacheEditor dirCacheEditor = tree.editor();
    pathEdits.forEach(dirCacheEditor::add);
    dirCacheEditor.finish();
}

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  w w w  . ja  v a2 s  .com
 */
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.google.gerrit.server.git.VersionedMetaData.java

License:Apache License

protected void saveFile(String fileName, byte[] raw) throws IOException {
    DirCacheEditor editor = newTree.editor();
    if (raw != null && 0 < raw.length) {
        final ObjectId blobId = inserter.insert(Constants.OBJ_BLOB, raw);
        editor.add(new PathEdit(fileName) {
            @Override/*from   www.  j ava2  s. c o m*/
            public void apply(DirCacheEntry ent) {
                ent.setFileMode(FileMode.REGULAR_FILE);
                ent.setObjectId(blobId);
            }
        });
    } else {
        editor.add(new DeletePath(fileName));
    }
    editor.finish();
}

From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 *//*from   w  ww .  ja  v  a2 s.c  o  m*/
private static DirCache createTemporaryIndex(final Git git, final ObjectId headId,
        final Map<String, File> content) {

    final DirCache inCoreIndex = DirCache.newInCore();
    final DirCacheBuilder dcBuilder = inCoreIndex.builder();
    final ObjectInserter inserter = git.getRepository().newObjectInserter();
    boolean hadFile = false;
    final Set<String> paths = new HashSet<String>(content.size());

    try {
        for (final Map.Entry<String, File> pathAndContent : content.entrySet()) {
            final String gPath = fixPath(pathAndContent.getKey());
            paths.add(gPath);
            if (pathAndContent.getValue() != null) {
                hadFile = true;
                final DirCacheEntry dcEntry = new DirCacheEntry(gPath);
                dcEntry.setLength(pathAndContent.getValue().length());
                dcEntry.setLastModified(pathAndContent.getValue().lastModified());
                dcEntry.setFileMode(REGULAR_FILE);

                final InputStream inputStream = new FileInputStream(pathAndContent.getValue());
                try {
                    final ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
                            pathAndContent.getValue().length(), inputStream);
                    dcEntry.setObjectId(objectId);
                } finally {
                    inputStream.close();
                }

                dcBuilder.add(dcEntry);
            }

            if (!hadFile) {
                final DirCacheEditor editor = inCoreIndex.editor();
                editor.add(new DirCacheEditor.DeleteTree(gPath));
                editor.finish();
            }
        }

        if (headId != null) {
            final TreeWalk treeWalk = new TreeWalk(git.getRepository());
            final int hIdx = treeWalk.addTree(new RevWalk(git.getRepository()).parseTree(headId));
            treeWalk.setRecursive(true);

            while (treeWalk.next()) {
                final String walkPath = treeWalk.getPathString();
                final CanonicalTreeParser hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);

                if (!paths.contains(walkPath)) {
                    // add entries from HEAD for all other paths
                    // create a new DirCacheEntry with data retrieved from HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(walkPath);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());

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

        dcBuilder.finish();

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        inserter.release();
    }

    return inCoreIndex;
}

From source file:org.uberfire.java.nio.fs.jgit.JGitSubdirectoryCloneTest.java

License:Apache License

private ObjectId writeTestFilesToTree(final DirCache dc, final DirCacheEditor editor, ObjectInserter inserter,
        final TestFile... testFiles) throws Exception {
    for (TestFile data : testFiles) {
        writeBlob(editor, inserter, data);
    }//from   w  w  w .ja  v a  2s  .com
    editor.finish();
    final ObjectId commitTreeId = dc.writeTree(inserter);
    return commitTreeId;
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.CreateCopyCommitTree.java

License:Apache License

public Optional<ObjectId> execute() {
    final Map<String, String> content = commitContent.getContent();

    final DirCacheEditor editor = DirCache.newInCore().editor();

    try {/*  w w  w  .j a  va  2s  .c o m*/
        iterateOverTreeWalk(git, headId, (walkPath, hTree) -> {
            final String toPath = content.get(walkPath);
            addToTemporaryInCoreIndex(editor, new DirCacheEntry(walkPath), hTree.getEntryObjectId(),
                    hTree.getEntryFileMode());
            if (toPath != null) {
                addToTemporaryInCoreIndex(editor, new DirCacheEntry(toPath), hTree.getEntryObjectId(),
                        hTree.getEntryFileMode());
            }
        });

        editor.finish();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    return buildTree(editor);
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.CreateDefaultCommitTree.java

License:Apache License

public Optional<ObjectId> execute() {
    final Map<String, File> content = commitContent.getContent();
    final Map<String, Pair<File, ObjectId>> paths = new HashMap<>(content.size());
    final Set<String> path2delete = new HashSet<>();

    final DirCacheEditor editor = DirCache.newInCore().editor();

    try {//from   w  w  w  .  j  a  v  a2  s.  c om
        for (final Map.Entry<String, File> pathAndContent : content.entrySet()) {
            final String gPath = PathUtil.normalize(pathAndContent.getKey());
            if (pathAndContent.getValue() == null) {
                path2delete.addAll(searchPathsToDelete(git, headId, gPath));
            } else {
                paths.putAll(storePathsIntoHashMap(odi, pathAndContent, gPath));
            }
        }

        iterateOverTreeWalk(git, headId, (walkPath, hTree) -> {
            if (paths.containsKey(walkPath) && paths.get(walkPath).getK2().equals(hTree.getEntryObjectId())) {
                paths.remove(walkPath);
            }

            if (paths.get(walkPath) == null && !path2delete.contains(walkPath)) {
                addToTemporaryInCoreIndex(editor, new DirCacheEntry(walkPath), hTree.getEntryObjectId(),
                        hTree.getEntryFileMode());
            }
        });

        paths.forEach((key, value) -> {
            if (value.getK1() != null) {
                editor.add(new DirCacheEditor.PathEdit(new DirCacheEntry(key)) {
                    @Override
                    public void apply(final DirCacheEntry ent) {
                        ent.setLength(value.getK1().length());
                        ent.setLastModified(value.getK1().lastModified());
                        ent.setFileMode(REGULAR_FILE);
                        ent.setObjectId(value.getK2());
                    }
                });
            }
        });

        editor.finish();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (path2delete.isEmpty() && paths.isEmpty()) {
        editor.getDirCache().clear();
        return Optional.empty();
    }

    return buildTree(editor);
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.CreateMoveCommitTree.java

License:Apache License

public Optional<ObjectId> execute() {
    final Map<String, String> content = commitContent.getContent();
    final DirCacheEditor editor = DirCache.newInCore().editor();
    final List<String> pathsAdded = new ArrayList<>();

    try {/*from   w w w.  ja  v a  2  s .com*/
        iterateOverTreeWalk(git, headId, (walkPath, hTree) -> {
            final String toPath = content.get(walkPath);
            final DirCacheEntry dcEntry = new DirCacheEntry((toPath == null) ? walkPath : toPath);
            if (!pathsAdded.contains(dcEntry.getPathString())) {
                addToTemporaryInCoreIndex(editor, dcEntry, hTree.getEntryObjectId(), hTree.getEntryFileMode());
                pathsAdded.add(dcEntry.getPathString());
            }
        });
        editor.finish();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    return buildTree(editor);
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.CreateRevertCommitTree.java

License:Apache License

public Optional<ObjectId> execute() {
    final DirCacheEditor editor = DirCache.newInCore().editor();

    try {/*from   www. j a v a  2 s .co  m*/
        iterateOverTreeWalk(git, headId, (walkPath, hTree) -> {
            addToTemporaryInCoreIndex(editor, new DirCacheEntry(walkPath), hTree.getEntryObjectId(),
                    hTree.getEntryFileMode());
        });

        editor.finish();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

    return buildTree(editor);
}