每次 commit 時會自動執行。例如我們想要每次 git commit 在 package.json version 自動加 0.0.1
可以如下新增 setup-pre-commit.sh:
記得先 brew install jq
#!/bin/sh# setup-pre-commit.sh# Path to the pre-commit hookHOOK_PATH=".git/hooks/pre-commit"# Pre-commit hook scriptHOOK_SCRIPT="#!/bin/sh\n\n# Increment version in package.json using jq\nVERSION=\$(jq -r '.version' package.json)\nNEW_VERSION=\$(echo \$VERSION | awk -F. -v OFS=. '{\$NF = \$NF + 1 ; print}')\n\n# Update the version in package.json\njq \".version = \\\"\$NEW_VERSION\\\"\" package.json > temp.json && mv temp.json package.json\n\n# Add the package.json to the commit\ngit add package.json\n\n# Exit successfully\nexit 0"
# Create the pre-commit hookecho"$HOOK_SCRIPT">"$HOOK_PATH"# Make the pre-commit hook executablechmod+x"$HOOK_PATH"echo"Pre-commit hook set up successfully."