R/O

CLI で GitHub のようにファイルを一覧表示する

Posted on 2022-07-31

CLI でも GitHub 等のようにファイルごとの最終更新を一覧表示したくなることがあるので、簡単なスクリプトを書いた。 git-ls としてパスの通った場所に置いて git ls で使えるようにしている。

#!/bin/sh

ls_file() {
    file_path="${1%%/}"
    file_basename=$(basename "${file_path}")
    ls_tree_opt=
    if [ -d "${file_path}" ]; then
        file_basename="${file_basename}/"
        ls_tree_opt='-d'
    fi
    file_mode=$(git ls-tree ${ls_tree_opt} HEAD -- "${file_path}" | cut -d ' ' -f 1)
    if [ -n "${file_mode}" ]; then
        git log -1 --pretty=format:"${file_mode} ${file_basename} %x09 %h %s %x09 %cr%n" HEAD -- "${file_path}"
    else
        printf '%s %s \t %s \t uncommitted\n' '------' "${file_basename}" '-------'
    fi
}

path="${1:-.}"
if [ -f "${path}" ]; then
    pattern="${path}"
elif [ -d "${path}" ]; then
    pattern="${path}/.* ${path}/*"
else
    echo "no such file or directory: ${path}"
    exit 1
fi

for file in ${pattern}; do
    case "${file}" in
    "${path}"/.|"${path}"/..)
        continue
        ;;
    "${path}"/.git)
        continue
        ;;
    "${path}/.*"|"${file}/*")
        continue
        ;;
    esac
    ls_file "${file##./}"
done | column -t -s '	'

Gist にも置いてある: https://gist.github.com/ryot4/245a4b2c28b064c68c1d957b8d580d18

サンプルとして https://github.com/githubtraining/hellogitworld で使ってみると以下のような表示になる。

hellogitworld $ git ls
100644 .gitattributes    bf7a9a5 .gitattributes to make this play nicely onWindows          10 years ago
100644 .gitignore        d2280d0 Adding maven build script                                  10 years ago
100644 .travis.yml       9805760 Fix YAML name-value pair missing space                     8 years ago
100644 README.txt        a13dba1 Even I can change the readme file                          9 years ago
100644 build.gradle      c594793 Added gradle build file                                    10 years ago
100644 fix.txt           78f4771 Fixes #1                                                   10 years ago
100644 pom.xml           ef7bebf Fix groupId after package refactor                         8 years ago
040000 resources/        755fd57 Addition of the README and basic Groovy source samples.    11 years ago
100755 runme.sh          f5ed019 Added shell script to drive the execution of the app       11 years ago
040000 src/              ebbbf77 Update package name, directory                             8 years ago

ファイルの数だけ git log を叩く実装なのでリポジトリによっては結構重い点は要注意。