Created
July 4, 2025 13:33
-
-
Save simonsmith/1133fd148c69bc4aba981f23fb84bb70 to your computer and use it in GitHub Desktop.
Output Git information into JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Function to escape JSON strings | |
escape_json() { | |
echo "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g' | |
} | |
# Get git information | |
BRANCH=$(git symbolic-ref HEAD 2>/dev/null | sed 's/refs\/heads\///' || echo "unknown") | |
COMMIT_ID=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
COMMIT_USER_NAME=$(git log -1 --pretty=format:%an 2>/dev/null || echo "unknown") | |
COMMIT_USER_EMAIL=$(git log -1 --pretty=format:%ae 2>/dev/null || echo "unknown") | |
COMMIT_MESSAGE_FULL=$(git log -1 --pretty=format:%B 2>/dev/null || echo "unknown") | |
COMMIT_MESSAGE_SHORT=$(git log -1 --pretty=format:%s 2>/dev/null || echo "unknown") | |
COMMIT_TIMESTAMP=$(git log -1 --pretty=format:%ct 2>/dev/null || echo "0") | |
# Convert timestamp to readable format (matching Node.js Date.toString() format) | |
if [[ "$COMMIT_TIMESTAMP" != "0" ]]; then | |
COMMIT_TIME=$(date -d "@$COMMIT_TIMESTAMP" 2>/dev/null || date -r "$COMMIT_TIMESTAMP" 2>/dev/null || echo "unknown") | |
else | |
COMMIT_TIME="unknown" | |
fi | |
# Get abbreviated commit ID (first 7 characters) | |
if [[ "$COMMIT_ID" != "unknown" ]]; then | |
ABBREV_ID="${COMMIT_ID:0:7}" | |
else | |
ABBREV_ID="unknown" | |
fi | |
# Get build time in UTC format | |
BUILD_TIME=$(date -u '+%a, %d %b %Y %H:%M:%S GMT') | |
# Escape all values for JSON | |
BRANCH_ESC=$(escape_json "$BRANCH") | |
COMMIT_ID_ESC=$(escape_json "$COMMIT_ID") | |
ABBREV_ID_ESC=$(escape_json "$ABBREV_ID") | |
COMMIT_USER_NAME_ESC=$(escape_json "$COMMIT_USER_NAME") | |
COMMIT_USER_EMAIL_ESC=$(escape_json "$COMMIT_USER_EMAIL") | |
COMMIT_MESSAGE_FULL_ESC=$(escape_json "$COMMIT_MESSAGE_FULL") | |
COMMIT_MESSAGE_SHORT_ESC=$(escape_json "$COMMIT_MESSAGE_SHORT") | |
COMMIT_TIME_ESC=$(escape_json "$COMMIT_TIME") | |
BUILD_TIME_ESC=$(escape_json "$BUILD_TIME") | |
# Output JSON | |
cat << EOF | |
{ | |
"buildTime": "$BUILD_TIME_ESC", | |
"git": { | |
"commit": { | |
"message": { | |
"full": "$COMMIT_MESSAGE_FULL_ESC", | |
"short": "$COMMIT_MESSAGE_SHORT_ESC" | |
}, | |
"time": "$COMMIT_TIME_ESC", | |
"id": "$COMMIT_ID_ESC", | |
"abbrevId": "$ABBREV_ID_ESC", | |
"user": { | |
"email": "$COMMIT_USER_EMAIL_ESC", | |
"name": "$COMMIT_USER_NAME_ESC" | |
} | |
}, | |
"branch": "$BRANCH_ESC" | |
} | |
} | |
EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment