Assuming the following code snippet is bound to a Git repository:
int test(){ int a = 3; int b = 4; int c = a + b; return c; }
and later updated to
int test(){ return 7; }
I currently have a method that uses the JGit API to access the Git repository, as indicated above, and outputs a line that looks like the following:
int test(){ -int a = 3; -int b = 4; -int c = a + b; -return c; +return 7; }
Now my requirements have changed and would like to know the line numbers of only the changed lines. So I would like something like the following:
2 -int a = 3; 3 -int b = 4; 4 -int c = a + b; 5 -return c; 2 +return 7;
Basically, the same information as the GitHub application when creating the update.
Any help would be greatly appreciated :)
fragment of how strings are calculated - / +:
String oldHash = "ee3e216ab5047748a22e9ec5ad3e92834704f0cc"; Git git = null; try { //the path where the repo is. git = Git.open(new File("C:\\Users\\Administrator\\Documents\\GitHub\\Trial")); } catch (IOException e1) { e1.printStackTrace(); } Repository repository = git.getRepository(); ObjectId old = null; ObjectId head = null; //a new reader to read objects from getObjectDatabase() ObjectReader reader = repository.newObjectReader(); //Create a new parser. CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); List<DiffEntry> diffs = null; try { //parse a git repository string and return an ObjectId old = repository.resolve(oldHash + "^{tree}"); head = repository.resolve("HEAD^{tree}"); //Reset this parser to walk through the given tree oldTreeIter.reset(reader, old); newTreeIter.reset(reader, head); diffs = git.diff()//Returns a command object to execute a diff command .setNewTree(newTreeIter) .setOldTree(oldTreeIter) .call();//returns a DiffEntry for each path which is different } catch (RevisionSyntaxException | IOException | GitAPIException e) { // TODO Auto-generated catch block e.printStackTrace(); } //DiffLineCountFilter d = new DiffLineCountFilter(); //out is the stream the formatter will write to ByteArrayOutputStream out = new ByteArrayOutputStream(); //Create a new formatter with a default level of context. DiffFormatter df = new DiffFormatter(out); //Set the repository the formatter can load object contents from. df.setRepository(git.getRepository()); ArrayList<String> diffText = new ArrayList<String>(); //A DiffEntry is 'A value class representing a change to a file' therefore for each file you have a diff entry for(DiffEntry diff : diffs) { try { //Format a patch script for one file entry. df.format(diff); RawText r = new RawText(out.toByteArray()); r.getLineDelimiter(); diffText.add(out.toString()); out.reset(); } catch (IOException e) { e.printStackTrace(); } }
java git eclipse jgit
gracey
source share