In the last days, I’ve found two situations in which I needed to get info from all git repositories in a directory and sub-directories and so on. The first case was that I had to check the status of some repositories in deployed devices, this is, what repositories existed and in which version or commit they were. The second case was that I bought a new laptop and had to re-create my workspace, including personal and third-party repositories.

For this reason, I create this bash script which scans a specified directory looking for a git repository and then search through all subdirectories. The output includes the remote URL and the current commit for each repository found. I also included in the comments the option to change commit SHA for the output of ‘git describe’, which includes the nearest annotated tag information. For now, this script does not scans for submodules within a git repository

#!/bin/bash

for i in "$@"
do
case $i in
    -d=*|--dir=*)
    dir_name="${i#*=}"
    shift # past argument=value
    ;;

    *)
            # unknown option
    ;;
esac
done

script_name=$(echo $0 | grep -oP '[0-9A-Za-z_]*$')

if [ -z "${ppath}" ] ; then
export ppath=$PWD
fi

if [ -d "$dir_name" ]; then
    cd "$dir_name"
    ls_out=$(ls .git 2>&1)
    has_git=$?

    if [ 0 -eq "$has_git" ]; then
        remote=$(git config --get remote.origin.url)

        # Use this for print current commit SHA
        # curr_head=$(git rev-parse HEAD)

        # Use this to use annotated tags, It will prompt errors if no annotated tags exist
        curr_head=$(git describe)

        echo -e "$remote\t$curr_head"
    else
        find . -maxdepth 1 -mindepth 1 -type d -regex '.*/[^.-].*' -printf '%f\n' | while read i
        do
            $ppath/$script_name -d="$i" &
        done
    fi

else
    echo "No directory specified $PWD $dir_name"
    echo "USAGE: git_list -d="
fi

Feel free to leave any suggestions or opinions in the comments below.

Advertisements