List of usage examples for org.eclipse.jgit.dircache DirCache editor
public DirCacheEditor editor()
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;//w w w. ja v a 2s. c om 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 w w w . j a va2 s . c om*/ }
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 ww w . j a v a2 s . co 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:org.eclipse.egit.core.GitMoveDeleteHook.java
License:Open Source License
public boolean moveFile(final IResourceTree tree, final IFile srcf, final IFile dstf, final int updateFlags, final IProgressMonitor monitor) { final boolean force = (updateFlags & IResource.FORCE) == IResource.FORCE; if (!force && !tree.isSynchronized(srcf, IResource.DEPTH_ZERO)) return false; final RepositoryMapping srcm = RepositoryMapping.getMapping(srcf); if (srcm == null) return false; final RepositoryMapping dstm = RepositoryMapping.getMapping(dstf); try {/* w w w . ja v a 2s .c om*/ final DirCache sCache = srcm.getRepository().lockDirCache(); final String sPath = srcm.getRepoRelativePath(srcf); final DirCacheEntry sEnt = sCache.getEntry(sPath); if (sEnt == null) { sCache.unlock(); return false; } final DirCacheEditor sEdit = sCache.editor(); sEdit.add(new DirCacheEditor.DeletePath(sEnt)); if (dstm != null && dstm.getRepository() == srcm.getRepository()) { final String dPath = srcm.getRepoRelativePath(dstf); sEdit.add(new DirCacheEditor.PathEdit(dPath) { @Override public void apply(final DirCacheEntry dEnt) { dEnt.copyMetaData(sEnt); } }); } if (!sEdit.commit()) tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0, CoreText.MoveDeleteHook_operationError, null)); tree.standardMoveFile(srcf, dstf, updateFlags, monitor); } catch (IOException e) { tree.failed(new Status(IStatus.ERROR, Activator.getPluginId(), 0, CoreText.MoveDeleteHook_operationError, e)); } return true; }
From source file:org.eclipse.egit.core.GitMoveDeleteHook.java
License:Open Source License
private boolean moveIndexContent(String dPath, final RepositoryMapping srcm, final String sPath) throws IOException { final DirCache sCache = srcm.getRepository().lockDirCache(); final DirCacheEntry[] sEnt = sCache.getEntriesWithin(sPath); if (sEnt.length == 0) { sCache.unlock();/*from w w w . j a v a 2 s . c o m*/ return false; } final DirCacheEditor sEdit = sCache.editor(); sEdit.add(new DirCacheEditor.DeleteTree(sPath)); final int sPathLen = sPath.length() + 1; for (final DirCacheEntry se : sEnt) { final String p = se.getPathString().substring(sPathLen); sEdit.add(new DirCacheEditor.PathEdit(dPath + p) { @Override public void apply(final DirCacheEntry dEnt) { dEnt.copyMetaData(se); } }); } return sEdit.commit(); }
From source file:org.eclipse.egit.ui.internal.actions.CompareWithIndexActionHandler.java
License:Open Source License
private ITypedElement getHeadTypedElement(final IFile baseFile) throws IOException { final RepositoryMapping mapping = RepositoryMapping.getMapping(baseFile.getProject()); final Repository repository = mapping.getRepository(); final String gitPath = mapping.getRepoRelativePath(baseFile); DirCache dc = repository.lockDirCache(); final DirCacheEntry entry = dc.getEntry(gitPath); dc.unlock();/*from www . ja v a 2 s . co m*/ if (entry == null) { // the file cannot be found in the index return new GitCompareFileRevisionEditorInput.EmptyTypedElement( NLS.bind(UIText.CompareWithIndexAction_FileNotInIndex, baseFile.getName())); } IFileRevision nextFile = GitFileRevision.inIndex(repository, gitPath); final EditableRevision next = new EditableRevision(nextFile); IContentChangeListener listener = new IContentChangeListener() { public void contentChanged(IContentChangeNotifier source) { final byte[] newContent = next.getModifiedContent(); DirCache cache = null; try { cache = repository.lockDirCache(); DirCacheEditor editor = cache.editor(); editor.add(new PathEdit(gitPath) { @Override public void apply(DirCacheEntry ent) { ent.copyMetaData(entry); ObjectInserter inserter = repository.newObjectInserter(); ent.copyMetaData(entry); ent.setLength(newContent.length); ent.setLastModified(System.currentTimeMillis()); InputStream in = new ByteArrayInputStream(newContent); try { ent.setObjectId(inserter.insert(Constants.OBJ_BLOB, newContent.length, in)); inserter.flush(); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { in.close(); } catch (IOException e) { // ignore here } } } }); try { editor.commit(); } catch (RuntimeException e) { if (e.getCause() instanceof IOException) throw (IOException) e.getCause(); else throw e; } } catch (IOException e) { Activator.handleError(UIText.CompareWithIndexAction_errorOnAddToIndex, e, true); } finally { if (cache != null) cache.unlock(); } } }; next.addContentChangeListener(listener); return next; }
From source file:org.eclipse.egit.ui.internal.staging.StagingView.java
License:Open Source License
private void unstage(IStructuredSelection selection) { if (selection.isEmpty()) return;//from w ww . j a va2 s . c om RevCommit headRev = null; try { final Ref head = currentRepository.getRef(Constants.HEAD); // head.getObjectId() is null if the repository does not contain any // commit if (head.getObjectId() != null) headRev = new RevWalk(currentRepository).parseCommit(head.getObjectId()); } catch (IOException e1) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); return; } final DirCache dirCache; final DirCacheEditor edit; try { dirCache = currentRepository.lockDirCache(); edit = dirCache.editor(); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); return; } try { updateDirCache(selection, headRev, edit); try { edit.commit(); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); } } finally { dirCache.unlock(); } }
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. *//*w w w .j a 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 void mergeCommit(final Git origin, final String targetBranchName, final String sourceBranchName, final TestFile... testFiles) throws Exception { final Repository repo = origin.getRepository(); final org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.wrap(repo); final ObjectId targetId = repo.resolve(targetBranchName); final ObjectId sourceId = repo.resolve(sourceBranchName); final DirCache dc = DirCache.newInCore(); final DirCacheEditor editor = dc.editor(); try (ObjectInserter inserter = repo.newObjectInserter()) { final ObjectId treeId = writeTestFilesToTree(dc, editor, inserter, testFiles); final ObjectId commitId = writeCommit(inserter, treeId, targetId, sourceId); updateBranch(targetBranchName, git, commitId); }//from w w w . ja v a 2 s. c o m }
From source file:org.uberfire.java.nio.fs.jgit.util.commands.SubdirectoryClone.java
License:Apache License
private Optional<ObjectId> filterCommitTree(final ObjectReader reader, final ObjectInserter inserter, final RevCommit commit) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException, UnmergedPathException { final DirCache dc = DirCache.newInCore(); final DirCacheEditor editor = dc.editor(); @SuppressWarnings("resource") final TreeWalk treeWalk = new TreeWalk(reader); int treeId = treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(true);//from ww w. j a v a 2s . co m boolean empty = true; while (treeWalk.next()) { final String pathString = treeWalk.getPathString(); final CanonicalTreeParser treeParser = treeWalk.getTree(treeId, CanonicalTreeParser.class); if (inSubdirectory(pathString)) { moveFromSubdirectoryToRoot(editor, pathString, treeParser); empty = false; } } editor.finish(); if (empty) { return Optional.empty(); } else { return Optional.of(dc.writeTree(inserter)); } }