Skip to content

Instantly share code, notes, and snippets.

@satinP
Last active January 6, 2024 20:19
Show Gist options
  • Save satinP/a8a201ee59ea90bc1de540de12457c42 to your computer and use it in GitHub Desktop.
Save satinP/a8a201ee59ea90bc1de540de12457c42 to your computer and use it in GitHub Desktop.
Shell function that runs nodejs package manager based on lockfile (npm, yarn, pnpm, bun)
function pm() {
if [ -f package-lock.json ]; then
echo "Running with $(tput bold)npm"
command npm "$@"
elif [ -f yarn.lock ]; then
echo "Running with $(tput bold)yarn"
command yarn "$@"
elif [ -f pnpm-lock.yaml ]; then
echo "Running with $(tput bold)pnpm"
command pnpm "$@"
elif [ -f bun.lockb ]; then
echo "Running with $(tput bold)bun"
command bun "$@"
else
echo "No lockfile found for npm, yarn, pnpm or bun.\nRunning with $(tput bold)npm as the default package manager."
command npm "$@"
fi
}
@satinP
Copy link
Author

satinP commented Jan 6, 2024

It can also be written with case statement:

function pm() {
  case 1 in
    $(test -f package-lock.json && echo 1) )
      echo "Running with $(tput bold)npm"
      command npm "$@"
      ;;
    $(test -f yarn.lock && echo 1) )
      echo "Running with $(tput bold)yarn"
      command yarn "$@"
      ;;
    $(test -f pnpm-lock.yaml && echo 1) )
      echo "Running with $(tput bold)pnpm"
      command pnpm "$@"
      ;;
    $(test -f bun.lockb && echo 1) )
      echo "Running with $(tput bold)bun"
      command bun "$@"
      ;;
    * )
      echo "No lockfile found for npm, yarn, pnpm, or bun.\nRunning with $(tput bold)npm as the default package maneger."
      command "$DEFAULT_MANAGER" "$@"
      ;;
  esac
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment