extract commit messages to json

mail@pastecode.io avatar
unknown
powershell
14 days ago
2.2 kB
4
Indexable
Never
#!/bin/bash

authors=("Muhammad Nasif Imtiaz" "muhammadnasif")
output_file="commits.json"

# Initialize an empty array to hold all commit objects
all_commits=()

for author in "${authors[@]}"; do
    echo "Processing commits by $author..."

    # Get commit hashes by author and sort them by date
    commit_hashes=$(git log --author="$author" --date-order --reverse --pretty=format:"%H")

    for hash in $commit_hashes; do
        # Fetch the commit date in the desired format
        commit_date=$(git log -1 --pretty=format:"%ad" --date=format:"%d-%m-%Y" $hash)

        # Fetch the commit message
        commit_message=$(git log -1 --pretty=format:"%s" $hash)
        
        # Fetch the file paths for the current commit and store filenames and paths separately
        file_paths=$(git show --pretty="" --name-only $hash)
        filenames=()
        paths=()
        
        for path in $file_paths; do
            # Extract the file name from the path
            file_name=$(basename "$path")
            filenames+=("$file_name")
            # Extract the path without the filename
            directory_path=$(dirname "$path")
            paths+=("$directory_path")
        done

        # Create a JSON object for the current commit
        commit_object=$(jq -n \
            --arg author "$author" \
            --arg hash "$hash" \
            --arg message "$commit_message" \
            --arg date "$commit_date" \
            --argjson files "$(printf '%s\n' "${filenames[@]}" | jq -R . | jq -s .)" \
            --argjson paths "$(printf '%s\n' "${paths[@]}" | jq -R . | jq -s .)" \
            '{
                author_name: $author,
                commit_hash: $hash,
                message: $message,
                date: $date,
                files: $files,
                paths: $paths
            }')

        # Append the JSON object to the array
        all_commits+=("$commit_object")
    done
done

# Write the array of commit objects to the output file
printf '%s\n' "${all_commits[@]}" | jq -s . > "$output_file"

echo "Output written to $output_file"
Leave a Comment