How can I fix these errors using Husky with SourceTree on MacOs with nvm? "Can't find node in PATH" and "Current directory is not a git directory!"

Viewed 5234

I'm seeing errors when I use husky hooks in a node project and attempt to commit to git via an app, SourceTree. The hooks are specified in package.json. I'm using nvm to manage node versions.

The error Can't find node in PATH husky > pre-commit hook failed is reported when SourceTree is used for a git commit.

Once this error is bypassed, husky reports another error when commit is attempted via SourceTree, using SourceTree's embedded git: "Current directory is not a git directory!".

How can I resolve the errors?

3 Answers

(1) To solve the first error, "Can't find node in PATH":

Since you're running git from an app (SourceTree) and not from the command line, husky doesn't have the env vars to find node. To solve this issue, husky provides a mechanism: it will run the user-specified file ~/.huskyrc before running hooks.

This worked for me:

in .bashrc, I added this line after the PATH was set:

echo "export PATH="$(dirname $(which node)):$PATH"" > ~/.huskyrc

Another suggestion is described in the husky documentation, https://typicode.github.io/husky/#/?id=command-not-found

# ~/.huskyrc
# This loads nvm.sh and sets the correct PATH before running hook
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

(2) To solve "Current directory is not a git directory!" A number of users have reported that changing their git version has resolved this issue for them.

If you're using SourceTree, you can configure it to use either the embedded git version inside SourceTree or a system version. When I switched from the embedded version in SourceTree, which is 2.31.0, to the system version, which is 2.30.1 on my system, the error was resolved.

In SourceTree, go to Preferences -> git to set the git version.

Switched from the embedded version in SourceTree, which is 2.31.0, to the system version, which is 2.30.1 on my system, the error was resolved.

Most universal and correct way for using Husky and SourceTree will be having next in ~/.huskyrc

#!/usr/bin/env bash

# Load NVM support and all defined ENV variables
source ~/.bash_profile

# Check if this repo has .nvmrc file and use it to set proper Node.js version
if test -f ".nvmrc"; then
    nvm use
fi

If it's not .bash_profile in your case, use another file, it should contain all the nvm.sh setup scripts required by NVM. First step could be optional in some cases, depends on bash profile setup.

Related