Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run husky pre-commit in child directory only

We have an enterprise application with a folder structure like the following:

/project
  .git
  /sub1
    ...Java project
  /sub2
    package.json
    ...Javascript Backbone project
  /sub3
    ...Java project
  /sub4
    ...Java project
  /sub5
    package.json
    ...Javascript React project

I currently have Husky set up both in sub2 and sub5 projects, which causes conflicts (requires an npm install whenever I switch projects). Also, the Java developers are reporting that when they commit code in projects sub1, sub3 and sub4, the Husky git hooks are being executed.

Is it possible to only have the hooks run if you are IN a certain folder when you commit?

like image 542
JoshT Avatar asked Dec 20 '18 12:12

JoshT


2 Answers

I faced the same issue. I fixed it by installing husky in the main directory.
my setup:

/project
    .git
    package.json
    /frontend
        package.json
    /frontend-admin
        package.json

In /project/package.json:

{
  "license": "MIT",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "frontend": "cd frontend && yarn lint"
    "frontend:admin": "cd frontend-admin && yarn lint",
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm-run-all frontend frontend:admin"
    }
  },
  // In the main folder you should install husky 
  // and npm-run-all to execute multiple commands
  "dependencies": {
    "husky": "^4.3.0",
    "npm-run-all": "^4.1.5"
  }
}

Your subdirectory should have a lint script to execute.
When one of the scripts crashes husky will give a report and abort immediately.

like image 131
user3379167 Avatar answered Sep 20 '22 14:09

user3379167


While this question is a few years old. Hopefully someone will benefit from an updated answer provided by the folks from husky.

TL;DR

See the new guidance here.

For those that w@ntz answ3rz n0wz!!

New guidance that is provided in the typicode/husky-init README.md suggests the following when "your package.json file and .git directory are not at the same level. For example, project/.git and project/front/package.json"

You can change directory during prepare script and pass a subdirectory:

// package.json
{
  "scripts": {
    "prepare": "cd .. && husky install front/.husky"
  }
}
like image 42
abest Avatar answered Sep 17 '22 14:09

abest