Skip to content

Instantly share code, notes, and snippets.

@marckubischta
Last active September 30, 2024 16:55
Show Gist options
  • Save marckubischta/795c293d42be2bf3603d318ac5bc0a0f to your computer and use it in GitHub Desktop.
Save marckubischta/795c293d42be2bf3603d318ac5bc0a0f to your computer and use it in GitHub Desktop.
Bash cd package shortcuts with tab completion
#!/usr/bin/env bash
#
# For moving between packages in an npm monorepo
#
# Installation:
# add `source packages-completion.sh` or the contents of this file to your .bash_profile
#
# Usage:
# While working in a npm monorepo
# - `cd_<tab><enter>` to return to the root (unless you have another alias starting with `cd_`)
# - `pkg package_name<enter>` to change to a package directory
# - `pkg <tab><tab>` to list all packages
# - `pkg str<tab>` to complete a package name uniquely starting with `str`
# - `pkg str<tab><tab>` to list all packages starting with `str`
# print the root directory of the current path
monorepo_rootdir() {
pwd | sed -Ee "s:(.*)/packages.*:\1:"
}
# cd into the root
cd_monorepo_rootdir() {
cd $(monorepo_rootdir)
}
# cd into a specific package dir
pkg() {
cd_monorepo_rootdir
cd packages/$*
}
# shell tab completion helper for pkg function
_pkg_completion() {
# the current input commandline is passed via COMP_WORDS / COMP_CWORD
# the word currently being typed:
local WORD="${COMP_WORDS[COMP_CWORD]}"
# current working root
local MONO_ROOT=$(monorepo_rootdir)
# set possible valid completions in COMPREPLY
COMPREPLY=( $(/bin/ls -1 "$MONO_ROOT/packages" | grep "$WORD") )
} &&
# set shell tab completion for "pkg"
# -F [function]: run function (1) for invocations of command (2)
complete -F _pkg_completion pkg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment