gitlabstatisticsgitlab-api

GitLab API - get the overall # of lines of code


I'm able to get the stats (additions, deletions, total) for each commit, however how can I get the overall #? For example, if one MR has 30 commits, I need the net # of lines of code added\deleted which you can see in the top corner. This # IS NOT the sum of all #'s per commit. So, I would need an API that returns the net # of lines of code added\removed at MR level (no matter how many commits are). For example, if I have 2 commits: 1st one adds 10 lines, and the 2nd one removes the exact same 10 lines, then the net # is 0.


Here is the scenario: I have an MR with 30 commits. GitLab API provides support to get the stats (lines of code added\deleted) per Commit (individually). If I go in GitLab UI, go to the MR \ Changes, I see the # of lines added\deleted that is not the SUM of all the Commits stats that I'm getting thru API. That's my issue. A simpler example: let's say I have 2 commits, one adds 10 lines of code, while the 2nd commit removes the exact same 10 lines of code. Using the API, I'm getting the sum, which is 20 LOCs added. However, if I go in the GitLab UI \ Changes, it's showing me 0 (zero), which is correct; that's the net # of chgs overall. This is the inconsistency I noticed.


Solution

  • To do this for an MR, you would use the MR changes API and count the occurrences of lines starting with + and - in the changes[].diff fields to get the additions and deletions respectively.

    Using bash with gitlab-org/gitlab-runner!3195 as an example:

    GITLAB_HOST="https://gitlab.com"
    PROJECT_ID="250833"
    MR_ID="3195"
    
    URL="${GITLAB_HOST}/api/v4/projects/${PROJECT_ID}/merge_requests/${MR_ID}/changes"
    DIFF=$(curl ${URL} | jq -r ".changes[].diff")
    ADDITIONS=$(grep -E "^\+" <<< "$DIFF")
    DELETIONS=$(grep -E "^\-" <<< "$DIFF")
    NUM_ADDITIONS=$(wc -l <<< "$ADDITIONS")
    NUM_DELETIONS=$(wc -l <<< "$DELETIONS")
    echo "${MR_ID} has ${NUM_ADDITIONS} additions and ${NUM_DELETIONS} deletions"
    

    The output is

    3195 has 9 additions and 2 deletions
    

    This matches the UI, which also shows 9 additions and 2 deletions

    GitLab-Runner MR 3195 diff UI

    This, as you can see is a representative example of your described scenario since the combined total of the individual commits in this MR are 13 additions and 6 deletions.