Skip to content

Instantly share code, notes, and snippets.

@CodeanIO
Created November 2, 2023 13:36
Show Gist options
  • Save CodeanIO/bb68f9ed015f68afb3f9b13f638b4f3c to your computer and use it in GitHub Desktop.
Save CodeanIO/bb68f9ed015f68afb3f9b13f638b4f3c to your computer and use it in GitHub Desktop.
Shell script for estimating LoC and average LoC/month
#!/bin/bash
# -------------------------------------------------------------------------------
# 1. Save this file to your computer
# 2. Mark as executable:
# chmod +x get_loc.sh
# 3. Navigate to a Git repository
# 4. Run the script:
# ./get_loc.sh
#
# The resulting numbers can be used as input here: https://codeanlabs.com/pricing
# -------------------------------------------------------------------------------
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Rough over-estimate of LoC, also counts comments and non-code (if any)
TOTAL_LOC=$(git ls-tree -r "$CURRENT_BRANCH" --name-only -z | xargs -0 wc -l 2>/dev/null | tail -n 1 | awk '{print $1}')
# Get earliest and latest commit hash and date
IFS=" " read -r OLDEST_COMMIT OLDEST_COMMIT_DATE <<<$(git rev-list --reverse "$CURRENT_BRANCH" --pretty='format:%H %cs'| sed -n '2p')
IFS=" " read -r LATEST_COMMIT LATEST_COMMIT_DATE <<<$(git rev-list "$CURRENT_BRANCH" --pretty='format:%H %cs'| sed -n '2p')
# Split out year and month
Y1=${OLDEST_COMMIT_DATE:0:4}
M1=${OLDEST_COMMIT_DATE:5:2}
Y2=${LATEST_COMMIT_DATE:0:4}
M2=${LATEST_COMMIT_DATE:5:2}
# Disregards days, so this is not entirely accurate
DELTA_MONTHS=$(( ($Y2 - $Y1) * 12 + ($M2 - $M1) ))
SHORTSTAT=$(git diff --shortstat "$OLDEST_COMMIT" "$LATEST_COMMIT")
N_INSERTIONS=$(echo "$SHORTSTAT" | awk '{print $4}')
N_DELETIONS=$(echo "$SHORTSTAT" | awk '{print $6}')
TOTAL_LINE_DIFF=$(( $N_INSERTIONS + $N_DELETIONS ))
LINE_DIFF_AVG_MONTH=$(( $TOTAL_LINE_DIFF / $DELTA_MONTHS ))
echo "Current total LoC: $TOTAL_LOC"
echo "Avg. delta LoC/mo: $LINE_DIFF_AVG_MONTH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment