What is the git command to get only the newly added/modified lines in a commit?

396 views Asked by At

I want to write shell script to parse java source files and find-out the common violations in source code based on some rule. This script should run on new code which is added/modified , this shouldn't get the old code. My code repository is git.

How to get the newly added/modified lines from git. I can then execute my script on top this.

1

There are 1 answers

4
LeGEC On

If you want to apply some parsing action on code, you are probably better off parsing whole files rather than spotting only the modified lines. On top of that, the notion of "added line" depends a lot on the heuristic implemented in diff, and will often give you results that don't match what you would expect.


I didn't get the context from your question, especially what you intend to compare :

  • to list modified files, use git diff --name-only or git diff --name-status :
# list of tracked files modified on disk since last commit :
git diff --name-status HEAD

# list of files modified between 2 commits :
git diff --name-status <commit1> <commit2>

# list of files modified in branch 'feature' since it forked from 'master' :
# (this will give you the same list as in a PR view)
git diff --name-status master...feature  # 3 dots, not a typo

# list files modified in a specific commit :
# compare it to its parent (add a '^' at the end)
git diff --name-status <commit>^ <commit>

If you need to target merge commits (which have more than one parent), git show tries to be smart and may give you better results :

git show --format="" --name-only <commit>

If you really want just the modified/added lines : just grep them from git diff

for each modified file, run something like :

# get lines starting with '+', but drop the extra '+++ the/file' line added
# by git
git diff <a> <b> -- the/file | grep '^+' | grep -v '^+++'