Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: Getting total numbers of uncomitted lines in a repo

Tags:

git

bash

zsh

Is there a command to get just total number of lines that are changed in current git repo. I want to take count considering both staged and unstaged files.

This is the closest I could get

$ git diff --cached --shortstat
 1 file changed, 1 insertion(+), 1 deletion(-)

$ git diff --shortstat
 1 file changed, 1 insertion(+)

But I have to execute two commands and then parse (quite error prone, you never know all cases) result to find number of lines that have changed.

If not a git command, a bash/zsh function would also do.

UPDATE:

So the idea was to track total uncommitted lines (showing approximate level of dirtiness of a git working directory) on my ZSH prompt, Something like:

[~/dotfiles] (master) ✗ [192]
$ ...

So thanks to @arco444's answer, which I slightly modified, I now have following, just if someone wants to achieve the same

function git_change_count {
    local IS_INSIDE_REPO=$(git rev-parse --is-inside-work-tree 2>/dev/null)
    if [[ $IS_INSIDE_REPO == "true" ]]; then
        { git diff --cached --numstat; git diff --numstat; } | awk '{ a+=($1+$2) } END {print a}'
    fi
}

I am adding the lines that were added and deleted lines, instead of getting their diff. Which essentially means edited lines shows up as 2 but doing so covers the scenario when two different lines were added and deleted and because of subtraction we get 0 as result.

like image 934
kdabir Avatar asked Dec 25 '22 12:12

kdabir


1 Answers

How about:

{ git diff --cached --numstat; git diff --numstat; } | awk '{ a+=($1-$2) } END {print a}'

The --numstat flag gives you:

#added #deleted #filename

You need to run it for both staged and unstaged files, then pipe to awk to do the arithmetic. It will return a sum of added and deleted lines, so you will get a negative result if more lines were removed than added.

like image 171
arco444 Avatar answered Jan 13 '23 14:01

arco444