Skip to content

Instantly share code, notes, and snippets.

@sbose78
Last active April 11, 2024 19:36
Show Gist options
  • Save sbose78/a9e11c5e94994736c9bb10d68948846d to your computer and use it in GitHub Desktop.
Save sbose78/a9e11c5e94994736c9bb10d68948846d to your computer and use it in GitHub Desktop.
Pre-commit hook to update package.json
#!/bin/bash
set -e
update_version(){
if [[ "$DONT_BUMP_VERSION" -ne "1" ]]
then
echo " Bumping version.. "
else
echo "Version will not be bumped since variable DONT_BUMP_VERSION is set."
exit 0
fi
old_version=`cat package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[\",]//g' | tr -d '[[:space:]]'`
version_split=( ${old_version//./ } )
#increment the number at the 3rd position ( 0,1,2 )
((version_split[2]++))
new_version="${version_split[0]}.${version_split[1]}.${version_split[2]}"
# overwrite it in the package.json file
sed -i -e "0,/$old_version/s/$old_version/$new_version/" package.json
}
# show off the old version
npm version | head -1
update_version
# show off the updated version
npm version | head -1
# track the change
git add package.json
@russoedu
Copy link

Nice script! I just added it to my git with some changes. Because I use npm ci on my CI pipeline, I need package-lock to have the same version as package, so I updated the end of the script to update package lock:

# show off the updated version
npm version | head -1

# run install to update package-lock.json
npm install

# track the changes
git add package.json
git add package-lock.json

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