List of usage examples for org.eclipse.jgit.revwalk RevWalk parseTree
@NonNull public RevTree parseTree(AnyObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException
From source file:ShowFileDiff.java
License:Apache License
private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId) throws IOException, MissingObjectException, IncorrectObjectTypeException { // from the commit we can build the tree which allows us to construct the TreeParser RevWalk walk = new RevWalk(repository); RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId)); RevTree tree = walk.parseTree(commit.getTree().getId()); CanonicalTreeParser oldTreeParser = new CanonicalTreeParser(); ObjectReader oldReader = repository.newObjectReader(); try {/*from w w w. j a v a 2 s .c o m*/ oldTreeParser.reset(oldReader, tree.getId()); } finally { oldReader.release(); } walk.dispose(); return oldTreeParser; }
From source file:MyDiffFormatter.java
License:Eclipse Distribution License
/** * Determine the differences between two trees. * <p/>/*from w w w. j av a 2 s .co m*/ * No output is created, instead only the file paths that are different are * returned. Callers may choose to format these paths themselves, or convert * them into {@link FileHeader} instances with a complete edit list by * <p/> * Either side may be null to indicate that the tree has beed added or * removed. The diff will be computed against nothing. * * @param a the old (or previous) side or null * @param b the new (or updated) side or null * @return the paths that are different. * @throws IOException trees cannot be read or file contents cannot be read. */ public List<DiffEntry> scan(AnyObjectId a, AnyObjectId b) throws IOException { assertHaveRepository(); RevWalk rw = new RevWalk(reader); RevTree aTree = a != null ? rw.parseTree(a) : null; RevTree bTree = b != null ? rw.parseTree(b) : null; return scan(aTree, bTree); }
From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java
License:Apache License
public boolean isTracked(String path) throws IOException { ObjectId objectId = localRepo.resolve(Constants.HEAD); RevTree tree;//from w w w. ja va 2 s . c o m RevWalk walk = null; if (objectId != null) { walk = new RevWalk(localRepo); tree = walk.parseTree(objectId); } else { tree = null; } try (TreeWalk treeWalk = new TreeWalk(localRepo)) { treeWalk.setRecursive(true); if (tree != null) treeWalk.addTree(tree); else treeWalk.addTree(new EmptyTreeIterator()); treeWalk.addTree(new DirCacheIterator(localRepo.readDirCache())); treeWalk.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); return treeWalk.next(); } finally { if (walk != null) walk.close(); } }
From source file:com.github.checkstyle.regression.git.DiffParser.java
License:Open Source License
/** * Creates a tree parser from a commit, to be used by diff command. * @param walk the {@link RevWalk} to parse the tree * @param commit the commit to create tree parser from * @return the tree parser//from w w w . jav a 2 s . co m * @throws IOException JGit library exception */ private static AbstractTreeIterator prepareTreeParser(RevWalk walk, RevCommit commit) throws IOException { final RevTree tree = walk.parseTree(commit.getTree().getId()); final CanonicalTreeParser returnValue; returnValue = new CanonicalTreeParser(); returnValue.reset(walk.getObjectReader(), tree.getId()); return returnValue; }
From source file:com.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java
License:Open Source License
private AbstractTreeIterator prepareTreeParserHelper(RevWalk walk, RevCommit commit) throws IOException, MissingObjectException, IncorrectObjectTypeException { RevTree tree = walk.parseTree(commit.getTree().getId()); CanonicalTreeParser oldTreeParser = new CanonicalTreeParser(); try (ObjectReader oldReader = repo.newObjectReader()) { oldTreeParser.reset(oldReader, tree.getId()); }/*from w ww . ja v a 2 s . c o m*/ return oldTreeParser; }
From source file:com.google.gerrit.acceptance.rest.change.ConfigChangeIT.java
License:Apache License
private Config readProjectConfig() throws Exception { RevWalk rw = testRepo.getRevWalk(); RevTree tree = rw.parseTree(testRepo.getRepository().resolve("HEAD")); RevObject obj = rw.parseAny(testRepo.get(tree, "project.config")); ObjectLoader loader = rw.getObjectReader().open(obj); String text = new String(loader.getCachedBytes(), UTF_8); Config cfg = new Config(); cfg.fromText(text);/*w ww . j a v a2 s. com*/ return cfg; }
From source file:com.google.gerrit.pgm.init.AllProjectsConfig.java
License:Apache License
private void save(PersonIdent ident, String msg) throws IOException { File path = getPath();/* ww w . ja v a2s . c o m*/ if (path == null) { throw new IOException("All-Projects does not exist."); } Repository repo = new FileRepository(path); try { inserter = repo.newObjectInserter(); reader = repo.newObjectReader(); try { RevWalk rw = new RevWalk(reader); try { RevTree srcTree = revision != null ? rw.parseTree(revision) : null; newTree = readTree(srcTree); saveConfig(ProjectConfig.PROJECT_CONFIG, cfg); ObjectId res = newTree.writeTree(inserter); if (res.equals(srcTree)) { // If there are no changes to the content, don't create the commit. return; } CommitBuilder commit = new CommitBuilder(); commit.setAuthor(ident); commit.setCommitter(ident); commit.setMessage(msg); commit.setTreeId(res); if (revision != null) { commit.addParentId(revision); } ObjectId newRevision = inserter.insert(commit); updateRef(repo, ident, newRevision, "commit: " + msg); revision = newRevision; } finally { rw.release(); } } finally { if (inserter != null) { inserter.release(); inserter = null; } if (reader != null) { reader.release(); reader = null; } } } finally { repo.close(); } }
From source file:com.google.gerrit.server.git.VersionedMetaData.java
License:Apache License
/** * Open a batch of updates to the same metadata ref. * <p>// w ww . ja v a2 s . c o m * This allows making multiple commits to a single metadata ref, at the end of * which is a single ref update. For batching together updates to multiple * refs (each consisting of one or more commits against their respective * refs), create the {@link MetaDataUpdate} with a {@link BatchRefUpdate}. * <p> * A ref update produced by this {@link BatchMetaDataUpdate} is only committed * if there is no associated {@link BatchRefUpdate}. As a result, the * configured ref updated event is not fired if there is an associated batch. * * @param update helper info about the update. * @throws IOException if the update failed. */ public BatchMetaDataUpdate openUpdate(final MetaDataUpdate update) throws IOException { final Repository db = update.getRepository(); reader = db.newObjectReader(); inserter = db.newObjectInserter(); final RevWalk rw = new RevWalk(reader); final RevTree tree = revision != null ? rw.parseTree(revision) : null; newTree = readTree(tree); return new BatchMetaDataUpdate() { AnyObjectId src = revision; AnyObjectId srcTree = tree; @Override public void write(CommitBuilder commit) throws IOException { write(VersionedMetaData.this, commit); } private boolean doSave(VersionedMetaData config, CommitBuilder commit) throws IOException { DirCache nt = config.newTree; ObjectReader r = config.reader; ObjectInserter i = config.inserter; try { config.newTree = newTree; config.reader = reader; config.inserter = inserter; return config.onSave(commit); } catch (ConfigInvalidException e) { throw new IOException( "Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(), e); } finally { config.newTree = nt; config.reader = r; config.inserter = i; } } @Override public void write(VersionedMetaData config, CommitBuilder commit) throws IOException { if (!doSave(config, commit)) { return; } // Reuse tree from parent commit unless there are contents in newTree or // there is no tree for a parent commit. ObjectId res = newTree.getEntryCount() != 0 || srcTree == null ? newTree.writeTree(inserter) : srcTree.copy(); if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) { // If there are no changes to the content, don't create the commit. return; } // If changes are made to the DirCache and those changes are written as // a commit and then the tree ID is set for the CommitBuilder, then // those previous DirCache changes will be ignored and the commit's // tree will be replaced with the ID in the CommitBuilder. The same is // true if you explicitly set tree ID in a commit and then make changes // to the DirCache; that tree ID will be ignored and replaced by that of // the tree for the updated DirCache. if (commit.getTreeId() == null) { commit.setTreeId(res); } else { // In this case, the caller populated the tree without using DirCache. res = commit.getTreeId(); } if (src != null) { commit.addParentId(src); } if (update.insertChangeId()) { ObjectId id = ChangeIdUtil.computeChangeId(res, getRevision(), commit.getAuthor(), commit.getCommitter(), commit.getMessage()); commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id)); } src = inserter.insert(commit); srcTree = res; } @Override public RevCommit createRef(String refName) throws IOException { if (Objects.equals(src, revision)) { return revision; } return updateRef(ObjectId.zeroId(), src, refName); } @Override public void removeRef(String refName) throws IOException { RefUpdate ru = db.updateRef(refName); ru.setForceUpdate(true); if (revision != null) { ru.setExpectedOldObjectId(revision); } RefUpdate.Result result = ru.delete(); switch (result) { case FORCED: update.fireGitRefUpdatedEvent(ru); return; default: throw new IOException( "Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult()); } } @Override public RevCommit commit() throws IOException { return commitAt(revision); } @Override public RevCommit commitAt(ObjectId expected) throws IOException { if (Objects.equals(src, expected)) { return revision; } return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName()); } @Override public void close() { newTree = null; rw.close(); if (inserter != null) { inserter.close(); inserter = null; } if (reader != null) { reader.close(); reader = null; } } private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName) throws IOException { BatchRefUpdate bru = update.getBatch(); if (bru != null) { bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName)); inserter.flush(); revision = rw.parseCommit(newId); return revision; } RefUpdate ru = db.updateRef(refName); ru.setExpectedOldObjectId(oldId); ru.setNewObjectId(src); ru.setRefLogIdent(update.getCommitBuilder().getAuthor()); String message = update.getCommitBuilder().getMessage(); if (message == null) { message = "meta data update"; } try (BufferedReader reader = new BufferedReader(new StringReader(message))) { // read the subject line and use it as reflog message ru.setRefLogMessage("commit: " + reader.readLine(), true); } inserter.flush(); RefUpdate.Result result = ru.update(); switch (result) { case NEW: case FAST_FORWARD: revision = rw.parseCommit(ru.getNewObjectId()); update.fireGitRefUpdatedEvent(ru); return revision; default: throw new IOException( "Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult()); } } }; }
From source file:com.google.gerrit.server.patch.PatchListLoader.java
License:Apache License
public static RevTree automerge(Repository repo, RevWalk rw, RevCommit b, ThreeWayMergeStrategy mergeStrategy, boolean save) throws IOException { String hash = b.name();/*from www . j a va 2 s. c o m*/ String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2); Ref ref = repo.getRefDatabase().exactRef(refName); if (ref != null && ref.getObjectId() != null) { return rw.parseTree(ref.getObjectId()); } ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true); try (ObjectInserter ins = repo.newObjectInserter()) { DirCache dc = DirCache.newInCore(); m.setDirCache(dc); m.setObjectInserter(new ObjectInserter.Filter() { @Override protected ObjectInserter delegate() { return ins; } @Override public void flush() { } @Override public void close() { } }); boolean couldMerge; try { couldMerge = m.merge(b.getParents()); } catch (IOException e) { // It is not safe to continue further down in this method as throwing // an exception most likely means that the merge tree was not created // and m.getMergeResults() is empty. This would mean that all paths are // unmerged and Gerrit UI would show all paths in the patch list. log.warn("Error attempting automerge " + refName, e); return null; } ObjectId treeId; if (couldMerge) { treeId = m.getResultTreeId(); } else { RevCommit ours = b.getParent(0); RevCommit theirs = b.getParent(1); rw.parseBody(ours); rw.parseBody(theirs); String oursMsg = ours.getShortMessage(); String theirsMsg = theirs.getShortMessage(); String oursName = String.format("HEAD (%s %s)", ours.abbreviate(6).name(), oursMsg.substring(0, Math.min(oursMsg.length(), 60))); String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(), theirsMsg.substring(0, Math.min(theirsMsg.length(), 60))); MergeFormatter fmt = new MergeFormatter(); Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults(); Map<String, ObjectId> resolved = new HashMap<>(); for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) { MergeResult<? extends Sequence> p = entry.getValue(); try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) { fmt.formatMerge(buf, p, "BASE", oursName, theirsName, "UTF-8"); buf.close(); try (InputStream in = buf.openInputStream()) { resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in)); } } } DirCacheBuilder builder = dc.builder(); int cnt = dc.getEntryCount(); for (int i = 0; i < cnt;) { DirCacheEntry entry = dc.getEntry(i); if (entry.getStage() == 0) { builder.add(entry); i++; continue; } int next = dc.nextEntry(i); String path = entry.getPathString(); DirCacheEntry res = new DirCacheEntry(path); if (resolved.containsKey(path)) { // For a file with content merge conflict that we produced a result // above on, collapse the file down to a single stage 0 with just // the blob content, and a randomly selected mode (the lowest stage, // which should be the merge base, or ours). res.setFileMode(entry.getFileMode()); res.setObjectId(resolved.get(path)); } else if (next == i + 1) { // If there is exactly one stage present, shouldn't be a conflict... res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } else if (next == i + 2) { // Two stages suggests a delete/modify conflict. Pick the higher // stage as the automatic result. entry = dc.getEntry(i + 1); res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } else { // 3 stage conflict, no resolve above // Punt on the 3-stage conflict and show the base, for now. res.setFileMode(entry.getFileMode()); res.setObjectId(entry.getObjectId()); } builder.add(res); i = next; } builder.finish(); treeId = dc.writeTree(ins); } ins.flush(); if (save) { RefUpdate update = repo.updateRef(refName); update.setNewObjectId(treeId); update.disableRefLog(); update.forceUpdate(); } return rw.lookupTree(treeId); } }
From source file:com.google.gerrit.server.project.ListDashboards.java
License:Apache License
private List<DashboardInfo> scanDashboards(Project definingProject, Repository git, RevWalk rw, Ref ref, String project, boolean setDefault) throws IOException { List<DashboardInfo> list = Lists.newArrayList(); try (TreeWalk tw = new TreeWalk(rw.getObjectReader())) { tw.addTree(rw.parseTree(ref.getObjectId())); tw.setRecursive(true);// w ww.j a v a2 s . c o m while (tw.next()) { if (tw.getFileMode(0) == FileMode.REGULAR_FILE) { try { list.add(DashboardsCollection.parse(definingProject, ref.getName().substring(REFS_DASHBOARDS.length()), tw.getPathString(), new BlobBasedConfig(null, git, tw.getObjectId(0)), project, setDefault)); } catch (ConfigInvalidException e) { log.warn(String.format("Cannot parse dashboard %s:%s:%s: %s", definingProject.getName(), ref.getName(), tw.getPathString(), e.getMessage())); } } } } return list; }