private static void listDiff(Repository repository, Git git, String oldCommit, String newCommit) throws GitAPIException, IOException { final List<DiffEntry> diffs = git.diff() .setOldTree(prepareTreeParser(repository, oldCommit)) .setNewTree(prepareTreeParser(repository, newCommit)) .call(); System.out.println("Found: " + diffs.size() + " differences"); for (DiffEntry diff : diffs) { System.out.println("Diff: " + diff.getChangeType() + ": " + (diff.getOldPath().equals(diff.getNewPath()) ? diff.getNewPath() : diff.getOldPath() + " -> " + diff.getNewPath())); } }
.setNewTree(newTreeIter) .setOldTree(oldTreeIter) .setShowNameAndStatusOnly(true) .call();
private static @NonNull DiffEntry diffFile(Repository repo, String oldCommit, String newCommit, String path) throws IOException, GitAPIException { Config config = new Config(); config.setBoolean("diff", null, "renames", true); DiffConfig diffConfig = config.get(DiffConfig.KEY); try (Git git = new Git(repo)) { List<DiffEntry> diffList = git.diff(). setOldTree(prepareTreeParser(repo, oldCommit)). setNewTree(prepareTreeParser(repo, newCommit)). setPathFilter(FollowFilter.create(path, diffConfig)). call(); if (diffList.size() == 0) return null; if (diffList.size() > 1) throw new RuntimeException("invalid diff"); return diffList.get(0); } } }
@Signature public Memory diff(ArrayMemory settings) throws GitAPIException { DiffCommand command = getWrappedObject().diff(); if (settings != null) { command.setCached(settings.valueOfIndex("cached").toBoolean()); Memory contextLines = settings.valueOfIndex("contextLines"); if (contextLines.isNotNull()) { command.setContextLines(contextLines.toInteger()); } Memory destPrefix = settings.valueOfIndex("destPrefix"); if (destPrefix.isNotNull()) { command.setDestinationPrefix(destPrefix.toString()); } Memory sourcePrefix = settings.valueOfIndex("sourcePrefix"); if (sourcePrefix.isNotNull()) { command.setSourcePrefix(sourcePrefix.toString()); } command.setShowNameAndStatusOnly(settings.valueOfIndex("showNameAndStatusOnly").toBoolean()); Memory pathFilter = settings.valueOfIndex("pathFilter"); if (pathFilter.isNotNull()) { command.setPathFilter(PathFilter.create(pathFilter.toString())); } } List<DiffEntry> call = command.call(); return GitUtils.valueOfDiffEntries(call); }
public DiffScmResult callDiff( Git git, ScmVersion startRevision, ScmVersion endRevision ) throws IOException, GitAPIException, ScmException { AbstractTreeIterator oldTree = null; if ( startRevision != null && StringUtils.isNotEmpty( startRevision.getName().trim() ) ) { String startRev = startRevision.getName().trim(); oldTree = getTreeIterator( git.getRepository(), startRev ); } AbstractTreeIterator newTree = null; if ( endRevision != null && StringUtils.isNotEmpty( endRevision.getName().trim() ) ) { String endRev = endRevision.getName().trim(); newTree = getTreeIterator( git.getRepository(), endRev ); } OutputStream out = new ByteArrayOutputStream(); git.diff().setOutputStream( out ).setOldTree( oldTree ).setNewTree( newTree ).setCached( false ).call(); git.diff().setOutputStream( out ).setOldTree( oldTree ).setNewTree( newTree ).setCached( true ).call(); out.flush(); GitDiffConsumer consumer = new GitDiffConsumer( getLogger(), null ); String fullDiff = out.toString(); out.close(); String[] lines = fullDiff.split( "\n" ); for ( String aLine : lines ) { consumer.consumeLine( aLine ); } return new DiffScmResult( "JGit diff", consumer.getChangedFiles(), consumer.getDifferences(), consumer.getPatch() ); }
/** * Get the diff of a file against a particular commit * * @param jobId The job config to diff * @param commitId If specified, the commit to compare against; otherwise, compare against the latest revision * @return A string description of the diff, comparable to the output of "git diff filename" * @throws GitAPIException If there is a problem fetching the diff from git * @throws IOException If there is a problem reading from the file */ public String getDiff(String jobId, String commitId) throws GitAPIException, IOException { OutputStream out = new ByteArrayOutputStream(); DiffCommand diff = git.diff() .setPathFilter(PathFilter.create(getPathForJobId(jobId))) .setOutputStream(out) .setSourcePrefix("old:") .setDestinationPrefix("new:"); if (commitId != null) { diff.setOldTree(getTreeIterator(commitId)); diff.setNewTree(getTreeIterator("HEAD")); } diff.call(); return out.toString(); }
CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(localRepo.newObjectReader(), remoteHead); DiffCommand dc = git.diff().setNewTree(newTreeIter); if (path != null) dc.setPathFilter(PathFilter.create(path)); dc.setShowNameAndStatusOnly(true); for (DiffEntry diff : dc.call()) { if (diff.getChangeType() == ChangeType.ADD || diff.getChangeType() == ChangeType.COPY) { diffs.add(DiffType.MISSING, diff.getNewPath());
.setOutputStream(computer.receiver()) .setOldTree(prepareTreeParser(repo, targetRef)) .setPathFilter(PathFilter.create(toGitPath(repoRootDir.relativize(path).toString()))) .call();
/** * @inheritDoc */ @Override public boolean checkIfUncommitedChanges(Git git) { try { List<DiffEntry> diff = git.diff().call(); return !diff.isEmpty(); } catch (GitAPIException e) { throw new RuntimeException("could not check if there are any uncommited changes", e); } }
/** * Check path vs repository */ public boolean isDiff(String path) throws Exception { return !git.diff().setPathFilter(PathFilter.create(path)).call().isEmpty(); }
public void postEventMap() throws GitAPIException { Map<DiffEntry, String> diffMap = new HashMap<>(); try (OutputStream stream = new ByteArrayOutputStream()) { List<DiffEntry> list = this.git.diff().setOutputStream(stream).call(); BufferedReader reader = new BufferedReader(new StringReader(stream.toString())); for (DiffEntry entry : list) { String line = reader.readLine(); StringWriter diff = new StringWriter(); while (line != null && !line.startsWith("diff")) { diff.append(line); diff.write('\n'); line = reader.readLine(); } diffMap.put(entry, diff.toString()); } } catch (IOException exc) { LOGGER.trace("Reading of git information failed!", exc); } catch (JGitInternalException gitException) { LOGGER.trace("Could not create Diff!", gitException); } this.eventBus.post(diffMap); }
public DiffScmResult callDiff( Git git, ScmVersion startRevision, ScmVersion endRevision ) throws IOException, GitAPIException, ScmException { AbstractTreeIterator oldTree = null; if ( startRevision != null && StringUtils.isNotEmpty( startRevision.getName().trim() ) ) { String startRev = startRevision.getName().trim(); oldTree = getTreeIterator( git.getRepository(), startRev ); } AbstractTreeIterator newTree = null; if ( endRevision != null && StringUtils.isNotEmpty( endRevision.getName().trim() ) ) { String endRev = endRevision.getName().trim(); newTree = getTreeIterator( git.getRepository(), endRev ); } OutputStream out = new ByteArrayOutputStream(); git.diff().setOutputStream( out ).setOldTree( oldTree ).setNewTree( newTree ).setCached( false ).call(); git.diff().setOutputStream( out ).setOldTree( oldTree ).setNewTree( newTree ).setCached( true ).call(); out.flush(); GitDiffConsumer consumer = new GitDiffConsumer( getLogger(), null ); String fullDiff = out.toString(); out.close(); String[] lines = fullDiff.split( "\n" ); for ( String aLine : lines ) { consumer.consumeLine( aLine ); } return new DiffScmResult( "JGit diff", consumer.getChangedFiles(), consumer.getDifferences(), consumer.getPatch() ); }
@Override public boolean isThereAnyDifs() { boolean ans = false; try { List<DiffEntry> list = _git.diff().call(); if (list.size() > 0) { ans = true; } } catch (GitAPIException e) { throw new RuntimeException("Failed to get diffs", e); } return ans; }
private static void listDiff(Repository repository, Git git, String oldCommit, String newCommit) throws GitAPIException, IOException { final List<DiffEntry> diffs = git.diff() .setOldTree(prepareTreeParser(repository, oldCommit)) .setNewTree(prepareTreeParser(repository, newCommit)) .call(); System.out.println("Found: " + diffs.size() + " differences"); for (DiffEntry diff : diffs) { System.out.println("Diff: " + diff.getChangeType() + ": " + (diff.getOldPath().equals(diff.getNewPath()) ? diff.getNewPath() : diff.getOldPath() + " -> " + diff.getNewPath())); } }
public static List<DiffEntry> getDiff( final Repository repo, final ObjectId oldRef, final ObjectId newRef ) { if ( oldRef == null || newRef == null || repo == null ) { return emptyList(); } try { ObjectReader reader = repo.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset( reader, oldRef ); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset( reader, newRef ); return new Git( repo ).diff().setNewTree( newTreeIter ).setOldTree( oldTreeIter ).setShowNameAndStatusOnly( true ).call(); } catch ( final Exception ex ) { throw new RuntimeException( ex ); } }
private static @NonNull DiffEntry diffFile(Repository repo, String oldCommit, String newCommit, String path) throws IOException, GitAPIException { Config config = new Config(); config.setBoolean("diff", null, "renames", true); DiffConfig diffConfig = config.get(DiffConfig.KEY); try (Git git = new Git(repo)) { List<DiffEntry> diffList = git.diff(). setOldTree(prepareTreeParser(repo, oldCommit)). setNewTree(prepareTreeParser(repo, newCommit)). setPathFilter(FollowFilter.create(path, diffConfig)). call(); if (diffList.size() == 0) return null; if (diffList.size() > 1) throw new RuntimeException("invalid diff"); return diffList.get(0); } } }
public boolean hasChangesInFile(RepositoryFileReference ref) { try { if (!this.git.status().call().isClean()) { List<DiffEntry> diffEntries = this.git.diff().call(); List<DiffEntry> entries = diffEntries.stream() // we use String::startsWith() and RepositoryFileReference::getParent() // because the component is considered changed, if any file of this component is changed. // -> check if any file in the folder is changed .filter(item -> item.getNewPath().startsWith(BackendUtils.getPathInsideRepo(ref.getParent()))) .collect(Collectors.toList()); return entries.size() > 0; } } catch (GitAPIException e) { LOGGER.trace(e.getMessage(), e); } return false; }
public static void main(String[] args) throws IOException, GitAPIException { try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { try (Git git = new Git(repository)) { if(repository.exactRef("refs/heads/testbranch") == null) { // first we need to ensure that the remote branch is visible locally Ref ref = git.branchCreate().setName("testbranch").setStartPoint("origin/testbranch").call(); System.out.println("Created local testbranch with ref: " + ref); } // the diff works on TreeIterators, we prepare two for the two branches AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, "refs/heads/testbranch"); AbstractTreeIterator newTreeParser = prepareTreeParser(repository, "refs/heads/master"); // then the procelain diff-command returns a list of diff entries List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call(); for (DiffEntry entry : diff) { System.out.println("Entry: " + entry); } } } }
@CheckForNull @Override public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) { try (Repository repo = buildRepo(rootBaseDir)) { Ref targetRef = resolveTargetRef(targetBranchName, repo); if (targetRef == null) { return null; } try (Git git = newGit(repo)) { return git.diff().setShowNameAndStatusOnly(true) .setOldTree(prepareTreeParser(repo, targetRef)) .setNewTree(prepareNewTree(repo)) .call().stream() .filter(diffEntry -> diffEntry.getChangeType() == DiffEntry.ChangeType.ADD || diffEntry.getChangeType() == DiffEntry.ChangeType.MODIFY) .map(diffEntry -> repo.getWorkTree().toPath().resolve(diffEntry.getNewPath())) .collect(Collectors.toSet()); } } catch (IOException | GitAPIException e) { LOG.warn(e.getMessage(), e); } return null; }
public static void main(String[] args) throws IOException, GitAPIException { try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { // the diff works on TreeIterators, we prepare two for the two branches AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, "b97b184b0ce11c0b6a4dcc2b57768ff155cb696b"); AbstractTreeIterator newTreeParser = prepareTreeParser(repository, "9e0719d7d773b41b49ebf04e6fd7b5c637e96063"); // then the porcelain diff-command returns a list of diff entries try (Git git = new Git(repository)) { List<DiffEntry> diff = git.diff(). setOldTree(oldTreeParser). setNewTree(newTreeParser). setPathFilter(PathFilter.create("README.md")). // to filter on Suffix use the following instead //setPathFilter(PathSuffixFilter.create(".java")). call(); for (DiffEntry entry : diff) { System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId()); try (DiffFormatter formatter = new DiffFormatter(System.out)) { formatter.setRepository(repository); formatter.format(entry); } } } } }