Lint Staged Git Add Found Some Errors Please Fix Them and Try Committing Again
🚫 💩 lint-staged
Run linters against staged git files and don't let
Why
Linting makes more than sense when run earlier committing your code. Past doing so you can ensure no errors go into the repository and enforce code style. Merely running a lint process on a whole project is boring, and linting results tin can be irrelevant. Ultimately you lot but desire to lint files that will exist committed.
This project contains a script that will run capricious beat tasks with a list of staged files equally an argument, filtered by a specified glob pattern.
Related blog posts and talks
- Introductory Medium mail service - Andrey Okonetchnikov, 2016
- Running Jest Tests Before Each Git Commit - Ben McCormick, 2017
- AgentConf presentation - Andrey Okonetchnikov, 2018
- SurviveJS interview - Juho Vepsäläinen and Andrey Okonetchnikov, 2018
- Prettier your CSharp with
dotnet-format
andlint-staged
If you've written one, please submit a PR with the link to information technology!
Installation and setup
The fastest way to start using lint-staged is to run the following control in your final:
This command will install and configure husky and lint-staged depending on the code quality tools from your projection's package.json
dependencies, so delight make certain you install (npm install --relieve-dev
) and configure all lawmaking quality tools similar Prettier and ESLint prior to that.
Don't forget to commit changes to packet.json
and .croaking
to share this setup with your squad!
Now change a few files, git add
or git add together --patch
some of them to your commit, and attempt to git commit
them.
Run into examples and configuration for more information.
Changelog
See Releases.
Migration
v12
- Since
v12.0.0
lint-staged is a pure ESM module, so make certain your Node.js version is at least12.20.0
,14.13.ane
, or16.0.0
. Read more about ESM modules from the official Node.js Documentation site hither.
v10
- From
v10.0.0
onwards whatsoever new modifications to originally staged files will exist automatically added to the commit. If your task previously independent agit add together
footstep, please remove this. The automated behaviour ensures there are less race-conditions, since trying to run multiple git operations at the same time usually results in an error. - From
v10.0.0
onwards, lint-staged uses git stashes to better speed and provide backups while running. Since git stashes crave at least an initial commit, you shouldn't run lint-staged in an empty repo. - From
v10.0.0
onwards, lint-staged requires Node.js version x.xiii.0 or subsequently. - From
v10.0.0
onwards, lint-staged will abort the commit if linter tasks undo all staged changes. To permit creating an empty commit, please apply the--let-empty
option.
Command line flags
❯ npx lint-staged --help Usage: lint-staged [options] Options: -V, --version output the version number --allow-empty allow empty commits when tasks revert all staged changes (default: false) -c, --config [path] path to configuration file, or - to read from stdin -d, --debug print additional debug information (default: simulated) --no-stash disable the backup stash, and do not revert in example of errors -p, --concurrent <parallel tasks> the number of tasks to run concurrently, or false to run tasks serially (default: true) -q, --quiet disable lint-staged's own console output (default: fake) -r, --relative pass relative filepaths to tasks (default: false) -x, --shell [path] skip parsing of tasks for better shell back up (default: false) -v, --verbose show task output even when tasks succeed; by default only failed output is shown (default: false) -h, --assistance display assist for command
-
--allow-empty
: By default, when linter tasks undo all staged changes, lint-staged will go out with an error and arrest the commit. Utilize this flag to allow creating empty git commits. -
--config [path]
: Manually specify a path to a config file or npm parcel proper noun. Note: when used, lint-staged won't perform the config file search and volition impress an mistake if the specified file cannot exist institute. If '-' is provided as the filename then the config will be read from stdin, allowing pipage in the config similarcat my-config.json | npx lint-staged --config -
. -
--debug
: Run in debug mode. When prepare, it does the post-obit:- uses debug internally to log boosted data near staged files, commands being executed, location of binaries, etc. Debug logs, which are automatically enabled by passing the flag, tin also exist enabled by setting the surround variable
$DEBUG
tolint-staged*
. - uses
verbose
renderer forlistr
; this causes serial, uncoloured output to the terminal, instead of the default (beautified, dynamic) output.
- uses debug internally to log boosted data near staged files, commands being executed, location of binaries, etc. Debug logs, which are automatically enabled by passing the flag, tin also exist enabled by setting the surround variable
-
--concurrent [number | (true/false)]
: Controls the concurrency of tasks being run by lint-staged. NOTE: This does NOT touch on the concurrency of subtasks (they will e'er be run sequentially). Possible values are:-
faux
: Run all tasks serially -
true
(default) : Infinite concurrency. Runs as many tasks in parallel every bit possible. -
{number}
: Run the specified number of tasks in parallel, whereone
is equivalent tofalse
.
-
-
--no-stash
: By default a backup stash will exist created before running the tasks, and all task modifications will be reverted in case of an error. This option will disable creating the stash, and instead leave all modifications in the index when aborting the commit. -
--quiet
: Supress all CLI output, except from tasks. -
--relative
: Pass filepaths relative toprocedure.cwd()
(wherelint-staged
runs) to tasks. Default isimitation
. -
--shell
: By default linter commands volition be parsed for speed and security. This has the side-effect that regular shell scripts might not work as expected. You lot tin skip parsing of commands with this option. To use a specific beat out, use a path like--shell "/bin/bash"
. -
--verbose
: Show task output even when tasks succeed. By default but failed output is shown.
Configuration
Starting with v3.ane you can at present use different means of configuring lint-staged:
-
lint-staged
object in yourpackage.json
-
.lintstagedrc
file in JSON or YML format, or you tin be explicit with the file extension:-
.lintstagedrc.json
-
.lintstagedrc.yaml
-
.lintstagedrc.yml
-
-
.lintstagedrc.mjs
orlint-staged.config.mjs
file in ESM format- the default export value should be a configuration:
export default { ... }
- the default export value should be a configuration:
-
.lintstagedrc.cjs
orlint-staged.config.cjs
file in CommonJS format- the exports value should be a configuration:
module.exports = { ... }
- the exports value should be a configuration:
-
lint-staged.config.js
or.lintstagedrc.js
in either ESM or CommonJS format, depending on whether your project's package.json contains the"type": "module"
option or not. - Pass a configuration file using the
--config
or-c
flag
Configuration should be an object where each value is a command to run and its primal is a glob pattern to employ for this control. This package uses micromatch for glob patterns. JavaScript files can besides export advanced configuration as a function. Encounter Using JS configuration files for more info.
package.json
instance:
{ "lint-staged": { "*": "your-cmd" } }
.lintstagedrc
case
This config will execute your-cmd
with the list of currently staged files passed as arguments.
So, considering you did git add file1.ext file2.ext
, lint-staged will run the following command:
your-cmd file1.ext file2.ext
Filtering files
Linter commands piece of work on a subset of all staged files, defined by a glob design. lint-staged uses micromatch for matching files with the following rules:
- If the glob design contains no slashes (
/
), micromatch'smatchBase
option will enabled, and so globs friction match a file's basename regardless of directory:-
"*.js"
will match all JS files, like/exam.js
and/foo/bar/examination.js
-
"!(*test).js"
. will match all JS files, except those ending intest.js
, and sofoo.js
but nonfoo.test.js
-
- If the glob pattern does contain a slash (
/
), information technology will friction match for paths as well:-
"./*.js"
will friction match all JS files in the git repo root, and so/test.js
just not/foo/bar/examination.js
-
"foo/**/\*.js"
will match all JS files within the/foo
directory, so/foo/bar/test.js
but not/test.js
-
When matching, lint-staged will practice the post-obit
- Resolve the git root automatically, no configuration needed.
- Option the staged files which are nowadays inside the project directory.
- Filter them using the specified glob patterns.
- Pass absolute paths to the linters as arguments.
Annotation: lint-staged
will laissez passer accented paths to the linters to avoid whatever confusion in case they're executed in a different working directory (i.due east. when your .git
directory isn't the same as your package.json
directory).
Too come across How to use lint-staged
in a multi-package monorepo?
Ignoring files
The concept of lint-staged
is to run configured linter tasks (or other tasks) on files that are staged in git. lint-staged
will e'er pass a list of all staged files to the task, and ignoring any files should be configured in the chore itself.
Consider a project that uses prettier
to keep code format consequent across all files. The project too stores minified 3rd-party vendor libraries in the vendor/
directory. To keep prettier
from throwing errors on these files, the vendor directory should exist added to prettier'south ignore configuration, the .prettierignore
file. Running npx prettier .
volition ignore the entire vendor directory, throwing no errors. When lint-staged
is added to the project and configured to run prettier, all modified and staged files in the vendor directory will be ignored by prettier, even though it receives them equally input.
In advanced scenarios, where it is impossible to configure the linter job itself to ignore files, but some staged files should still exist ignored by lint-staged
, it is possible to filter filepaths before passing them to tasks by using the office syntax. Run across Instance: Ignore files from match.
What commands are supported?
Supported are any executables installed locally or globally via npm
besides as any executable from your $PATH.
Using globally installed scripts is discouraged, since lint-staged may not work for someone who doesn't have it installed.
lint-staged
uses execa to locate locally installed scripts. So in your .lintstagedrc
yous can write:
{ "*.js": "eslint --fix" }
Pass arguments to your commands separated past space equally you would do in the vanquish. Run across examples below.
Running multiple commands in a sequence
You can run multiple commands in a sequence on every glob. To do then, pass an assortment of commands instead of a single one. This is useful for running autoformatting tools like eslint --prepare
or stylefmt
just tin can be used for whatsoever arbitrary sequences.
For example:
{ "*.js": [ "eslint" , "prettier --write" ] }
going to execute eslint
and if it exits with 0
code, it will execute prettier --write
on all staged *.js
files.
Using JS configuration files
Writing the configuration file in JavaScript is the most powerful way to configure lint-staged (lint-staged.config.js
, similar, or passed via --config
). From the configuration file, you tin can export either a unmarried function or an object.
If the exports
value is a role, information technology will receive an array of all staged filenames. Y'all tin can then build your own matchers for the files and return a command string or an assortment of command strings. These strings are considered complete and should include the filename arguments, if wanted.
If the exports
value is an object, its keys should be glob matches (like in the normal non-js config format). The values can either be like in the normal config or individual functions like described above. Instead of receiving all matched files, the functions in the exported object will only receive the staged files matching the corresponding glob key.
Function signature
The part can also be async:
( filenames: string [ ] ) => cord | string [ ] | Promise < string | string [ ] >
Instance: Consign a office to build your ain matchers
Click to expand
// lint-staged.config.js import micromatch from 'micromatch' export default ( allStagedFiles ) => { const shFiles = micromatch ( allStagedFiles , [ '**/src/**/*.sh' ] ) if ( shFiles . length ) { return `printf '%southward\n' "Script files aren't immune in src directory" >&2` } const codeFiles = micromatch ( allStagedFiles , [ '**/*.js' , '**/*.ts' ] ) const docFiles = micromatch ( allStagedFiles , [ '**/*.md' ] ) return [ `eslint ${ codeFiles . join ( ' ' ) } ` , `mdl ${ docFiles . join ( ' ' ) } ` ] }
Example: Wrap filenames in unmarried quotes and run one time per file
Click to expand
// .lintstagedrc.js consign default { '**/*.js?(x)': ( filenames ) => filenames . map ( ( filename ) => `prettier --write ' ${ filename } '` ) , }
Example: Run tsc
on changes to TypeScript files, just practice not pass any filename arguments
Click to aggrandize
// lint-staged.config.js export default { '**/*.ts?(x)': ( ) => 'tsc -p tsconfig.json --noEmit' , }
Example: Run ESLint on entire repo if more than 10 staged files
Click to aggrandize
// .lintstagedrc.js export default { '**/*.js?(10)': ( filenames ) => filenames . length > x ? 'eslint .' : `eslint ${ filenames . bring together ( ' ' ) } ` , }
Example: Apply your own globs
Click to expand
It'southward better to utilise the function-based configuration (seen above), if your employ case is this.
// lint-staged.config.js import micromatch from 'micromatch' consign default { '*': ( allFiles ) => { const codeFiles = micromatch ( allFiles , [ '**/*.js' , '**/*.ts' ] ) const docFiles = micromatch ( allFiles , [ '**/*.dr.' ] ) return [ `eslint ${ codeFiles . bring together ( ' ' ) } ` , `mdl ${ docFiles . join ( ' ' ) } ` ] } , }
Example: Ignore files from lucifer
Click to expand
If for some reason you want to ignore files from the glob match, y'all can use micromatch.not()
:
// lint-staged.config.js import micromatch from 'micromatch' export default { '*.js': ( files ) => { // from `files` filter those _NOT_ matching `*exam.js` const lucifer = micromatch . not ( files , '*exam.js' ) return `eslint ${ match . join ( ' ' ) } ` } , }
Please note that for virtually cases, globs can reach the same consequence. For the higher up example, a matching glob would be !(*test).js
.
Instance: Use relative paths for commands
Click to expand
import path from 'path' export default { '*.ts': ( absolutePaths ) => { const cwd = process . cwd ( ) const relativePaths = absolutePaths . map ( ( file ) => path . relative ( cwd , file ) ) render `ng lint myProjectName --files ${ relativePaths . join ( ' ' ) } ` } , }
Reformatting the code
Tools like Prettier, ESLint/TSLint, or stylelint can reformat your lawmaking according to an appropriate config by running prettier --write
/eslint --fix
/tslint --fix
/stylelint --gear up
. Lint-staged will automatically add together whatever modifications to the commit equally long equally there are no errors.
{ "*.js": "prettier --write" }
Prior to version 10, tasks had to manually include git add
as the terminal step. This beliefs has been integrated into lint-staged itself in gild to foreclose race conditions with multiple tasks editing the same files. If lint-staged detects git add together
in task configurations, it will show a warning in the console. Please remove git add
from your configuration after upgrading.
Examples
All examples assume you lot've already set lint-staged in the package.json
file and husky in its own config file.
{ "proper noun": "My projection" , "version": "0.one.0" , "scripts": { "my-custom-script": "linter --arg1 --arg2" }, "lint-staged": {} }
In .husky/pre-commit
#!/usr/bin/env sh . " $(dirname " $0 " ) /_/husky.sh" npx lint-staged
Note: nosotros don't pass a path equally an argument for the runners. This is of import since lint-staged will do this for you.
ESLint with default parameters for *.js
and *.jsx
running as a pre-commit hook
Click to expand
{ "*.{js,jsx}": "eslint" }
Automatically fix code style with --fix
and add together to commit
Click to aggrandize
{ "*.js": "eslint --set up" }
This will run eslint --fix
and automatically add changes to the commit.
Reuse npm script
Click to expand
If you wish to reuse a npm script defined in your parcel.json:
{ "*.js": "npm run my-custom-script --" }
The following is equivalent:
{ "*.js": "linter --arg1 --arg2" }
Use environment variables with linting commands
Click to expand
Linting commands do not support the shell convention of expanding environment variables. To enable the convention yourself, use a tool similar cantankerous-env
.
For example, here is jest
running on all .js
files with the NODE_ENV
variable being set to "test"
:
{ "*.js": [ "cross-env NODE_ENV=exam jest --bail --findRelatedTests" ] }
Automatically fix code manner with prettier
for whatever format Prettier supports
Click to expand
{ "*": "prettier --ignore-unknown --write" }
Automatically fix code style with prettier
for JavaScript, TypeScript, Markdown, HTML, or CSS
Click to aggrandize
{ "*.{js,jsx,ts,tsx,md,html,css}": "prettier --write" }
Stylelint for CSS with defaults and for SCSS with SCSS syntax
Click to expand
{ "*.css": "stylelint" , "*.scss": "stylelint --syntax=scss" }
Run PostCSS sorting and Stylelint to check
Click to aggrandize
{ "*.scss": [ "postcss --config path/to/your/config --replace" , "stylelint" ] }
Minify the images
Click to expand
{ "*.{png,jpeg,jpg,gif,svg}": "imagemin-lint-staged" }
More about imagemin-lint-staged
imagemin-lint-staged is a CLI tool designed for lint-staged usage with sensible defaults.
Run into more on this blog mail service for benefits of this approach.
Typecheck your staged files with catamenia
Click to expand
{ "*.{js,jsx}": "catamenia focus-check" }
Oftentimes Asked Questions
Can I use lint-staged
via node?
Click to expand
Yes!
import lintStaged from 'lint-staged' try { const success = wait lintStaged ( ) console . log ( success ? 'Linting was successful!' : 'Linting failed!' ) } catch ( eastward ) { // Failed to load configuration console . error ( eastward ) }
Parameters to lintStaged
are equivalent to their CLI counterparts:
const success = wait lintStaged ( { allowEmpty: false , concurrent: true , configPath: './path/to/configuration/file' , cwd: process . cwd ( ) , debug: false , maxArgLength: zip , quiet: false , relative: simulated , crush: fake stash: true , verbose: faux } )
You can also pass config directly with config
option:
const success = look lintStaged ( { allowEmpty: false , concurrent: truthful , config: { '*.js': 'eslint --fix' } , cwd: process . cwd ( ) , debug: false , maxArgLength: null , quiet: false , relative: false , beat: simulated , stash: truthful , verbose: fake , } )
The maxArgLength
option configures chunking of tasks into multiple parts that are run ane afterwards the other. This is to avoid issues on Windows platforms where the maximum length of the command line argument string is express to 8192 characters. Lint-staged might generate a very long argument string when there are many staged files. This option is ready automatically from the cli, simply non via the Node.js API by default.
Using with JetBrains IDEs (WebStorm, PyCharm, IntelliJ Idea, RubyMine, etc.)
Click to expand
Update : The latest version of JetBrains IDEs now support running hooks as y'all would expect.
When using the IDE's GUI to commit changes with the precommit
claw, you might see inconsistencies in the IDE and command line. This is known outcome at JetBrains so if yous want this stock-still, please vote for it on YouTrack.
Until the issue is resolved in the IDE, you tin employ the following config to work effectually it:
husky v1.10
{ "croaking": { "hooks": { "pre-commit": "lint-staged" , "mail-commit": "git update-index --again" } } }
husky v0.x
{ "scripts": { "precommit": "lint-staged" , "postcommit": "git update-index --once again" } }
Thanks to this comment for the fix!
How to use lint-staged
in a multi-package monorepo?
Click to expand
Starting with v5.0, lint-staged
automatically resolves the git root without any additional configuration. You configure lint-staged
equally you lot commonly would if your project root and git root were the aforementioned directory.
If you wish to utilise lint-staged
in a multi packet monorepo, it is recommended to install husky
in the root package.json. lerna
can exist used to execute the precommit
script in all sub-packages.
Example repo: sudo-suhas/lint-staged-multi-pkg.
Tin can I lint files outside of the current projection binder?
Click to aggrandize
tl;dr: Yes, but the pattern should start with ../
.
Past default, lint-staged
executes linters only on the files present within the project binder(where lint-staged
is installed and run from). So this question is relevant only when the project folder is a child folder within the git repo. In certain projection setups, it might be desirable to bypass this brake. See #425, #487 for more context.
lint-staged
provides an escape hatch for the same(>= v7.3.0
). For patterns that start with ../
, all the staged files are allowed to lucifer against the pattern. Note that patterns like *.js
, **/*.js
volition notwithstanding but friction match the project files and not any of the files in parent or sibling directories.
Example repo: sudo-suhas/lint-staged-django-react-demo.
How tin can I ignore files from .eslintignore
?
Click to aggrandize
ESLint throws out warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override
warnings that breaks the linting process ( if you used --max-warnings=0
which is recommended ).
ESLint < 7
Click to expand
Based on the give-and-take from this issue, it was decided that using the outlined script is the best route to fix this.
And so you can setup a .lintstagedrc.js
config file to practise this:
import { CLIEngine } from 'eslint' export default { '*.js': ( files ) => { const cli = new CLIEngine ( { } ) render 'eslint --max-warnings=0 ' + files . filter ( ( file ) => ! cli . isPathIgnored ( file ) ) . join ( ' ' ) } , }
ESLint >= seven
Click to expand
In versions of ESLint > seven, isPathIgnored is an async function and now returns a promise. The code beneath tin can be used to reinstate the above functionality.
Since 10.5.3, any errors due to a bad ESLint config volition come through to the console.
import { ESLint } from 'eslint' const removeIgnoredFiles = async ( files ) => { const eslint = new ESLint ( ) const isIgnored = expect Promise . all ( files . map ( ( file ) => { return eslint . isPathIgnored ( file ) } ) ) const filteredFiles = files . filter ( ( _ , i ) => ! isIgnored [ i ] ) render filteredFiles . join ( ' ' ) } consign default { '**/*.{ts,tsx,js,jsx}': async ( files ) => { const filesToLint = expect removeIgnoredFiles ( files ) return [ `eslint --max-warnings=0 ${ filesToLint } ` ] } , }
Source: https://www.npmjs.com/package/lint-staged/v/12.1.6
0 Response to "Lint Staged Git Add Found Some Errors Please Fix Them and Try Committing Again"
Post a Comment