org.eclipse.jgit.diff.DiffFormatter Java Examples
The following examples show how to use
org.eclipse.jgit.diff.DiffFormatter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExportDiffTest.java From netbeans with Apache License 2.0 | 7 votes |
public void testDiffRenameDetectionProblem () throws Exception { File file = new File(workDir, "file"); File renamed = new File(workDir, "renamed"); write(file, "hey, i will be renamed\n"); add(file); commit(file); file.renameTo(renamed); write(renamed, "hey, i will be renamed\nand now i am\n"); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); try (OutputStream out = new BufferedOutputStream(baos); DiffFormatter formatter = new DiffFormatter(out);) { formatter.setRepository(repository); formatter.setDetectRenames(true); AbstractTreeIterator firstTree = new DirCacheIterator(repository.readDirCache()); AbstractTreeIterator secondTree = new FileTreeIterator(repository); formatter.format(firstTree, secondTree); formatter.flush(); } assertFalse( "Fixed in JGit, modify and simplify the sources in ExportDiff command", baos.toString().contains("similarity index ") ); }
Example #2
Source File: GitCommit.java From Getaviz with Apache License 2.0 | 6 votes |
private void addDiff(DiffImplementation returnable, RevCommit parent) throws IOException { RevWalk revWalk = new RevWalk(repository); parent = revWalk.parseCommit(parent.getId()); revWalk.close(); ByteArrayOutputStream put = new ByteArrayOutputStream(BUFFER_SIZE); DiffFormatter df = new DiffFormatter(put); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for(DiffEntry e : diffs){ df.format(e); String diffText = put.toString(DEFAULT_ENCODING); //TODO make encoding insertable returnable.addOperation(e.getOldPath(), new GitOperation(diffText, e.getOldPath(), e.getNewPath(), e.getChangeType())); put.reset(); } df.close(); }
Example #3
Source File: GitServiceImpl.java From RefactoringMiner with MIT License | 6 votes |
@Override public Churn churn(Repository repository, RevCommit currentCommit) throws Exception { if (currentCommit.getParentCount() > 0) { ObjectId oldTree = currentCommit.getParent(0).getTree(); ObjectId newTree = currentCommit.getTree(); final TreeWalk tw = new TreeWalk(repository); tw.setRecursive(true); tw.addTree(oldTree); tw.addTree(newTree); List<DiffEntry> diffs = DiffEntry.scan(tw); DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE); diffFormatter.setRepository(repository); diffFormatter.setContext(0); int addedLines = 0; int deletedLines = 0; for (DiffEntry entry : diffs) { FileHeader header = diffFormatter.toFileHeader(entry); List<? extends HunkHeader> hunks = header.getHunks(); for (HunkHeader hunkHeader : hunks) { for (Edit edit : hunkHeader.toEditList()) { if (edit.getType() == Type.INSERT) { addedLines += edit.getLengthB(); } else if (edit.getType() == Type.DELETE) { deletedLines += edit.getLengthA(); } else if (edit.getType() == Type.REPLACE) { deletedLines += edit.getLengthA(); addedLines += edit.getLengthB(); } } } } diffFormatter.close(); return new Churn(addedLines, deletedLines); } return null; }
Example #4
Source File: GitRepoMetaData.java From GitFx with Apache License 2.0 | 6 votes |
public String getDiffBetweenCommits(int commitIndex) throws IOException,GitAPIException{ if(commitIndex+1==commitCount) return "Nothing to Diff. This is first commit"; AbstractTreeIterator current = prepareTreeParser(repository,commitSHA.get(commitIndex)); AbstractTreeIterator parent = prepareTreeParser(repository,commitSHA.get(++commitIndex)); ObjectReader reader = repository.newObjectReader(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); // finally get the list of changed files Git git = new Git(repository) ; List<DiffEntry> diff = git.diff(). setOldTree(parent). setNewTree(current). //TODO Set the path filter to filter out the selected file //setPathFilter(PathFilter.create("README.md")). call(); for (DiffEntry entry : diff) { System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId()); DiffFormatter formatter = new DiffFormatter(byteStream) ; formatter.setRepository(repository); formatter.format(entry); } // System.out.println(byteStream.toString()); String diffContent = byteStream.toString(); return byteStream.toString(); }
Example #5
Source File: AppraiseReviewsTaskDataHandler.java From git-appraise-eclipse with Eclipse Public License 1.0 | 5 votes |
/** * Fills the diffs into the given task data. */ private void populateDiffs(TaskRepository repository, List<DiffEntry> diffs, TaskData taskData) { int diffCount = 1; for (DiffEntry diffEntry : diffs) { TaskAttribute diffAttribute = taskData.getRoot().createAttribute(AppraiseReviewTaskSchema.PREFIX_DIFF + diffCount); diffAttribute.getMetaData().setType(AppraiseReviewTaskSchema.TYPE_DIFF); TaskAttribute diffNewPathAttribute = diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_NEWPATH); setAttributeValue(diffNewPathAttribute, diffEntry.getNewPath()); TaskAttribute diffOldPathAttribute = diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_OLDPATH); setAttributeValue(diffOldPathAttribute, diffEntry.getNewPath()); TaskAttribute diffTypeAttribute = diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_TYPE); setAttributeValue(diffTypeAttribute, diffEntry.getChangeType().name()); TaskAttribute diffTextAttribute = diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_TEXT); ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream(); try (DiffFormatter formatter = new DiffFormatter(diffOutputStream)) { formatter.setRepository(AppraisePluginUtils.getGitRepoForRepository(repository)); try { formatter.format(diffEntry); String diffText = new String(diffOutputStream.toByteArray(), "UTF-8"); setAttributeValue(diffTextAttribute, diffText); } catch (IOException e) { AppraiseConnectorPlugin.logWarning( "Failed to load a diff for " + taskData.getTaskId(), e); } } diffCount++; } }
Example #6
Source File: GitRepository.java From APDE with GNU General Public License v2.0 | 5 votes |
public DiffFormatter getDiffFormatter(OutputStream out) { DiffFormatter formatter = new DiffFormatter(out); formatter.setRepository(git.getRepository()); formatter.setDiffComparator(RawTextComparator.DEFAULT); formatter.setDetectRenames(true); return formatter; }
Example #7
Source File: GitHistoryParser.java From proctor with Apache License 2.0 | 5 votes |
static GitHistoryParser fromRepository(final Repository repository, final String testDefinitionDirectory) { final RevWalk revWalk = new RevWalk(repository); final DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(false); // to regard rename changes as add and remove return new GitHistoryParser(revWalk, df, testDefinitionDirectory); }
Example #8
Source File: GitHistoryParser.java From proctor with Apache License 2.0 | 5 votes |
private GitHistoryParser( final RevWalk revWalk, final DiffFormatter diffFormatter, final String definitionDirectory ) { this.revWalk = revWalk; this.diffFormatter = diffFormatter; testNamePattern = compileTestNamePattern(definitionDirectory); }
Example #9
Source File: ConfigRepository.java From gocd with Apache License 2.0 | 5 votes |
String findDiffBetweenTwoRevisions(RevCommit laterCommit, RevCommit earlierCommit) { if (laterCommit == null || earlierCommit == null) { return null; } String output = null; try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DiffFormatter diffFormatter = new DiffFormatter(out)) { diffFormatter.setRepository(gitRepo); diffFormatter.format(earlierCommit.getId(), laterCommit.getId()); output = out.toString(); output = StringUtil.stripTillLastOccurrenceOf(output, "+++ b/cruise-config.xml"); } catch (IOException e) { throw new RuntimeException("Error occurred during diff computation. Message: " + e.getMessage()); } return output; }
Example #10
Source File: JGitHelper.java From go-plugins with Apache License 2.0 | 5 votes |
private Revision getRevisionObj(Repository repository, RevCommit commit) throws IOException { String commitSHA = commit.getName(); Date commitTime = commit.getAuthorIdent().getWhen(); String comment = commit.getFullMessage().trim(); String user = commit.getAuthorIdent().getName(); String emailId = commit.getAuthorIdent().getEmailAddress(); List<ModifiedFile> modifiedFiles = new ArrayList<ModifiedFile>(); if (commit.getParentCount() == 0) { TreeWalk treeWalk = new TreeWalk(repository); treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(false); while (treeWalk.next()) { modifiedFiles.add(new ModifiedFile(treeWalk.getPathString(), "added")); } } else { RevWalk rw = new RevWalk(repository); RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE); diffFormatter.setRepository(repository); diffFormatter.setDiffComparator(RawTextComparator.DEFAULT); diffFormatter.setDetectRenames(true); List<DiffEntry> diffEntries = diffFormatter.scan(parent.getTree(), commit.getTree()); for (DiffEntry diffEntry : diffEntries) { modifiedFiles.add(new ModifiedFile(diffEntry.getNewPath(), getAction(diffEntry.getChangeType().name()))); } } return new Revision(commitSHA, commitTime, comment, user, emailId, modifiedFiles); }
Example #11
Source File: GitSCM.java From repositoryminer with Apache License 2.0 | 5 votes |
private void analyzeDiff(Change change, DiffEntry diff) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); DiffFormatter df = new DiffFormatter(output); df.setRepository(git.getRepository()); df.format(diff); Scanner scanner = new Scanner(output.toString("UTF-8")); int added = 0; int removed = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("+") && !line.startsWith("+++")) { added++; } else if (line.startsWith("-") && !line.startsWith("---")) { removed++; } } output.close(); df.close(); scanner.close(); change.setLinesAdded(added); change.setLinesRemoved(removed); }
Example #12
Source File: GitSCM.java From repositoryminer with Apache License 2.0 | 5 votes |
private List<Change> getChangesForCommitedFiles(String hash) throws IOException { RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(ObjectId.fromString(hash)); if (commit.getParentCount() > 1) { revWalk.close(); return new ArrayList<Change>(); } RevCommit parentCommit = commit.getParentCount() > 0 ? revWalk.parseCommit(ObjectId.fromString(commit.getParent(0).getName())) : null; DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setBinaryFileThreshold(2048); df.setRepository(git.getRepository()); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffEntries = df.scan(parentCommit, commit); df.close(); revWalk.close(); List<Change> changes = new ArrayList<Change>(); for (DiffEntry entry : diffEntries) { Change change = new Change(entry.getNewPath(), entry.getOldPath(), 0, 0, ChangeType.valueOf(entry.getChangeType().name())); analyzeDiff(change, entry); changes.add(change); } return changes; }
Example #13
Source File: LocalFacadeBuilder.java From sputnik with Apache License 2.0 | 5 votes |
public LocalFacade build() { try (Repository repository = new FileRepositoryBuilder().readEnvironment().findGitDir().build()) { try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE)) { diffFormatter.setRepository(repository); return new LocalFacade(repository, diffFormatter, new LocalFacadeOutput()); } } catch (IOException e) { throw new RuntimeException("Error getting git repository", e); } }
Example #14
Source File: CommitUtil.java From SZZUnleashed with MIT License | 5 votes |
/** * Extract a list containing all Edits that exists between two revisions. * * @param entry a diffentry which contains information about a diff between two revisions. * @return an EditList containing all Edits. */ public EditList getDiffEditList(DiffEntry entry) throws IOException, GitAPIException { DiffFormatter form = new DiffFormatter(DisabledOutputStream.INSTANCE); form.setRepository(this.git.getRepository()); FileHeader fh = form.toFileHeader(entry); return fh.toEditList(); }
Example #15
Source File: ExportCommitCommand.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected void run() throws GitException { Repository repository = getRepository(); String workTreePath = repository.getWorkTree().getAbsolutePath(); RevCommit commit = Utils.findCommit(repository, revisionStr); if (commit.getParentCount() > 1) { throw new GitException("Unable to export a merge commit"); } try (DiffFormatter formatter = new DiffFormatter(out)) { out.write(Constants.encode(formatCommitInfo(commit))); formatter.setRepository(repository); List<DiffEntry> diffEntries; if (commit.getParentCount() > 0) { formatter.setDetectRenames(true); diffEntries = formatter.scan(commit.getParent(0), commit); } else { TreeWalk walk = new TreeWalk(repository); walk.reset(); walk.setRecursive(true); walk.addTree(new EmptyTreeIterator()); walk.addTree(commit.getTree()); walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF)); diffEntries = DiffEntry.scan(walk); } for (DiffEntry ent : diffEntries) { if (monitor.isCanceled()) { break; } listener.notifyFile(new File(workTreePath + File.separator + ent.getNewPath()), ent.getNewPath()); formatter.format(ent); } formatter.flush(); } catch (IOException ex) { throw new GitException(ex); } }
Example #16
Source File: PGA.java From coming with MIT License | 5 votes |
private void runDiff(Repository repo, String oldCommit, String newCommit, String path) throws IOException, GitAPIException { // Diff README.md between two commits. The file is named README.md in // the new commit (5a10bd6e), but was named "jgit-cookbook README.md" in // the old commit (2e1d65e4). DiffEntry diff = diffFile(repo, oldCommit, newCommit, path); // Display the diff System.out.println("Showing diff of " + path); DiffFormatter formatter = new DiffFormatter(System.out); formatter.setRepository(repo); //noinspection ConstantConditions formatter.format(diff); }
Example #17
Source File: GitUtils.java From onedev with MIT License | 5 votes |
public static List<DiffEntry> diff(Repository repository, AnyObjectId oldRevId, AnyObjectId newRevId) { List<DiffEntry> diffs = new ArrayList<>(); try ( DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE); RevWalk revWalk = new RevWalk(repository); ObjectReader reader = repository.newObjectReader();) { diffFormatter.setRepository(repository); diffFormatter.setDetectRenames(true); diffFormatter.setDiffComparator(RawTextComparator.DEFAULT); CanonicalTreeParser oldTreeParser = new CanonicalTreeParser(); if (!oldRevId.equals(ObjectId.zeroId())) oldTreeParser.reset(reader, revWalk.parseCommit(oldRevId).getTree()); CanonicalTreeParser newTreeParser = new CanonicalTreeParser(); if (!newRevId.equals(ObjectId.zeroId())) newTreeParser.reset(reader, revWalk.parseCommit(newRevId).getTree()); for (DiffEntry entry: diffFormatter.scan(oldTreeParser, newTreeParser)) { if (!Objects.equal(entry.getOldPath(), entry.getNewPath()) || !Objects.equal(entry.getOldMode(), entry.getNewMode()) || entry.getOldId()==null || !entry.getOldId().isComplete() || entry.getNewId()== null || !entry.getNewId().isComplete() || !entry.getOldId().equals(entry.getNewId())) { diffs.add(entry); } } } catch (IOException e) { throw new RuntimeException(e); } return diffs; }
Example #18
Source File: GitRepoMetaData.java From GitFx with Apache License 2.0 | 5 votes |
public ArrayList<String> getShortMessage() { for (RevCommit revision : walk) { shortMessage.add(revision.getShortMessage()); //[LOG] logger.debug(revision.getShortMessage()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); RevCommit parent = null; if(revision.getParentCount()!=0) { try { parent = walk.parseCommit(revision.getParent(0).getId()); RevTree tree = revision.getTree(); List<DiffEntry> diffs = df.scan(parent.getTree(), revision.getTree()); for (DiffEntry diff : diffs) { String changeType = diff.getChangeType().name(); if(changeType.equals(ADD)|| changeType.equals(MODIFY)) { //[LOG] logger.debug(diff.getChangeType().name()); //[LOG] logger.debug(diff.getNewPath()); tempCommitHistory.add(diff.getNewPath()); } } }catch (IOException ex) { //[LOG] logger.debug("IOException", ex); } } commitSHA.add(commitCount,revision.name()); commitHistory.add(commitCount++,new ArrayList<String>(tempCommitHistory)); tempCommitHistory.clear(); } walk.reset(); return shortMessage; }
Example #19
Source File: Change.java From rewrite with Apache License 2.0 | 5 votes |
String getDiff() { if (oldId.equals(newId)) { return ""; } var patch = new ByteArrayOutputStream(); var formatter = new DiffFormatter(patch); formatter.setRepository(repo); try { formatter.format(this); } catch (IOException e) { throw new UncheckedIOException(e); } return new String(patch.toByteArray()); }
Example #20
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 5 votes |
protected static DiffFormatter createDiffFormatter(Repository r, OutputStream buffer) { DiffFormatter formatter = new DiffFormatter(buffer); formatter.setRepository(r); formatter.setDiffComparator(RawTextComparator.DEFAULT); formatter.setDetectRenames(true); return formatter; }
Example #21
Source File: GitIndexEntry.java From git-code-format-maven-plugin with MIT License | 5 votes |
private LineRanges computeLineRanges(DiffEntry diffEntry) { DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE); diffFormatter.setRepository(repository); try { FileHeader fileHeader = diffFormatter.toFileHeader(diffEntry); return fileHeader.getHunks().stream() .map(HunkHeader.class::cast) .map(this::computeLineRanges) .reduce(LineRanges::concat) .orElse(LineRanges.all()); } catch (IOException e) { throw new MavenGitCodeFormatException(e); } }
Example #22
Source File: GitRepository.java From centraldogma with Apache License 2.0 | 5 votes |
private List<DiffEntry> blockingCompareTreesUncached(@Nullable RevTree treeA, @Nullable RevTree treeB, TreeFilter filter) { readLock(); try (DiffFormatter diffFormatter = new DiffFormatter(null)) { diffFormatter.setRepository(jGitRepository); diffFormatter.setPathFilter(filter); return ImmutableList.copyOf(diffFormatter.scan(treeA, treeB)); } catch (IOException e) { throw new StorageException("failed to compare two trees: " + treeA + " vs. " + treeB, e); } finally { readUnlock(); } }
Example #23
Source File: GitRepository.java From centraldogma with Apache License 2.0 | 5 votes |
private Map<String, Change<?>> blockingPreviewDiff(Revision baseRevision, Iterable<Change<?>> changes) { requireNonNull(baseRevision, "baseRevision"); requireNonNull(changes, "changes"); baseRevision = normalizeNow(baseRevision); readLock(); try (ObjectReader reader = jGitRepository.newObjectReader(); RevWalk revWalk = newRevWalk(reader); DiffFormatter diffFormatter = new DiffFormatter(null)) { final ObjectId baseTreeId = toTree(revWalk, baseRevision); final DirCache dirCache = DirCache.newInCore(); final int numEdits = applyChanges(baseRevision, baseTreeId, dirCache, changes); if (numEdits == 0) { return Collections.emptyMap(); } final CanonicalTreeParser p = new CanonicalTreeParser(); p.reset(reader, baseTreeId); diffFormatter.setRepository(jGitRepository); final List<DiffEntry> result = diffFormatter.scan(p, new DirCacheIterator(dirCache)); return toChangeMap(result); } catch (IOException e) { throw new StorageException("failed to perform a dry-run diff", e); } finally { readUnlock(); } }
Example #24
Source File: GetDiffEntriesForCommitsAdapter.java From coderadar with MIT License | 4 votes |
@Override public List<DiffEntry> getDiffs(String projectRoot, String commitName1, String commitName2) throws UnableToGetDiffsFromCommitsException { try { Git git = Git.open(new File(projectRoot)); Repository repository = git.getRepository(); RevCommit commit1 = repository.parseCommit(ObjectId.fromString(commitName1)); RevCommit commit2 = repository.parseCommit(ObjectId.fromString(commitName2)); // change commits so that commit2 is the older one if (commit1.getCommitTime() > commit2.getCommitTime()) { RevCommit tmp = commit1; commit1 = commit2; commit2 = tmp; } ObjectReader reader = git.getRepository().newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); ObjectId oldTree = commit1.getTree(); oldTreeIter.reset(reader, oldTree); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); ObjectId newTree = commit2.getTree(); newTreeIter.reset(reader, newTree); DiffFormatter df = new DiffFormatter(new ByteArrayOutputStream()); df.setRepository(repository); List<DiffEntry> entries = df.scan(oldTreeIter, newTreeIter).stream() .map( diffEntry -> { DiffEntry entry = new DiffEntry(); entry.setNewPath(diffEntry.getNewPath()); entry.setOldPath(diffEntry.getOldPath()); entry.setChangeType( ChangeTypeMapper.jgitToCoderadar(diffEntry.getChangeType()).ordinal()); return entry; }) .collect(Collectors.toList()); git.close(); return entries; } catch (IOException e) { throw new UnableToGetDiffsFromCommitsException(e.getMessage()); } }
Example #25
Source File: GitCommit.java From compiler with Apache License 2.0 | 4 votes |
private void updateChangedFiles(final RevCommit parent, final int parentIndex, final RevCommit child) { final DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); try { final AbstractTreeIterator parentIter = new CanonicalTreeParser(null, repository.newObjectReader(), parent.getTree()); final AbstractTreeIterator childIter = new CanonicalTreeParser(null, repository.newObjectReader(), child.getTree()); List<DiffEntry> diffs = df.scan(parentIter, childIter); for (final DiffEntry diff : diffs) { if (diff.getChangeType() == ChangeType.MODIFY) { if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) { updateChangedFiles(parent, child, diff, ChangeKind.MODIFIED); } // RENAMED file may have the same/different object id(s) for old and new } else if (diff.getChangeType() == ChangeType.RENAME) { if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) { updateChangedFiles(parent, child, diff, ChangeKind.RENAMED); } } else if (diff.getChangeType() == ChangeType.COPY) { if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) { updateChangedFiles(parent, child, diff, ChangeKind.COPIED); } // ADDED file should not have old path and its old object id is 0's } else if (diff.getChangeType() == ChangeType.ADD) { if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) { updateChangedFiles(parent, child, diff, ChangeKind.ADDED); } // DELETED file's new object id is 0's and doesn't have new path } else if (diff.getChangeType() == ChangeType.DELETE) { if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB) { String oldPath = diff.getOldPath(); String oldObjectId = diff.getOldId().toObjectId().getName(); ChangedFile.Builder cfb = getChangedFile(oldPath, ChangeKind.DELETED); filePathGitObjectIds.put(oldPath, diff.getNewId().toObjectId()); } } } } catch (final IOException e) { if (debug) System.err.println("Git Error getting commit diffs: " + e.getMessage()); } df.close(); }
Example #26
Source File: GitHelper.java From repairnator with MIT License | 4 votes |
public void computePatchStats(JobStatus jobStatus, Git git, RevCommit headRev, RevCommit commit) { try { ObjectReader reader = git.getRepository().newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, headRev.getTree()); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, commit.getTree()); DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE); diffFormatter.setRepository(git.getRepository()); diffFormatter.setContext(0); List<DiffEntry> entries = diffFormatter.scan(newTreeIter, oldTreeIter); int nbLineAdded = 0; int nbLineDeleted = 0; Set<String> changedFiles = new HashSet<>(); Set<String> addedFiles = new HashSet<>(); Set<String> deletedFiles = new HashSet<>(); for (DiffEntry entry : entries) { String path; if (entry.getChangeType() == DiffEntry.ChangeType.DELETE) { path = entry.getOldPath(); } else { path = entry.getNewPath(); } if (!jobStatus.isCreatedFileToPush(path) && path.endsWith(".java")) { if (entry.getChangeType() == DiffEntry.ChangeType.MODIFY || entry.getChangeType() == DiffEntry.ChangeType.RENAME) { changedFiles.add(path); } else if (entry.getChangeType() == DiffEntry.ChangeType.ADD || entry.getChangeType() == DiffEntry.ChangeType.COPY) { addedFiles.add(path); } else if (entry.getChangeType() == DiffEntry.ChangeType.DELETE) { deletedFiles.add(path); } FileHeader fileHeader = diffFormatter.toFileHeader(entry); List<? extends HunkHeader> hunks = fileHeader.getHunks(); for (HunkHeader hunk : hunks) { EditList edits = hunk.toEditList(); for (Edit edit : edits) { switch (edit.getType()) { case INSERT: nbLineAdded += edit.getLengthB(); break; case DELETE: nbLineDeleted += edit.getLengthA(); break; case REPLACE: int diff = edit.getLengthA() - edit.getLengthB(); if (diff > 0) { nbLineAdded += edit.getLengthA(); nbLineDeleted += edit.getLengthB(); } else { nbLineDeleted += edit.getLengthA(); nbLineAdded += edit.getLengthB(); } break; case EMPTY: break; } } } } } PatchDiff patchDiff = jobStatus.getProperties().getPatchDiff(); patchDiff.getFiles().setNumberAdded(addedFiles.size()); patchDiff.getFiles().setNumberChanged(changedFiles.size()); patchDiff.getFiles().setNumberDeleted(deletedFiles.size()); patchDiff.getLines().setNumberAdded(nbLineAdded); patchDiff.getLines().setNumberDeleted(nbLineDeleted); } catch (IOException e) { this.getLogger().error("Error while computing stat on the patch.", e); } }
Example #27
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 4 votes |
protected String doDiff(Git git, String objectId, String baseObjectId, String pathOrBlobPath) throws IOException { Repository r = git.getRepository(); String blobPath = trimLeadingSlash(pathOrBlobPath); RevCommit commit; if (Strings.isNotBlank(objectId)) { commit = CommitUtils.getCommit(r, objectId); } else { commit = CommitUtils.getHead(r); } RevCommit baseCommit = null; if (Strings.isNotBlank(baseObjectId) && !Objects.equals(baseObjectId, objectId)) { baseCommit = CommitUtils.getCommit(r, baseObjectId); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DiffFormatter formatter = createDiffFormatter(r, buffer); RevTree commitTree = commit.getTree(); RevTree baseTree; if (baseCommit == null) { if (commit.getParentCount() > 0) { final RevWalk rw = new RevWalk(r); RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); rw.dispose(); baseTree = parent.getTree(); } else { // FIXME initial commit. no parent?! baseTree = commitTree; } } else { baseTree = baseCommit.getTree(); } List<DiffEntry> diffEntries = formatter.scan(baseTree, commitTree); if (blobPath != null && blobPath.length() > 0) { for (DiffEntry diffEntry : diffEntries) { if (diffEntry.getNewPath().equalsIgnoreCase(blobPath)) { formatter.format(diffEntry); break; } } } else { formatter.format(diffEntries); } formatter.flush(); return buffer.toString(); }
Example #28
Source File: ExportDiffCommand.java From netbeans with Apache License 2.0 | 4 votes |
@Override protected void run() throws GitException { Repository repository = getRepository(); String workTreePath = repository.getWorkTree().getAbsolutePath(); try (DiffFormatter formatter = new DiffFormatter(out); ObjectReader or = repository.newObjectReader()) { formatter.setRepository(repository); Collection<PathFilter> pathFilters = Utils.getPathFilters(repository.getWorkTree(), roots); if (!pathFilters.isEmpty()) { formatter.setPathFilter(PathFilterGroup.create(pathFilters)); } if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) { // work-around for autocrlf formatter.setDiffComparator(new AutoCRLFComparator()); } AbstractTreeIterator firstTree = getIterator(firstCommit, or); AbstractTreeIterator secondTree = getIterator(secondCommit, or); List<DiffEntry> diffEntries; if (secondTree instanceof WorkingTreeIterator) { // remote when fixed in JGit, see ExportDiffTest.testDiffRenameDetectionProblem formatter.setDetectRenames(false); diffEntries = formatter.scan(firstTree, secondTree); formatter.setDetectRenames(true); RenameDetector detector = formatter.getRenameDetector(); detector.reset(); detector.addAll(diffEntries); diffEntries = detector.compute(new ContentSource.Pair(ContentSource.create(or), ContentSource.create((WorkingTreeIterator) secondTree)), NullProgressMonitor.INSTANCE); } else { formatter.setDetectRenames(true); diffEntries = formatter.scan(firstTree, secondTree); } for (DiffEntry ent : diffEntries) { if (monitor.isCanceled()) { break; } listener.notifyFile(new File(workTreePath + File.separator + ent.getNewPath()), ent.getNewPath()); formatter.format(ent); } formatter.flush(); } catch (IOException ex) { throw new GitException(ex); } }