How to efficiently run lint, format, and test only on modified files with git and husky
Tags: webdev, productivity, git, frontend
Published: 2023-09-22 05:28:48

Hi everyone, my name is Sai and i am currently working as a Frontend developer.

In this article we will find out on how to run Lint, Format and Test only on changed files and integrate them on Pre-commit and Pre-push using husky.

> First lets setup Husky, Eslint, Prettier and Jest

If you already have husky in your project you can skip this section and move to Run checks only on modified files.

```
npm i husky
```

you can find more about husky [here](https://www.npmjs.com/package/husky)

Then you can install ESlint(or similar library), Prettier(or similar library) and Jest(or similar library).

## Setting up husky and pre-commit hooks

Under package.json

```
"scripts": {
    "lint": "eslint --ignore-path ../../.eslintignore",
    "format:check": "prettier --check './src/**/*.{js,jsx,scss}'",
    "test": "jest --collectCoverage"
},
"husky": {
    "hooks": {
        "pre-commit": "npm run format:check && npm run lint",
        "pre-push": "npm run test",
    }
}
```
With this above husky commands whenever we try to commit format:check and lint will run, And when pushing to origin test will run.

## Run checks only on modified files

Challenges with the above approach is it run checks on the entire codebase during commits or push. which consumes time and CPU

> Can we somehow run only on changed files while commit - Yes we can let's see how to implement it.

There are couple of ways to achieve this

1. Using custom git commands
2. Using lint-staged library

## 1. Using custom git commands for pre-commit

```
"scripts": {
    "lint:pre-commit" : "eslint --ignore-path ./.eslintignore $(git diff --staged --name-only | grep -E '.ts$|.tsx$' | xargs)",
    "format:pre-commit": "prettier --check $(git diff --staged --name-only | grep -E '.ts$|.tsx$|.scss$' | xargs)"
},
"husky": {
    "hooks": {
        "pre-commit": "npm run format:pre-commit && npm run lint:pre-commit"
    }
}
```
The main command here is

```
git diff --staged --name-only | grep -E '.ts$|.tsx$' | xargs
// (git diff --staged --name-only) this will give all the staged files which are to be commited
// (grep -E '.ts$|.tsx$') this will filter the files ending with particular extension
// xargs will give in space separated format
```

## 2. Using Lint-staged

check this [link](https://www.npmjs.com/package/lint-staged) on how to install lint-staged

`npm i -D lint-staged
`

Create a file ends with .json, i named it .lint-staged-pre-commit.json

```
{
    "*.{ts,tsx,scss}": ["prettier --check"],
    "*.{ts,tsx}": ["eslint --ignore-path .eslintignore"]
}
"scripts": {
    "lint-staged-pre-commit": "lint-staged --config .lint-staged-pre-commit.json"
},
"husky": {
    "hooks": {
        "pre-commit": "npm run lint-staged-pre-commit"
    }
}
```

The above code runs whenever you try to commit something and verify the prettier and lint and if those commands run successfully it will create a commit else will fail.

So no more bad formatted code in your repos.

> Bonus setup for pre-push which should run on files of commits which are not pushed to origin.

create another json file for pre-push .lint-staged-pre-push.json

```
{
    "*.{ts,tsx,js}": ["jest --bail --findRelatedTests"]
}
"scripts": {
    "lint-staged-pre-push": "lint-staged --diff=$(git log HEAD --not --remotes --pretty=format:'%h' | tail -1) --config .lint-staged-pre-push.json && jest --bail --findRelatedTests $(echo $(git show --pretty='format:' --name-only $(git log HEAD --not --remotes --pretty=format:'%h' | tail -1)) 'package.json' | xargs)"
},
"husky": {
    "hooks": {
        "pre-push": "cross-env CI=true npm run lint-staged-pre-push"
    }
}
```

There is a big lengthy command let's understand what it does.
and i will divide that command into two parts.

`lint-staged --diff=$(git log HEAD --not --remotes --pretty=format:'%h' | tail -1) --config .lint-staged-pre-push.json`

This command will run on commits which are from Head to last commit which is not pushed to origin.

Then why we need other command, the catch here is it only runs till last commit(here last commit refers to the one which is not pushed to origin) and will not include the last commit.

so we have to run the tests for last commit using jest.

`jest --bail --findRelatedTests $(echo $(git show --pretty='format:' --name-only $(git log HEAD --not --remotes --pretty=format:'%h' | tail -1)) 'package.json' | xargs)`

This will run tests for last commit but by default adding package.json to the list why?

Because jest will break if no files are found for _--findRelatedTests_ (it will happen in case of merge commits), so manually adding one file to make sure jest doesn't break.


Beyond just linting, testing, formatting, you can leverage this approach to stream line any other preprocessing tasks before committing or pushing code.

Hope you like this content, we can connect over linkedin

> https://www.linkedin.com/in/saiteja2145/
Thanks, Sai Teja

#frontend #frontendDevelopment #git #husky #lint #format #test #jest
#webDevelopment #git-hooks #changedFiles #DevelopmentTips #DevelopmentWorkflow