/ PROGRAMMING, WEB TECHNOLOGIES, TECH

Git: Hooks run “npm install” on checkout

When working on a project you usually install various packages from NPM. Of course, these packages are maintained and updated, adding more features and security fixes, and stability patches.

One person on your team should run npm outdated once per week to see what all has been updated and test if you can integrate the packages into your project. Thus the package.json is updated and causes a grand problem for all other developers on the project. If a package has major breaking changes the code will need to be adjusted, however, that code will not run on the other developer’s environment. The other developers working on the project they have to run npm update to install the missing/outdated packages in their environment.

The solution to this problem is “git hooks”, essentially git can execute code on specific events, like before committing your code, or pre-push etc. git hooks. For my use case, I would like to run npm update after a developer checks out from the git repository, this is the event “post-checkout”.

Native Git Hooks

To create a git hook you need to add a file to your project called .git/hooks/post-checkout (On Linux add the executable bit with chmod +x)

#!/bin/sh
echo "[post-checkout hook: $1]"

changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"

check_run() {
  echo "$changed_files" | grep -E --quiet "$1" && eval "$2"
}

check_run package.json "npm update"

exit 0 #Needed so Visual Studio Code does not display an error

You will test this and say, yes this works as intended - let’s commit it to the repository. - Now you will discover that you cannot commit files in .git to the repository. In fact, git does not allow you to do this, due to security concerns as git hooks can execute any shell script.

The workaround for this issue is to simply add it into a folder called git-hooks/ and tell the developers to copy the file when they set up their dev environment.

Husky

As always if there is a Problem for development with javascript there is an npm package to solve the problem. Husky uses the package.json to define the scripts that are executed via git hooks. Simply Install Husky npm install husky -D

Then edit the package.json:

{ 
    "name" : "test Project"
    "scripts": {
          "postupdate": "npm update"
    }
}

The Husky solution would also allow you to execute your own js file, maybe also doing some cleanup of files or running tests etc.

Image: Designed by Freepik