Search in sources :

Example 16 with DirCacheBuilder

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

the class GitMoveDeleteHook method deleteFile.

@Override
public boolean deleteFile(final IResourceTree tree, final IFile file, final int updateFlags, final IProgressMonitor monitor) {
    if (!org.eclipse.egit.core.Activator.autoStageDeletion()) {
        return false;
    }
    // Linked resources are not files, hence not tracked by git
    if (file.isLinked())
        return false;
    final boolean force = (updateFlags & IResource.FORCE) == IResource.FORCE;
    if (!force && !tree.isSynchronized(file, IResource.DEPTH_ZERO))
        return false;
    final RepositoryMapping map = RepositoryMapping.getMapping(file);
    if (map == null)
        return false;
    String repoRelativePath = map.getRepoRelativePath(file);
    IndexDiffCache indexDiffCache = Activator.getDefault().getIndexDiffCache();
    IndexDiffCacheEntry indexDiffCacheEntry = indexDiffCache.getIndexDiffCacheEntry(map.getRepository());
    if (indexDiffCacheEntry == null) {
        return false;
    }
    IndexDiffData indexDiff = indexDiffCacheEntry.getIndexDiff();
    if (indexDiff != null) {
        if (indexDiff.getUntracked().contains(repoRelativePath))
            return false;
        if (indexDiff.getIgnoredNotInIndex().contains(repoRelativePath))
            return false;
    }
    if (!file.exists())
        return false;
    if (file.isDerived())
        return false;
    DirCache dirc = null;
    try {
        dirc = map.getRepository().lockDirCache();
        final int first = dirc.findEntry(repoRelativePath);
        if (first < 0) {
            dirc.unlock();
            return false;
        }
        final DirCacheBuilder edit = dirc.builder();
        if (first > 0)
            edit.keep(0, first);
        final int next = dirc.nextEntry(first);
        if (next < dirc.getEntryCount())
            edit.keep(next, dirc.getEntryCount() - next);
        if (!edit.commit())
            tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0, CoreText.MoveDeleteHook_operationError, null));
        tree.standardDeleteFile(file, updateFlags, monitor);
    } catch (LockFailedException e) {
        // FIXME The index is currently locked. This notably happens during
        // rebase operations. auto-staging deletions should be queued... and
        // the queued job will have to double-check whether the file has
        // truly been deleted or if it was only deleted to be replaced by
        // another version.
        // This hook only exists to automatically add changes to the index.
        // If the index is currently locked, do not accept the
        // responsibility of deleting the file, return false to tell the
        // workspace it can continue with the standard deletion. The user
        // will have to stage the deletion later on _if_ this was truly
        // needed, which won't happen for calls triggered by merge
        // operations from the merge strategies.
        Activator.getDefault().getLog().log(new Status(IStatus.WARNING, Activator.getPluginId(), MessageFormat.format(CoreText.MoveDeleteHook_cannotAutoStageDeletion, file.getLocation())));
        return FINISH_FOR_ME;
    } catch (IOException e) {
        tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0, CoreText.MoveDeleteHook_operationError, e));
    } finally {
        if (dirc != null)
            dirc.unlock();
    }
    return true;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) DirCache(org.eclipse.jgit.dircache.DirCache) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) LockFailedException(org.eclipse.jgit.errors.LockFailedException) IndexDiffCacheEntry(org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry) RepositoryMapping(org.eclipse.egit.core.project.RepositoryMapping) IOException(java.io.IOException) IndexDiffCache(org.eclipse.egit.core.internal.indexdiff.IndexDiffCache) IndexDiffData(org.eclipse.egit.core.internal.indexdiff.IndexDiffData)

Example 17 with DirCacheBuilder

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

the class SubmoduleCommits method readTree.

private static DirCache readTree(RevWalk rw, ObjectId base) throws IOException {
    final DirCache dc = DirCache.newInCore();
    final DirCacheBuilder b = dc.builder();
    b.addTree(// no prefix path
    new byte[0], // standard stage
    DirCacheEntry.STAGE_0, rw.getObjectReader(), rw.parseTree(base));
    b.finish();
    return dc;
}
Also used : DirCache(org.eclipse.jgit.dircache.DirCache) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder)

Example 18 with DirCacheBuilder

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

the class AbstractSubmoduleSubscription method directUpdateSubmodule.

protected void directUpdateSubmodule(Project.NameKey project, String refName, Project.NameKey path, AnyObjectId id) throws Exception {
    try (Repository serverRepo = repoManager.openRepository(project);
        ObjectInserter ins = serverRepo.newObjectInserter();
        RevWalk rw = new RevWalk(serverRepo)) {
        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));
        PersonIdent ident = serverIdent.get();
        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);
    }
}
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) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) DirCacheEditor(org.eclipse.jgit.dircache.DirCacheEditor) RevWalk(org.eclipse.jgit.revwalk.RevWalk) 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) PersonIdent(org.eclipse.jgit.lib.PersonIdent) RefUpdate(org.eclipse.jgit.lib.RefUpdate) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate)

Example 19 with DirCacheBuilder

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

the class BranchTicketService method writeTicketsFile.

/**
 * Writes a file to the tickets branch.
 *
 * @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();
    }
}
Also used : DirCache(org.eclipse.jgit.dircache.DirCache) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) IOException(java.io.IOException) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) HashSet(java.util.HashSet)

Example 20 with DirCacheBuilder

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

the class BranchTicketService method deleteTicketImpl.

/**
 * Deletes a ticket from the repository.
 *
 * @param ticket
 * @return true if successful
 */
@Override
protected synchronized boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket, String deletedBy) {
    if (ticket == null) {
        throw new RuntimeException("must specify a ticket!");
    }
    boolean success = false;
    Repository db = repositoryManager.getRepository(ticket.repository);
    try {
        RefModel ticketsBranch = getTicketsBranch(db);
        if (ticketsBranch == null) {
            throw new RuntimeException(BRANCH + " does not exist!");
        }
        String ticketPath = toTicketPath(ticket.number);
        TreeWalk treeWalk = null;
        try {
            ObjectId treeId = db.resolve(BRANCH + "^{tree}");
            // Create the in-memory index of the new/updated ticket
            DirCache index = DirCache.newInCore();
            DirCacheBuilder builder = index.builder();
            // Traverse HEAD to add all other paths
            treeWalk = new TreeWalk(db);
            int hIdx = -1;
            if (treeId != null) {
                hIdx = treeWalk.addTree(treeId);
            }
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1) {
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                }
                if (!path.startsWith(ticketPath)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        final DirCacheEntry entry = new DirCacheEntry(path);
                        entry.setObjectId(hTree.getEntryObjectId());
                        entry.setFileMode(hTree.getEntryFileMode());
                        // add to temporary in-core index
                        builder.add(entry);
                    }
                }
            }
            // finish temporary in-core index used for this commit
            builder.finish();
            success = commitIndex(db, index, deletedBy, "- " + ticket.number);
        } catch (Throwable t) {
            log.error(MessageFormat.format("Failed to delete ticket {0,number,0} from {1}", ticket.number, db.getDirectory()), t);
        } finally {
            // release the treewalk
            if (treeWalk != null) {
                treeWalk.close();
            }
        }
    } finally {
        db.close();
    }
    return success;
}
Also used : RefModel(com.gitblit.models.RefModel) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectId(org.eclipse.jgit.lib.ObjectId) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk)

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