Search in sources :

Example 21 with DirCacheBuilder

use of org.eclipse.jgit.dircache.DirCacheBuilder in project gitblit by gitblit.

the class RefLogUtils method createIndex.

/**
 * Creates an in-memory index of the reflog entry.
 *
 * @param repo
 * @param headId
 * @param commands
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, Collection<ReceiveCommand> commands) throws IOException {
    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();
    long now = System.currentTimeMillis();
    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // add receive commands to the temporary index
        for (ReceiveCommand command : commands) {
            // use the ref names as the path names
            String path = command.getRefName();
            ignorePaths.add(path);
            StringBuilder change = new StringBuilder();
            change.append(command.getType().name()).append(' ');
            switch(command.getType()) {
                case CREATE:
                    change.append(ObjectId.zeroId().getName());
                    change.append(' ');
                    change.append(command.getNewId().getName());
                    break;
                case UPDATE:
                case UPDATE_NONFASTFORWARD:
                    change.append(command.getOldId().getName());
                    change.append(' ');
                    change.append(command.getNewId().getName());
                    break;
                case DELETE:
                    change = null;
                    break;
            }
            if (change == null) {
                // ref deleted
                continue;
            }
            String content = change.toString();
            // create an index entry for this attachment
            final DirCacheEntry dcEntry = new DirCacheEntry(path);
            dcEntry.setLength(content.length());
            dcEntry.setLastModified(now);
            dcEntry.setFileMode(FileMode.REGULAR_FILE);
            // insert object
            dcEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes("UTF-8")));
            // 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.close();
        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.close();
    }
    return inCoreIndex;
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DirCache(org.eclipse.jgit.dircache.DirCache) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) TreeSet(java.util.TreeSet) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk)

Example 22 with DirCacheBuilder

use of org.eclipse.jgit.dircache.DirCacheBuilder in project gerrit by GerritCodeReview.

the class SubmoduleCommitsTest method directUpdateSubmodule.

private CodeReviewCommit directUpdateSubmodule(Project.NameKey project, String refName, Project.NameKey path, AnyObjectId id) throws Exception {
    OpenRepo or = mergeOpRepoManager.getRepo(project);
    Repository serverRepo = or.repo;
    ObjectInserter ins = or.ins;
    CodeReviewRevWalk rw = or.rw;
    Ref ref = serverRepo.exactRef(refName);
    assertWithMessage(refName).that(ref).isNotNull();
    ObjectId oldCommitId = ref.getObjectId();
    DirCache dc = DirCache.newInCore();
    DirCacheBuilder b = dc.builder();
    b.addTree(new byte[0], DirCacheEntry.STAGE_0, rw.getObjectReader(), rw.parseTree(oldCommitId));
    b.finish();
    DirCacheEditor e = dc.editor();
    e.add(new PathEdit(path.get()) {

        @Override
        public void apply(DirCacheEntry ent) {
            ent.setFileMode(FileMode.GITLINK);
            ent.setObjectId(id);
        }
    });
    e.finish();
    CommitBuilder cb = new CommitBuilder();
    cb.addParentId(oldCommitId);
    cb.setTreeId(dc.writeTree(ins));
    cb.setAuthor(ident);
    cb.setCommitter(ident);
    cb.setMessage("Direct update submodule " + path);
    ObjectId newCommitId = ins.insert(cb);
    ins.flush();
    RefUpdate ru = serverRepo.updateRef(refName);
    ru.setExpectedOldObjectId(oldCommitId);
    ru.setNewObjectId(newCommitId);
    assertThat(ru.update()).isEqualTo(RefUpdate.Result.FAST_FORWARD);
    return rw.parseCommit(newCommitId);
}
Also used : DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) PathEdit(org.eclipse.jgit.dircache.DirCacheEditor.PathEdit) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) DirCacheEditor(org.eclipse.jgit.dircache.DirCacheEditor) DirCache(org.eclipse.jgit.dircache.DirCache) TestRepository(org.eclipse.jgit.junit.TestRepository) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) OpenRepo(com.google.gerrit.server.submit.MergeOpRepoManager.OpenRepo) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 23 with DirCacheBuilder

use of org.eclipse.jgit.dircache.DirCacheBuilder in project VoxelGamesLibv2 by VoxelGamesLib.

the class CustomAddCommand method call.

/**
 * Executes the {@code Add} command. Each instance of this class should only be used for one invocation of the
 * command. Don't call this method twice on an instance.
 *
 * @return the DirCache after Add
 */
@Override
@Nonnull
public DirCache call() throws GitAPIException {
    if (filepatterns.isEmpty())
        throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
    checkCallable();
    DirCache dc = null;
    // $NON-NLS-1$
    boolean addAll = filepatterns.contains(".");
    try (ObjectInserter inserter = repo.newObjectInserter();
        NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
        tw.setOperationType(OperationType.CHECKIN_OP);
        dc = repo.lockDirCache();
        DirCacheBuilder builder = dc.builder();
        tw.addTree(new DirCacheBuildIterator(builder));
        if (workingTreeIterator == null)
            workingTreeIterator = new FileTreeIterator(repo);
        workingTreeIterator.setDirCacheIterator(tw, 0);
        tw.addTree(workingTreeIterator);
        if (!addAll)
            tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
        byte[] lastAdded = null;
        while (tw.next()) {
            DirCacheIterator c = tw.getTree(0, DirCacheIterator.class);
            WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
            // if (c == null && f != null && f.isEntryIgnored()) {
            // // file is not in index but is ignored, do nothing
            // continue;
            // } else if (c == null && update) {
            // // Only update of existing entries was requested.
            // continue;
            // }
            // JUST FUCK YOU
            DirCacheEntry entry = c != null ? c.getDirCacheEntry() : null;
            if (entry != null && entry.getStage() > 0 && lastAdded != null && lastAdded.length == tw.getPathLength() && tw.isPathPrefix(lastAdded, lastAdded.length) == 0) {
                // new DirCacheEntry per path.
                continue;
            }
            if (tw.isSubtree() && !tw.isDirectoryFileConflict()) {
                tw.enterSubtree();
                continue;
            }
            if (f == null) {
                // working tree file does not exist
                if (entry != null && (!update || GITLINK == entry.getFileMode())) {
                    builder.add(entry);
                }
                continue;
            }
            if (entry != null && entry.isAssumeValid()) {
                // Index entry is marked assume valid. Even though
                // the user specified the file to be added JGit does
                // not consider the file for addition.
                builder.add(entry);
                continue;
            }
            if ((f.getEntryRawMode() == TYPE_TREE && f.getIndexFileMode(c) != FileMode.GITLINK) || (f.getEntryRawMode() == TYPE_GITLINK && f.getIndexFileMode(c) == FileMode.TREE)) {
                // Index entry exists and is symlink, gitlink or file,
                // otherwise the tree would have been entered above.
                // Replace the index entry by diving into tree of files.
                tw.enterSubtree();
                continue;
            }
            byte[] path = tw.getRawPath();
            if (entry == null || entry.getStage() > 0) {
                entry = new DirCacheEntry(path);
            }
            FileMode mode = f.getIndexFileMode(c);
            entry.setFileMode(mode);
            if (GITLINK != mode) {
                entry.setLength(f.getEntryLength());
                entry.setLastModified(f.getEntryLastModified());
                long len = f.getEntryContentLength();
                // inserting. TODO: Fix this by using Buffers.
                try (InputStream in = f.openEntryStream()) {
                    ObjectId id = inserter.insert(OBJ_BLOB, len, in);
                    entry.setObjectId(id);
                }
            } else {
                entry.setLength(0);
                entry.setLastModified(0);
                entry.setObjectId(f.getEntryObjectId());
            }
            builder.add(entry);
            lastAdded = path;
        }
        inserter.flush();
        builder.commit();
        setCallable(false);
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof FilterFailedException)
            throw (FilterFailedException) cause;
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
    } finally {
        if (dc != null)
            dc.unlock();
    }
    return dc;
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) WorkingTreeIterator(org.eclipse.jgit.treewalk.WorkingTreeIterator) ObjectId(org.eclipse.jgit.lib.ObjectId) InputStream(java.io.InputStream) NoFilepatternException(org.eclipse.jgit.api.errors.NoFilepatternException) DirCacheBuildIterator(org.eclipse.jgit.dircache.DirCacheBuildIterator) IOException(java.io.IOException) NameConflictTreeWalk(org.eclipse.jgit.treewalk.NameConflictTreeWalk) DirCache(org.eclipse.jgit.dircache.DirCache) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) FilterFailedException(org.eclipse.jgit.api.errors.FilterFailedException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) DirCacheIterator(org.eclipse.jgit.dircache.DirCacheIterator) FileTreeIterator(org.eclipse.jgit.treewalk.FileTreeIterator) Nonnull(javax.annotation.Nonnull)

Aggregations

DirCacheBuilder (org.eclipse.jgit.dircache.DirCacheBuilder)23 DirCache (org.eclipse.jgit.dircache.DirCache)21 DirCacheEntry (org.eclipse.jgit.dircache.DirCacheEntry)16 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)9 ObjectId (org.eclipse.jgit.lib.ObjectId)8 IOException (java.io.IOException)7 Repository (org.eclipse.jgit.lib.Repository)6 InputStream (java.io.InputStream)5 RevWalk (org.eclipse.jgit.revwalk.RevWalk)4 IStatus (org.eclipse.core.runtime.IStatus)3 JGitInternalException (org.eclipse.jgit.api.errors.JGitInternalException)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 TreeSet (java.util.TreeSet)2 Nonnull (javax.annotation.Nonnull)2 IFile (org.eclipse.core.resources.IFile)2 CoreException (org.eclipse.core.runtime.CoreException)2 TestProject (org.eclipse.egit.core.test.TestProject)2 TestRepository (org.eclipse.egit.core.test.TestRepository)2 ConcurrentRefUpdateException (org.eclipse.jgit.api.errors.ConcurrentRefUpdateException)2