List of usage examples for org.eclipse.jgit.dircache DirCacheEditor add
public void add(PathEdit edit)
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 va 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.ChangeEditModifier.java
License:Apache License
private static void addFileToCommit(String newFile, DirCacheEditor dce, TreeWalk tw) { final FileMode mode = tw.getFileMode(0); final ObjectId oid = tw.getObjectId(0); dce.add(new PathEdit(newFile) { @Override/* www .j a v a 2 s . c o m*/ public void apply(DirCacheEntry ent) { ent.setFileMode(mode); ent.setObjectId(oid); } }); }
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 ww .j av a2s. c om*/ */ 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 a v a2 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.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 ww.j av a 2s . com*/ 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 www . java2 s .co 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.core.op.UntrackOperation.java
License:Open Source License
private void remove(final IResource path) throws CoreException { final IProject proj = path.getProject(); final GitProjectData pd = GitProjectData.get(proj); if (pd == null) return;//from w w w .jav a 2 s . c o m final RepositoryMapping rm = pd.getRepositoryMapping(path); if (rm == null) return; final Repository db = rm.getRepository(); DirCacheEditor e = edits.get(db); if (e == null) { try { e = db.lockDirCache().editor(); } catch (IOException err) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, err)); } edits.put(db, e); mappings.put(rm, rm); } if (path instanceof IContainer) e.add(new DirCacheEditor.DeleteTree(rm.getRepoRelativePath(path))); else e.add(new DirCacheEditor.DeletePath(rm.getRepoRelativePath(path))); }
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();// w w w.ja v a2 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 updateDirCache(IStructuredSelection selection, final RevCommit headRev, final DirCacheEditor edit) { Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry entry = (StagingEntry) iterator.next(); switch (entry.getState()) { case ADDED: edit.add(new DirCacheEditor.DeletePath(entry.getPath())); break; case CHANGED: case REMOVED: // set the index object id/file mode back to our head revision try { final TreeWalk tw = TreeWalk.forPath(currentRepository, entry.getPath(), headRev.getTree()); if (tw != null) edit.add(new DirCacheEditor.PathEdit(entry.getPath()) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(tw.getFileMode(0)); ent.setObjectId(tw.getObjectId(0)); // for index & working tree compare ent.setLastModified(0); }//from w w w . ja v a 2 s. c o m }); } catch (IOException e) { // TODO fix text MessageDialog.openError(getSite().getShell(), UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); } break; default: // unstaged } } }
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.j a v a 2 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; }