Giter VIP home page Giter VIP logo

lint-staged's Introduction

🚫💩 lint-staged Test & Release Publish npm version Codecov

Run linters against staged git files and don't let 💩 slip into your code base!

npm install --save-dev lint-staged # requires further setup
$ git commit

✔ Preparing lint-staged...
❯ Running tasks for staged files...
  ❯ packages/frontend/.lintstagedrc.json — 1 file
    ↓ *.js — no files [SKIPPED]
    ❯ *.{json,md} — 1 file
      ⠹ prettier --write
  ↓ packages/backend/.lintstagedrc.json — 2 files
    ❯ *.js — 2 files
      ⠼ eslint --fix
    ↓ *.{json,md} — no files [SKIPPED]
◼ Applying modifications from tasks...
◼ Cleaning up temporary files...
See asciinema video

asciicast

Why

Linting makes more sense when run before committing your code. By doing so you can ensure no errors go into the repository and enforce code style. But running a lint process on a whole project is slow, and linting results can be irrelevant. Ultimately you only want to lint files that will be committed.

This project contains a script that will run arbitrary shell tasks with a list of staged files as an argument, filtered by a specified glob pattern.

Related blog posts and talks

If you've written one, please submit a PR with the link to it!

Installation and setup

To install lint-staged in the recommended way, you need to:

  1. Install lint-staged itself:
    • npm install --save-dev lint-staged
  2. Set up the pre-commit git hook to run lint-staged
    • Husky is a popular choice for configuring git hooks
    • Read more about git hooks here
  3. Install some linters, like ESLint or Prettier
  4. Configure lint-staged to run linters and other tasks:
    • for example: { "*.js": "eslint" } to run ESLint for all staged JS files
    • See Configuration for more info

Don't forget to commit changes to package.json and .husky to share this setup with your team!

Now change a few files, git add or git add --patch some of them to your commit, and try to git commit them.

See examples and configuration for more information.

Changelog

See Releases.

Migration

v15

  • Since v15.0.0 lint-staged no longer supports Node.js 16. Please upgrade your Node.js version to at least 18.12.0.

v14

  • Since v14.0.0 lint-staged no longer supports Node.js 14. Please upgrade your Node.js version to at least 16.14.0.

v13

  • Since v13.0.0 lint-staged no longer supports Node.js 12. Please upgrade your Node.js version to at least 14.13.1, or 16.0.0 onward.
  • Version v13.3.0 was incorrectly released including code of version v14.0.0. This means the breaking changes of v14 are also included in v13.3.0, the last v13 version released

v12

  • Since v12.0.0 lint-staged is a pure ESM module, so make sure your Node.js version is at least 12.20.0, 14.13.1, or 16.0.0. Read more about ESM modules from the official Node.js Documentation site here.

v10

  • From v10.0.0 onwards any new modifications to originally staged files will be automatically added to the commit. If your task previously contained a git add step, please remove this. The automatic 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 improve speed and provide backups while running. Since git stashes require 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 10.13.0 or later.
  • From v10.0.0 onwards, lint-staged will abort the commit if linter tasks undo all staged changes. To allow creating an empty commit, please use the --allow-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)
  -p, --concurrent <number|boolean>  the number of tasks to run concurrently, or false for serial (default: true)
  -c, --config [path]                path to configuration file, or - to read from stdin
  --cwd [path]                       run all tasks in specific directory, instead of the current
  -d, --debug                        print additional debug information (default: false)
  --diff [string]                    override the default "--staged" flag of "git diff" to get list of files. Implies
                                     "--no-stash".
  --diff-filter [string]             override the default "--diff-filter=ACMR" flag of "git diff" to get list of files
  --max-arg-length [number]          maximum length of the command-line argument string (default: 0)
  --no-stash                         disable the backup stash, and do not revert in case of errors. Implies
                                     "--no-hide-partially-staged".
  --no-hide-partially-staged         disable hiding unstaged changes from partially staged files
  -q, --quiet                        disable lint-staged’s own console output (default: false)
  -r, --relative                     pass relative filepaths to tasks (default: false)
  -x, --shell [path]                 skip parsing of tasks for better shell support (default: false)
  -v, --verbose                      show task output even when tasks succeed; by default only failed output is shown
                                     (default: false)
  -h, --help                         display help for command
  • --allow-empty: By default, when linter tasks undo all staged changes, lint-staged will exit with an error and abort the commit. Use this flag to allow creating empty git commits.
  • --concurrent [number|boolean]: Controls the concurrency of tasks being run by lint-staged. NOTE: This does NOT affect the concurrency of subtasks (they will always be run sequentially). Possible values are:
    • false: Run all tasks serially
    • true (default) : Infinite concurrency. Runs as many tasks in parallel as possible.
    • {number}: Run the specified number of tasks in parallel, where 1 is equivalent to false.
  • --config [path]: Manually specify a path to a config file or npm package name. Note: when used, lint-staged won't perform the config file search and will print an error if the specified file cannot be found. If '-' is provided as the filename then the config will be read from stdin, allowing piping in the config like cat my-config.json | npx lint-staged --config -.
  • --cwd [path]: By default tasks run in the current working directory. Use the --cwd some/directory to override this. The path can be absolute or relative to the current working directory.
  • --debug: Run in debug mode. When set, it does the following:
    • uses debug internally to log additional information about staged files, commands being executed, location of binaries, etc. Debug logs, which are automatically enabled by passing the flag, can also be enabled by setting the environment variable $DEBUG to lint-staged*.
    • uses verbose renderer for listr2; this causes serial, uncoloured output to the terminal, instead of the default (beautified, dynamic) output. (the verbose renderer can also be activated by setting the TERM=dumb or NODE_ENV=test environment variables)
  • --diff: By default linters are filtered against all files staged in git, generated from git diff --staged. This option allows you to override the --staged flag with arbitrary revisions. For example to get a list of changed files between two branches, use --diff="branch1...branch2". You can also read more from about git diff and gitrevisions. This option also implies --no-stash.
  • --diff-filter: By default only files that are added, copied, modified, or renamed are included. Use this flag to override the default ACMR value with something else: added (A), copied (C), deleted (D), modified (M), renamed (R), type changed (T), unmerged (U), unknown (X), or pairing broken (B). See also the git diff docs for --diff-filter.
  • --max-arg-length: long commands (a lot of files) are automatically split into multiple chunks when it detects the current shell cannot handle them. Use this flag to override the maximum length of the generated command string.
  • --no-stash: By default a backup stash will be 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. Can be re-enabled with --stash. This option also implies --no-hide-partially-staged.
  • --no-hide-partially-staged: By default, unstaged changes from partially staged files will be hidden. This option will disable this behavior and include all unstaged changes in partially staged files. Can be re-enabled with --hide-partially-staged
  • --quiet: Supress all CLI output, except from tasks.
  • --relative: Pass filepaths relative to process.cwd() (where lint-staged runs) to tasks. Default is false.
  • --shell: By default linter commands will be parsed for speed and security. This has the side-effect that regular shell scripts might not work as expected. You can skip parsing of commands with this option. To use a specific shell, use a path like --shell "/bin/bash".
  • --verbose: Show task output even when tasks succeed. By default only failed output is shown.

Configuration

Lint-staged can be configured in many ways:

  • lint-staged object in your package.json, or package.yaml
  • .lintstagedrc file in JSON or YML format, or you can be explicit with the file extension:
    • .lintstagedrc.json
    • .lintstagedrc.yaml
    • .lintstagedrc.yml
  • .lintstagedrc.mjs or lint-staged.config.mjs file in ESM format
    • the default export value should be a configuration: export default { ... }
  • .lintstagedrc.cjs or lint-staged.config.cjs file in CommonJS format
    • the exports value should be a configuration: module.exports = { ... }
  • 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 key is a glob pattern to use for this command. This package uses micromatch for glob patterns. JavaScript files can also export advanced configuration as a function. See Using JS configuration files for more info.

You can also place multiple configuration files in different directories inside a project. For a given staged file, the closest configuration file will always be used. See "How to use lint-staged in a multi-package monorepo?" for more info and an example.

package.json example:

{
  "lint-staged": {
    "*": "your-cmd"
  }
}

.lintstagedrc example

{
  "*": "your-cmd"
}

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

Task concurrency

By default lint-staged will run configured tasks concurrently. This means that for every glob, all the commands will be started at the same time. With the following config, both eslint and prettier will run at the same time:

{
  "*.ts": "eslint",
  "*.md": "prettier --list-different"
}

This is typically not a problem since the globs do not overlap, and the commands do not make changes to the files, but only report possible errors (aborting the git commit). If you want to run multiple commands for the same set of files, you can use the array syntax to make sure commands are run in order. In the following example, prettier will run for both globs, and in addition eslint will run for *.ts files after it. Both sets of commands (for each glob) are still started at the same time (but do not overlap).

{
  "*.ts": ["prettier --list-different", "eslint"],
  "*.md": "prettier --list-different"
}

Pay extra attention when the configured globs overlap, and tasks make edits to files. For example, in this configuration prettier and eslint might try to make changes to the same *.ts file at the same time, causing a race condition:

{
  "*": "prettier --write",
  "*.ts": "eslint --fix"
}

You can solve it using the negation pattern and the array syntax:

{
  "!(*.ts)": "prettier --write",
  "*.ts": ["eslint --fix", "prettier --write"]
}

Another example in which tasks make edits to files and globs match multiple files but don't overlap:

{
  "*.css": [
    "stylelint --fix",
    "prettier --write"
  ],
  "*.{js,jsx}": [
    "eslint --fix",
    "prettier --write"
  ],
  "!(*.css|*.js|*.jsx)": [
    "prettier --write"
  ]
}

Or, if necessary, you can limit the concurrency using --concurrent <number> or disable it entirely with --concurrent false.

Filtering files

Linter commands work on a subset of all staged files, defined by a glob pattern. lint-staged uses micromatch for matching files with the following rules:

  • If the glob pattern contains no slashes (/), micromatch's matchBase option will enabled, so globs match a file's basename regardless of directory:
    • "*.js" will match all JS files, like /test.js and /foo/bar/test.js
    • "!(*test).js" will match all JS files, except those ending in test.js, so foo.js but not foo.test.js
    • "!(*.css|*.js)" will match all files except CSS and JS files
  • If the glob pattern does contain a slash (/), it will match for paths as well:
    • "./*.js" will match all JS files in the git repo root, so /test.js but not /foo/bar/test.js
    • "foo/**/*.js" will match all JS files inside the /foo directory, so /foo/bar/test.js but not /test.js

When matching, lint-staged will do the following

  • Resolve the git root automatically, no configuration needed.
  • Pick the staged files which are present inside the project directory.
  • Filter them using the specified glob patterns.
  • Pass absolute paths to the linters as arguments.

NOTE: lint-staged will pass absolute paths to the linters to avoid any confusion in case they're executed in a different working directory (i.e. when your .git directory isn't the same as your package.json directory).

Also see 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 always pass a list of all staged files to the task, and ignoring any files should be configured in the task itself.

Consider a project that uses prettier to keep code format consistent across all files. The project also stores minified 3rd-party vendor libraries in the vendor/ directory. To keep prettier from throwing errors on these files, the vendor directory should be added to prettier's ignore configuration, the .prettierignore file. Running npx prettier . will 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 as input.

In advanced scenarios, where it is impossible to configure the linter task itself to ignore files, but some staged files should still be ignored by lint-staged, it is possible to filter filepaths before passing them to tasks by using the function syntax. See Example: Ignore files from match.

What commands are supported?

Supported are any executables installed locally or globally via npm as well 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 you can write:

{
  "*.js": "eslint --fix"
}

Pass arguments to your commands separated by space as you would do in the shell. See examples below.

Running multiple commands in a sequence

You can run multiple commands in a sequence on every glob. To do so, pass an array of commands instead of a single one. This is useful for running autoformatting tools like eslint --fix or stylefmt but can be used for any 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 can export either a single function or an object.

If the exports value is a function, it will receive an array of all staged filenames. You can then build your own matchers for the files and return a command string or an array 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 function can also be async:

(filenames: string[]) => string | string[] | Promise<string | string[]>

Example: Export a function to build your own 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 '%s\n' "Script files aren't allowed 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 single quotes and run once per file

Click to expand
// .lintstagedrc.js
export default {
  '**/*.js?(x)': (filenames) => filenames.map((filename) => `prettier --write '${filename}'`),
}

Example: Run tsc on changes to TypeScript files, but do not pass any filename arguments

Click to expand
// 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 expand
// .lintstagedrc.js
export default {
  '**/*.js?(x)': (filenames) =>
    filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}`,
}

Example: Use your own globs

Click to expand

It's better to use the function-based configuration (seen above), if your use case is this.

// lint-staged.config.js
import micromatch from 'micromatch'

export default {
  '*': (allFiles) => {
    const codeFiles = micromatch(allFiles, ['**/*.js', '**/*.ts'])
    const docFiles = micromatch(allFiles, ['**/*.md'])
    return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
  },
}

Example: Ignore files from match

Click to expand

If for some reason you want to ignore files from the glob match, you can use micromatch.not():

// lint-staged.config.js
import micromatch from 'micromatch'

export default {
  '*.js': (files) => {
    // from `files` filter those _NOT_ matching `*test.js`
    const match = micromatch.not(files, '*test.js')
    return `eslint ${match.join(' ')}`
  },
}

Please note that for most cases, globs can achieve the same effect. For the above example, a matching glob would be !(*test).js.

Example: 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))
    return `ng lint myProjectName --files ${relativePaths.join(' ')}`
  },
}

Reformatting the code

Tools like Prettier, ESLint/TSLint, or stylelint can reformat your code according to an appropriate config by running prettier --write/eslint --fix/tslint --fix/stylelint --fix. Lint-staged will automatically add any modifications to the commit as long as there are no errors.

{
  "*.js": "prettier --write"
}

Prior to version 10, tasks had to manually include git add as the final step. This behavior has been integrated into lint-staged itself in order to prevent race conditions with multiple tasks editing the same files. If lint-staged detects git add 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've already set up lint-staged in the package.json file and husky in its own config file.

{
  "name": "My project",
  "version": "0.1.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: we don't pass a path as an argument for the runners. This is important 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 to commit

Click to expand
{
  "*.js": "eslint --fix"
}

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 package.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 like cross-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=test jest --bail --findRelatedTests"]
}

Automatically fix code style with prettier for any 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 expand
{
  "*.{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 expand
{
  "*.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.

See more on this blog post for benefits of this approach.

Typecheck your staged files with flow

Click to expand
{
  "*.{js,jsx}": "flow focus-check"
}

Integrate with Next.js

Click to expand
// .lintstagedrc.js
// See https://nextjs.org/docs/basic-features/eslint#lint-staged for details

const path = require('path')

const buildEslintCommand = (filenames) =>
  `next lint --fix --file ${filenames.map((f) => path.relative(process.cwd(), f)).join(' --file ')}`

module.exports = {
  '*.{js,jsx,ts,tsx}': [buildEslintCommand],
}

Frequently Asked Questions

The output of commit hook looks weird (no colors, duplicate lines, verbose output on Windows, …)

Click to expand

Git 2.36.0 introduced a change to hooks where they were no longer run in the original TTY. This was fixed in 2.37.0:

https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.37.0.txt

  • In Git 2.36 we revamped the way how hooks are invoked. One change that is end-user visible is that the output of a hook is no longer directly connected to the standard output of "git" that spawns the hook, which was noticed post release. This is getting corrected. (merge a082345372 ab/hooks-regression-fix later to maint).

If updating Git doesn't help, you can try to manually redirect the output in your Git hook; for example:

# .husky/pre-commit

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

if sh -c ": >/dev/tty" >/dev/null 2>/dev/null; then exec >/dev/tty 2>&1; fi

npx lint-staged

Source: typicode/husky#968 (comment)

Can I use lint-staged via node?

Click to expand

Yes!

import lintStaged from 'lint-staged'

try {
  const success = await lintStaged()
  console.log(success ? 'Linting was successful!' : 'Linting failed!')
} catch (e) {
  // Failed to load configuration
  console.error(e)
}

Parameters to lintStaged are equivalent to their CLI counterparts:

const success = await lintStaged({
  allowEmpty: false,
  concurrent: true,
  configPath: './path/to/configuration/file',
  cwd: process.cwd(),
  debug: false,
  maxArgLength: null,
  quiet: false,
  relative: false,
  shell: false,
  stash: true,
  verbose: false,
})

You can also pass config directly with config option:

const success = await lintStaged({
  allowEmpty: false,
  concurrent: true,
  config: { '*.js': 'eslint --fix' },
  cwd: process.cwd(),
  debug: false,
  maxArgLength: null,
  quiet: false,
  relative: false,
  shell: false,
  stash: true,
  verbose: false,
})

The maxArgLength option configures chunking of tasks into multiple parts that are run one after the other. This is to avoid issues on Windows platforms where the maximum length of the command line argument string is limited to 8192 characters. Lint-staged might generate a very long argument string when there are many staged files. This option is set automatically from the cli, but not 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 you would expect.

When using the IDE's GUI to commit changes with the precommit hook, you might see inconsistencies in the IDE and command line. This is known issue at JetBrains so if you want this fixed, please vote for it on YouTrack.

Until the issue is resolved in the IDE, you can use the following config to work around it:

husky v1.x

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "post-commit": "git update-index --again"
    }
  }
}

husky v0.x

{
  "scripts": {
    "precommit": "lint-staged",
    "postcommit": "git update-index --again"
  }
}

Thanks to this comment for the fix!

How to use lint-staged in a multi-package monorepo?

Click to expand

Install lint-staged on the monorepo root level, and add separate configuration files in each package. When running, lint-staged will always use the configuration closest to a staged file, so having separate configuration files makes sure linters do not "leak" into other packages.

For example, in a monorepo with packages/frontend/.lintstagedrc.json and packages/backend/.lintstagedrc.json, a staged file inside packages/frontend/ will only match that configuration, and not the one in packages/backend/.

Note: lint-staged discovers the closest configuration to each staged file, even if that configuration doesn't include any matching globs. Given these example configurations:

// ./.lintstagedrc.json
{ "*.md": "prettier --write" }
// ./packages/frontend/.lintstagedrc.json
{ "*.js": "eslint --fix" }

When committing ./packages/frontend/README.md, it will not run prettier, because the configuration in the frontend/ directory is closer to the file and doesn't include it. You should treat all lint-staged configuration files as isolated and separated from each other. You can always use JS files to "extend" configurations, for example:

import baseConfig from '../.lintstagedrc.js'

export default {
  ...baseConfig,
  '*.js': 'eslint --fix',
}

To support backwards-compatibility, monorepo features require multiple lint-staged configuration files present in the git repo. If you still want to run lint-staged in only one of the packages in a monorepo, you can either add an "empty" lint-staged configuration to the root of the repo (so that there's two configs in total), or alternatively run lint-staged with the --cwd option pointing to your package directory (for example, lint-staged --cwd packages/frontend).

Can I lint files outside of the current project folder?

Click to expand

tl;dr: Yes, but the pattern should start with ../.

By default, lint-staged executes linters only on the files present inside the project folder(where lint-staged is installed and run from). So this question is relevant only when the project folder is a child folder inside the git repo. In certain project setups, it might be desirable to bypass this restriction. 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 match against the pattern. Note that patterns like *.js, **/*.js will still only match the project files and not any of the files in parent or sibling directories.

Example repo: sudo-suhas/lint-staged-django-react-demo.

Can I run lint-staged in CI, or when there are no staged files?

Click to expand

Lint-staged will by default run against files staged in git, and should be run during the git pre-commit hook, for example. It's also possible to override this default behaviour and run against files in a specific diff, for example all changed files between two different branches. If you want to run lint-staged in the CI, maybe you can set it up to compare the branch in a Pull Request/Merge Request to the target branch.

Try out the git diff command until you are satisfied with the result, for example:

git diff --diff-filter=ACMR --name-only master...my-branch

This will print a list of added, changed, modified, and renamed files between master and my-branch.

You can then run lint-staged against the same files with:

npx lint-staged --diff="master...my-branch"

Can I use lint-staged with ng lint

Click to expand

You should not use ng lint through lint-staged, because it's designed to lint an entire project. Instead, you can add ng lint to your git pre-commit hook the same way as you would run lint-staged.

See issue !951 for more details and possible workarounds.

How can I ignore files from .eslintignore?

Click to expand

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 discussion from this issue, it was decided that using the outlined scriptis the best route to fix this.

So you can setup a .lintstagedrc.js config file to do this:

import { CLIEngine } from 'eslint'

export default {
  '*.js': (files) => {
    const cli = new CLIEngine({})
    return 'eslint --max-warnings=0 ' + files.filter((file) => !cli.isPathIgnored(file)).join(' ')
  },
}

ESLint >= 7

Click to expand

In versions of ESLint > 7, isPathIgnored is an async function and now returns a promise. The code below can be used to reinstate the above functionality.

Since 10.5.3, any errors due to a bad ESLint config will come through to the console.

import { ESLint } from 'eslint'

const removeIgnoredFiles = async (files) => {
  const eslint = new ESLint()
  const isIgnored = await Promise.all(
    files.map((file) => {
      return eslint.isPathIgnored(file)
    })
  )
  const filteredFiles = files.filter((_, i) => !isIgnored[i])
  return filteredFiles.join(' ')
}

export default {
  '**/*.{ts,tsx,js,jsx}': async (files) => {
    const filesToLint = await removeIgnoredFiles(files)
    return [`eslint --max-warnings=0 ${filesToLint}`]
  },
}

ESLint >= 8.51.0 && Flat ESLint config

Click to expand

ESLint v8.51.0 introduced --no-warn-ignored CLI flag. It suppresses the warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override warning, so manually ignoring files via eslint.isPathIgnored is no longer necessary.

{
  "*.js": "eslint --max-warnings=0 --no-warn-ignored"
}

NOTE: --no-warn-ignored flag is only available when Flat ESLint config is used.

lint-staged's People

Contributors

ai avatar albertjan avatar cameronhunter avatar dependabot[bot] avatar fezvrasta avatar github-actions[bot] avatar greenkeeper[bot] avatar greenkeeperio-bot avatar iiroj avatar jamesgeorge007 avatar johnnyreilly avatar johnnywalker avatar lildeadprince avatar luftywiranda13 avatar mojodna avatar mrrefactoring avatar okonet avatar plroebuck avatar rodneyrehm avatar rvetere avatar s-h-a-d-o-w avatar sachinshekhar avatar sapegin avatar simenb avatar sudo-suhas avatar thewolfnl avatar tjenkinson avatar tkalmar avatar typicode avatar ybiquitous avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lint-staged's Issues

Wrong path with gitDir

My config is located in front/package.json and contains:

    "gitDir": "../",
    "*.sss": [
      "stylelint",
      "node ./front/postcss/sort",
      "git add"
    ],
    "*.js": "eslint"

If I was staged front/a.js file, lint-stage will execute front/node_modules/.bin/eslint a.js. There is no front/ in file path.

Maybe we should use absolute path there?

Linting throws npm error because linter returns with non-zero status

When running npm run lint-staged npm throws an error because, I guess, the linter exits with a non-zero status:

> npm run lint-staged
> project@ lint-staged C:\Users\user\Projects\project
> lint-staged

  source\script\component\accordion.js:2:1
  ×  2:1  Unexpected space between function name and paren.            no-spaced-func
  ×  2:1  meg is not defined.                                          no-undef
  ×  3:1  Unexpected newline between function and ( of function call.  no-unexpected-multiline

  3 errors
�  scripts:lint found some issues. Fix them and try again.

npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\user\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "run" "lint-staged"
npm ERR! node v4.5.0
npm ERR! npm  v3.8.5
npm ERR! code ELIFECYCLE
npm ERR! project@ lint-staged: `lint-staged`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the project@ lint-staged script 'lint-staged'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the project package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     lint-staged
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs project
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls project
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\user\Projects\project\npm-debug.log

package.json looks like this:

{
  "scripts": {
    "scripts:lint": "xo",
    "lint-staged": "lint-staged"
  },
  "lint-staged": {
    "*.js": "scripts:lint"
  },
  "pre-commit": "lint-staged"
}

Is this a bug or how can I otherwise prevent the npm error?

Issues with git workflow

This is valid for #75 and doesn't affect the published version!

Not sure how to reproduce but seems like if there were some stashes before for this file it ends up with

If one of the linters update the file contents then when we execute git stash pop where will be merge conflict for this file. We should execute git stash pop after the commit. I've added a test case here: 80ba161

 ✔ Running tasks for *.js
src/lib/__tests__/parseConfig.spec.js: unmerged (10b204cca737bc26f901456372c503354c43f815)
src/lib/__tests__/parseConfig.spec.js: unmerged (2f3e3c5f14e40ba9dcf6f5418deed76cb3757605)
src/lib/__tests__/parseConfig.spec.js: unmerged (a9ea7e10e0dda3995f214d84a0e72738d2115579)
error: Error building trees

Make linters optional

  1. Remove linter packages from dependencies.
  2. Check in Shell scripts that particular linter is installed, show installation instructions otherwise.

Work in subdirectory

@okonet thanks for awesome project.

We already add it for ESLint but have some strange issues with Stylelint. Sorry, I don’t know where I should look more.

package.json:

  "scripts": {
    "lint:css": "stylelint",
    "lint:js":  "eslint",
    "build":    "gulp build",
    "test":     "gulp"
  },
  "pre-commit": "lint-staged",
  "lint-staged": {
    "*.sss": "lint:css",
    "*.js":  "lint:js"
  }

When I add any .sss file to stage and run lint-stage I get:

Error: Files glob patterns specified did not match any files
    at /home/ai/Dev/amplifr/front/node_modules/stylelint/dist/standalone.js:83:19
😱  lint:css found some issues. Fix them and try again.

But when I run same stylelint script manually — npm run -s lint:css -- blocks/plan-viewport/plan-viewport.sss, everything works fine :-/

Doesn’t work in subdir

Preleased lint-staged works in subdirectory, but 3.1 doesn’t.

I tested, and got that lint-staged try to execute eslint with:

/home/ai/Dev/amplifr/front/node_modules/.bin/eslint -- /home/ai/Dev/amplifr/front/front/blocks/upload/upload.js

There are a two front/front in file path.

How to let 💩 slip into your code base

Hey,

thank you for the great work on #47 👍
Today I found out that you can trick lint-staged if you add code to the staging area which doesn't meet the linting rules and then change the file again to meet the rules before committing.

For example if you have forbidden semicolons in your .eslintrc you can commit code with semicolons if you:

  1. Stage the file with semicolons
  2. Change the file and remove all semicolons
  3. Commit the first file with semicolons but lint-staged will lint the second file without semicolons

I think it's not a big deal because you can always check the styleguide with travis on GitHub and you can run git commit --no-verify to skip commit hooks.

Switch from CLI to Node versions of libraries

It seems like using the shell (CLI) versions has too many issues: #5 #6 #7

The only way to resolve all of them would be going away from CLI and using Node API of libraries. This would allow more flexible configs. It should also fix issues with npm 2.x paths.

[Error: fatal: Not a git repository: '.git'

/home/theodor/projects/xxxxx/app/node_modules/lint-staged/src/resolvePaths.js:8
return filePaths.map(file => path.relative(cwd, path.resolve(base, file.filename)))
^

What am I missing ?

Accept commands in addition to NPM scripts

Hey,

I was wondering why I have to add git add and eslint --fix to the npm scripts to use them with lint-staged.

For example my package.json has to be:

"scripts": {
  "git:add": "git add",
  "eslint:fix": "eslint --fix"
},
"lint-staged": {
  "*.js": ["eslint:fix", "git:add"]
}

and I think it could be:

"lint-staged": {
  "*.js": ["eslint --fix", "git add"]
}

Is there any limitation, I am not aware of, so it can't be supported?

Double lint errors, NPM errors

First of all: thanks for the neat script 👍

In my current setup I could not get it to work because my package.json is way deep in the project. But: using Husky and an insane gitDir works…

"scripts": {
  "lint-staged": "lint-staged",
  "lint-staged:js": "eslint ./source/Javascript/modules/foo/",
  "lint-staged:css": "stylelint './source/CSS/**/*.css'",
},

"precommit": "lint-staged",

"lint-staged": {
  "gitDir": "../../../../../../../../",
  "linters": {
    "*.js": "lint-staged:js",
    "*.css": "lint-staged:css"
  }
}

However: I noticed running (testing) npm run lint-staged outputs a lint error twice.

screenshot 2016-11-14 13 32 46

When I simply run the task npm run lint-staged:css the linter shows one error.

Any ideas?

PS: related to #45 I have the same question. Because stylelint (in my case) returns non-zero both the stylelint error and the NPM ERR! are shown. This happens both when running npm run lint-staged as well as it being run from precommit.

I guess we need the linter to return a non-zero, but the NPM ERR!'s are a bit noisy...

Specify a different linter config file

Is there a way to specify a different linter config file than the .eslintrc in the project's root? There are certain rules I want disabled when I'm developing but still want to lint at commit time.

Allow glob exclusions

Some projects commit build (dist) files to the repository. Usually, the syntax of these generated files is out of the scope of linters. But ATM all files that matches the glob pattern will run against linters.

Ideally we want *-staged tasks to be configured the same way as normal linter tasks.

But this might require a major rewrite and switch to the Node from CLI.

Error message in Github Desktop

This tool gave error nicely in CLI but I just wanted to share that I use GitHub for desktop too along with CLI and some other developers in my team use SourceTree too.

Commit error in Github Desktop looks like this

image

Whole error code copied

/Users/jitendravyas/.zim/init.zsh: line 16: syntax error near unexpected token `('
/Users/jitendravyas/.zim/init.zsh: line 16: `  for wanted_module (${zmodules}); do'
�[?25l �[33m❯�[39m Running tasks for *.css
   �[33m⠙�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠹�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠸�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠼�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠴�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠦�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠧�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠇�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠏�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠋�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠙�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠹�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠸�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠼�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[33m⠴�[39m stylelint
�[?25l�[1000D�[K�[1A�[1000D�[K�[1A�[1000D�[K �[33m❯�[39m Running tasks for *.css
   �[31m✖�[39m stylelint
�[?25h
🚨  stylelint found some errors. Please fix them and try committing again.



�[4mapp/styles/main.css�[24m
 �[2m2:17�[22m  �[31m�[31m�[31m�[31m�[31m�[31m�[31m�[31m�[31m�[31m✖�[31m�[39m  Expected "#FFFFFF" to be "#ffffff"              �[2m�[2m�[2m�[2mcolor-hex-case�[22m        
 �[2m7:1�[22m   �[31m�[31m�[31m�[31m�[31m�[31m�[31m�[31m�[31m�[31m✖�[31m�[39m  Unexpected duplicate selector ".main-section"   �[2m�[2m�[2m�[2mno-duplicate-selectors�[22m



�[?25hpre-commit: 
pre-commit: We've failed to pass the specified git pre-commit hooks as the `lint-staged`
pre-commit: hook returned an exit code (1). If you're feeling adventurous you can
pre-commit: skip the git pre-commit hooks by adding the following flags to your commit:
pre-commit: 
pre-commit:   git commit -n (or --no-verify)
pre-commit: 
pre-commit: This is ill-advised since the commit is broken.
pre-commit: 
 (1)

Linting happening on unstaged files

So things seem to work as I would expect in 1.0.1 but not in 2.0.3 or @next.

I have 2 changed .scss files. One contains a linting error, the other does not.

In 1.0.1 I am able to do the following with no issues.

git add non-error-file.scss
git commit -m 'test'

It seems in v2+, the linter runs on staged and unstaged files as I get an error about the unstaged error-file.scss. Is this the intended behavior? I have no issues being on version 1 but I generally like to keep up to date on things.

No output from linter

I've configured lint-staged with tslint.
tslint is run via npm-run-script:

"scripts": {
      "tslint": "tslint -c tslint.json"
}

"lint-staged": {
    "*.tsx": "tslint",
    "gitDir": "../"
}

When I run tslint directly via Npm, I get linting messages:

~/workspace/ibanking/ui> npm run --silent tslint -- src/common/ModalDialog.tsx
src/common/ModalDialog.tsx[23, 27]: missing whitespace

But when I run it using lint-staged, I get no messages, just the indication of failed process

~/workspace/ibanking/ui> lint-staged
 ❯ Running tasks for *.tsx
   ✖ tslint

🚫 tslint found some errors. Please fix them and try committing again.

Using [email protected], execa 0.6.0 on MacOS.

Using .lintstagedrc file gives error

I get the following error:
TypeError: Cannot read property 'config' of null

I've copied the "lint-staged" section into the .lintstagedrc file.
{ "gitDir": "../../", "linters": { "*.js": "eslint" } }

Did I miss something?

When a task in a sequence of tasks fails, it should fail the hook

Following config will pass the check and commit even if eslint task fails:

"scripts": {
    "eslint:fix": "eslint --fix",
    "git:add": "git add",
    "lint-staged": "lint-staged"
  },
  "lint-staged": {
    "*.js": ["eslint:fix", "git:add"]
  },
  "pre-commit": [
    "lint-staged"
  ]

It should stop after the first non-zero exit code apparently.

Support npm 2.x

Using npm 2.x lint-staged installs staged-files binary at ./node_modules/lint-staged/node_modules/.bin making all scripts break. We should use some kind of resolving to find the proper path to the staged-files binary.

Re-formatting the code

// directory
.git/
assets/
    javascripts/
    stylesheets/
    package.json
// package.json
{
  "scripts": {
    "lint": "lint-staged",
  },
  "lint-staged": {
    "gitDir": "../",
    "linters": {
      "*.{js,jsx}": ["eslint --fix", "git add"],,
    }
  },
}
// .git/hooks/pre-commit
cd assets
npm run lint

My setting is like ↑.

With this setting it will be "Error: fatal: Not a git repository: '.git'".

Doesnt seem to fire as expected

I followed the steps in the associated blog post

I have things configured correctly (I believe) but when lint-staged script is executed, it does not report any errors. However, if I run eslint from CLI it correctly reports the errors.

$ run lint-staged
> [email protected] lint-staged /Users/mikeerickson/Documents/Projects/sandbox
> lint-staged

I am firing the script manually to see what happens, it appears to do nothing (maybe thinking there are no *.js files) My eslint script runs across whole project (I am trying to run it only against staged items)

I have issued git add . to add files, then running git commit and it commits without errors (but I have placed specific errors into files added)

If I run npm run eslint it correctly reports errors

“scripts”: {
 “eslint”: “eslint \”./src/**/*.js\””,
 “sass-lint”: “sass-lint -v -q”,
 “lint-staged”: “lint-staged”
 },
 “lint-staged”: {
 “eslint”: “*.js”,
 “sass-lint”: “*.sass”
 },
 “pre-commit”: “lint-staged”,
…

Run local scripts from package.json before trying a bin lookup

Having eslint installed and the following config in the package.json

"scripts": {
  "eslint": "eslint --fix"
},
"lint-staged": {
  "eslint": "*.js"
}

will run eslint without --fix parameter since it tries a bin lookup before trying to execute the local script. Local npm script should be the default behavior with a fallback to the bin lookup.

Lint staged array calling pre-configured scripts

Is it possible to do this (simply just run lint-staged on a script already pre-configured in the scripts section?)

"scripts": {
    "eslint": "./node_modules/.bin/eslint .",
    "stylelint": "./node_modules/.bin/stylelint statics/css/**/*.less --syntax less",
    "htmlhint": "./node_modules/.bin/htmlhint mvc/views",
    "lint": "npm run htmlhint && npm run stylelint && npm run eslint",
    "lint-staged": "lint-staged"
  },
  "lint-staged" [
    "htmlhint",
    "lesshint",
    "eslint"
  ]
  "pre-commit": [
    "lint-staged"
  ]

Commiting deleted files breaks lint-staged

If I delete a file, and then I try to commit the deletion. The linter throws an error in the pre-commit hook, because it tries to lint the deleted file that doesn't exists anymore.

Running eslint on git staged files: **/*.@(js|jsx)
Running jscs on git staged files: **/*.@(js|jsx)
Error: Path internals/scripts/clean.js was not found.
    at .<anonymous> (node_modules/jscs/lib/checker.js:188:19)
    at Array.<anonymous> (node_modules/vow/lib/vow.js:712:39)
    at Immediate.callFns [as _onImmediate] (node_modules/vow/lib/vow.js:23:35)
    at tryOnImmediate (timers.js:543:15)
    at processImmediate [as _immediateCallback] (timers.js:523:5)
pre-commit: 
pre-commit: We've failed to pass the specified git pre-commit hooks as the `lint:staged`
pre-commit: hook returned an exit code (1). If you're feeling adventurous you can
pre-commit: skip the git pre-commit hooks by adding the following flags to your commit:
pre-commit: 
pre-commit:   git commit -n (or --no-verify)
pre-commit: 
pre-commit: This is ill-advised since the commit is broken.
pre-commit: 

From: react-boilerplate/react-boilerplate#397

Support piping

Some packages implement stdin/out piping. For example $path | imageoptim should also be possible.

Spaces in Windows Git executable path causing errors

I'm likely barking up the wrong tree here, but I have to use a Windows 7 virtual machine to develop a project and I ran into a path issue while trying to use lint-staged.

Error: Command failed: C:\Program Files (x86)\Git\cmd\git.EXE rev-parse --show-toplevel
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.

    at checkExecSyncError (child_process.js:470:13)
    at Object.execSync (child_process.js:510:13)
    at Object.<anonymous> (E:\project\node_modules\lint-staged\src\index.js:12:15)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (E:\project\node_modules\lint-staged\index.js:2:1)

It seems the path to the Git executable isn't quoted properly, so the space inside is causing an issue. I'd imagine this is very likely to happen on most Windows systems, due to the default installation path containing a space.

I'm using Node v5.11.0 and NPM v3.8.6.

Provide a way to specify `--syntax` flag for stylelint

stylelint-staged detects syntax (i.e. SCSS) of committed files incorrectly — it throws errors that don't appear when stylelint is run normally. I'd guess that this is related to a new way that Stylelint requires syntax to be specified — it used to be defined in index.js, but now it is provided as param stylelint --syntax scss.

2.0.2 version in Windows causing errors

I updated to version 2 and is now on all Windows computers error. In this case all is well on the mac.

{
  "scripts": {
     "lint-staged": "lint-staged",
     "eslint:fix": "eslint --fix",
     "stylelint:less": "stylelint --syntax=less",
     "git:add": "git add"
  },
  "lint-staged": {
      "*.@(js|jsx)": [
        "eslint:fix",
        "git:add"
      ],
      "*.less": [
        "stylelint:less"
      ]
  },
  "pre-commit": [
      "lint-staged"
  ],
}
25h25hevents.js:154
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm ENOENT
    at exports._errnoException (util.js:856:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at nextTickCallbackWith2Args (node.js:475:9)
    at process._tickCallback (node.js:389:17)
pre-commit:
pre-commit: We've failed to pass the specified git pre-commit hooks as the `lint-staged`
pre-commit: hook returned an exit code (1). If you're feeling adventurous you can
pre-commit: skip the git pre-commit hooks by adding the following flags to your commit:
pre-commit:
pre-commit:   git commit -n (or --no-verify)
pre-commit:
pre-commit: This is ill-advised since the commit is broken.
pre-commit:

npm 3.6.0/3.9.3, node 5.6.0/6.2.1

Code published to npm is not compatible with README

Hi,

I installed the latest version from npm (3.0.3) but it wasn't working. I looked at the code in node_modules and it seems older than the code in the repo.

The README states that I can set the git root in the config 'git-root' but the code that pulls from npm does not support that, so it didn't work.

I manually copied the code from the repo into my node_modules and it works perfectly.

Could you please ensure that the README is in parity with the published code in the future?
Plus, publishing the latest code would be a huge help :)

P.S. This package is super helpful!

Many thanks!

confusion with file patterns

My package.json looks as follows:

{
  "scripts": {
    "lint-staged": "lint-staged"
  },
  "pre-commit": "lint-staged",
  "lint-staged": {
    "*.js": "eslint",
    "src/**/*.js": "eslint"
  },
}

My directory structure looks as follows:

├── .git
├── package.json
├── alpha.js                          [should match "*.js"]
├── src
    └── bravo
        └── charlie.js                [should match "src/**/*.js"]

I'm trying to commit alpha.js and src/bravo/charlie.js and expect both patterns given in lint-staged to each match one pattern, considering everything is relative to CWD. However neither matches.

If I prefix the patterns with **/ the files are matched. That's because the paths handed to minimatch are made absolute based on gitDir but not made relative against CWD again. The test suggests this is an oversight, or the test is mislabeled.

lint-staged v3.2.4
node v7.3.0
npm v3.10.10

my linters are engaged properly, if I replace the resolvePaths.js with the following:

module.exports = function resolvePaths(filePaths, relativeTo) {
    const cwd = process.cwd()
    const base = relativeTo || cwd
    return filePaths.map(file => path.relative(cwd, path.resolve(base, file.filename)))
}

TypeError: Cannot create property 'context' on string

Hi there

I have the following setup in place on a project running on node 7.2.1 and npm 3.10.10.

{
  "scripts": {
    "lint:js": "semistandard",
    "lint:fix": "semistandard --fix",
    "lint:staged": "lint-staged",
  },
  "lint-staged": {
    "*.{js,jsx}": "lint:js"
  },
  "pre-commit": {
    "run": "lint:staged",
    "colors": true,
    "silent": true
  },
  "devDependencies": {
    "lint-staged": "^3.2.3",
    "pre-commit": "^1.2.2",
    "semistandard": "^9.2.1",
  }
}

All is okay here:

$ npm run lint:js

> [email protected] lint:js /Users/mberridge/Sites/example
> semistandard | snazzy

semistandard: Semicolons For All! (https://github.com/Flet/semistandard)

/Users/mberridge/Sites/example/src/index.js
  9:1  error  Parsing error: Unexpected token

✖ 1 problem

But running npm run lint:staged returns an error wrapped around the output:

$ npm run lint:staged

> [email protected] lint:staged /Users/mberridge/Sites/example
> lint-staged

 ❯ Running tasks for *.{js,jsx}
   ✖ lint:js
{ TypeError: Cannot create property 'context' on string '
🚫 lint:js found some errors. Please fix them and try committing again.

semistandard: Semicolons For All! (https://github.com/Flet/semistandard)

/Users/mberridge/Sites/example/src/index.js
  9:1  error  Parsing error: Unexpected token

✖ 1 problem

'
    at tasks.then.catch.err (/Users/mberridge/Sites/example/node_modules/lint-staged/node_modules/listr/index.js:74:17)
    at process._tickCallback (internal/process/next_tick.js:103:7) context: {} }

Not the end of the world, as it's still linting and working with pre-commit too.
But have I done something wrong to cause the error?

Any help appreciated, thanks all!

Support sequences of commands

Sometimes it's required to run a set of commands on same file. Consider this example:

  "scripts": {
    "stylelint-staged": "stylelint --syntax scss",
    "postcss-sorting": "postcss --syntax postcss-scss --config postcss-sorting.config.js --replace",
    "lint-staged": "lint-staged"
  },
  "lint-staged": {
    "postcss-sorting": "*.scss",
    "stylelint-staged": "*.scss"
  }

This will run postcss-sorting and stylelint-staged in parallel. But what we want is to sort rules and then lint it — i.e. sequential run.

Together with #16 it should allow interesting workflows with almost zero configuration.

git: 'Files\Git\mingw64\libexec\git-core\git.EXE' is not a git command. See 'git --help'.

Hi,
I just upgraded from 3.0.3 to 3.2.4 and got this error:

[12:16:25] Running tasks for **/scripts/**/*.js [started]
[12:16:25] eslint --fix --config ./.eslintrc-fix.yml [started]
[12:16:25] eslint --fix --config ./.eslintrc-fix.yml [completed]
[12:16:25] git add [started]
[12:16:25] git add [failed]
[12:16:25] Running tasks for **/scripts/**/*.js [failed]

� git add found some errors. Please fix them and try committing again.

git: 'Files\Git\mingw64\libexec\git-core\git.EXE' is not a git command. See 'git --help'.

I have lint-staged configured like this:

  "lint-staged": {
    ...,
    "**/scripts/**/*.js": [
      "eslint --fix --config ./.eslintrc-fix.yml",
      "git add"
    ],
    ...
  },

My guess is that there is some issue when git binary location contains space characters. In my case it is: C:\Program Files\Git\mingw64\libexec\git-core\git.exe

OS: Windows 10 Pro
npm: 3.10.10
node: 7.2.1

For the time being I am staying on 3.0.3 3.2.0 where everything works just fine.
Thank you for work you put in this awesome project 😄

Update:
It works on 3.2.0 as well

Add presets for even simpler installation process

ESLint presets are awesome and I think lint-staged should allow pre-configured presets as well.

In a nutshell, presets should be just plain objects that then should be added to an array during the init phase.

When running with just 1 linter, it throws

node ./index.js
⠋ Starting lint-staged/Users/okonet/Projects/OSS/lint-staged/src/index.js:26
                spinner.text = 'Running ' + Array.isArray(linter) ? linter.join(' → ') : linter + '...'
                                                                           ^

TypeError: linter.join is not a function
    at /Users/okonet/Projects/OSS/lint-staged/src/index.js:26:76
    at Array.forEach (native)
    at /Users/okonet/Projects/OSS/lint-staged/src/index.js:22:30
    at /Users/okonet/Projects/OSS/lint-staged/node_modules/staged-git-files/index.js:20:21
    at ChildProcess.<anonymous> (/Users/okonet/Projects/OSS/lint-staged/node_modules/staged-git-files/index.js:88:9)
    at emitTwo (events.js:100:13)
    at ChildProcess.emit (events.js:185:7)
    at maybeClose (internal/child_process.js:850:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:215:5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.