Skip to content

Instantly share code, notes, and snippets.

@zanbaldwin
Last active January 4, 2024 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zanbaldwin/19d10f103fcefa301b2ba144d4610b8b to your computer and use it in GitHub Desktop.
Save zanbaldwin/19d10f103fcefa301b2ba144d4610b8b to your computer and use it in GitHub Desktop.
Onefetch Git Information on `cd`

Show Git Information when cding into a Git repository

  1. Install onefetch by either:
    • Compiling it from scratch using the Rust compiler, Cargo: with the command cargo install onefetch
    • Downloading a pre-built binary from Onefetch's GitHub releases page (recommended) and placing it in your $PATH (such as /usr/local/bin/onefetch).
  2. Add the snippet listed in onefetch_on_cd.sh to whatever file that gets run whenever you start a new Bash session. This differs per distro but common files include:
    • ~/.bashrc
    • ~/.bash_profile
    • sometimes ~/.bash_aliases?

Extra Information

Is this safe?

That depends.
Is it safe to blindly trust random code and programs from the internet?
I mean, what's the worst that could happen? Go on, do it. You know you want to.

Where did this come from?

From the Git repository where I store all my dotfiles, which includes lots more useful Bash aliases and shortcuts.
Start a dotfiles repo today, you'll be hooked forever! 🥳

Will it slow my computer down?

No, it's pretty fast. Unless you're cding into a massive repository like the Linux kernel which is several gigabytes in size and over 1.2 million commits. Then it takes about 20 seconds.

For normal web projects it's almost instant.

## Add this to whatever file that gets run whenever you start a new Bash session
## Eg, `~/.bashrc` or `~/.bash_profile` etc.
## Keep a record of the last repository we cd'd into.
CD_LAST_REPO=""
## Git Repository Information on Directory Change
function cd {
## Perform the normal `cd` operation first. Return quickly if that fails (eg, directory does not exist).
builtin cd "$@" || return;
## Only do this if both `git` and `onefetch` are installed.
if command -v "onefetch" >"/dev/null" 2>&1 && command -v "git" >"/dev/null" 2>&1; then
## Get the directory of the Git repository we're in, regardless of how many directories we're nested in.
if git rev-parse --show-toplevel >"/dev/null" 2>&1; then
NEW_REPO="$(git rev-parse --show-toplevel 2>"/dev/null")"
## Only show information if we've cd'd into a _different_ repository.
## No need to display it every time we cd from `gitrepo` to `gitrepo/src`, etc.
if [ "${CD_LAST_REPO}" != "${NEW_REPO}" ]; then
## Display Git repository information in all it's Rusty goodness.
onefetch
## Remember the new Git repository we've cd'd into.
CD_LAST_REPO="${NEW_REPO}"
fi
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment