Two of the most common commands I run when I cd into a directory are:

  1. git status (which i do through git-number)
  2. ls -lh (aliased automatically as ll through fish)
  • If this directory is not a git repo, then I usually am thinking of command 2.
  • If however it is a git repository then
    • I’d like to know if any files have been changed in this directory and
    • which ones specifically (which is command 1).

Wouldn’t it be nice if I could just hit the ↩ (enter key) and have this automatically happen?

If you’re using fish, I got you covered:

# fish/conf.d/magic-enter.fish
function magic-enter-cmd --description "Issue git status or ls on hitting enter in a dir"
    set -l cmd ll
    set -l is_git_repository (fish -c "git rev-parse --is-inside-work-tree >&2" 2>| grep true) # Special variable indicating git.
    set -l in_root_folder (fish -c "git rev-parse --show-toplevel >&2" 2>| grep (pwd))
    set -l repo_has_changes (git status -s --ignore-submodules=dirty)

    if test -n "$is_git_repository"
        if test -n "$in_root_folder"
            if test -n "$repo_has_changes"
                set cmd git-number
            end
        end
    end

    echo $cmd
end

function magic-enter
    set -l cmd (commandline)
    if test -z "$cmd"
        commandline -r (magic-enter-cmd)
        commandline -f suppress-autosuggestion
    end
    commandline -f execute
end

bind \r magic-enter

Revisions

  • Make a change to only check git status in a root folder.
  • Reddit /u/colemaker360 reminded me that the ^/dev/null redirect strategy is now deprecated with fish 3.
  • Redditor /u/jblondreddit pointed out that porcelain can be a slow.