Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active April 20, 2024 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magnetikonline/287813d76bd3d904065eb12f4ca80eab to your computer and use it in GitHub Desktop.
Save magnetikonline/287813d76bd3d904065eb12f4ca80eab to your computer and use it in GitHub Desktop.
npm wrapper script to ensure `npm publish` from a clean Git repository.

npm wrapper to ensure npm publish from clean Git repository

Tip

By default npm publish will publish all files within a working directory - excluding .gitignore / .npmignore / package-lock.json.

This is typically fine, but often I find myself leaving un-staged files (e.g. TODO.txt files) in a repository root and these of course get accidently taken along for the publish ride.

Helper script npm-publish-wrap.sh will catch calls to npm publish and:

  • Ensure I'm at the root of a repository (.git directory) found.
  • Local git clone the current repository to a temp directory - removing any unstaged files.
  • npm publish the cloned repository into the registry.

I have this set as an alias in my ~/.bash_profile:

alias npm='/path/to/npm-publish-wrap.sh'
#!/bin/bash -e
NPM_BIN="/usr/local/bin/npm"
function exitError {
echo "Error: $1" >&2
exit 1
}
function main {
if [[ $1 == "publish" ]]; then
shift
# always ensure `npm publish` from a clean Git repository
if [[ ! -d .git ]]; then
exitError "expected .git/ directory not found"
fi
local cloneDir=$(mktemp -d)
git clone . "$cloneDir"
# ensure `package-lock.json` version matches that set in `package.json` - if not will abort
# can use `npm install --package-lock-only` to rebuild `package-lock.json`
cd "$cloneDir"
$NPM_BIN install --package-lock-only
cd -
set +e
git --work-tree="$cloneDir" diff --exit-code
if [[ $? -ne 0 ]]; then
exitError "package-lock.json requires update"
fi
set -e
# ready to publish
$NPM_BIN publish "$@" "$cloneDir"
return
fi
# not publishing - pass all arguments directly to npm
$NPM_BIN "$@"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment