ignore

repository·master·Indexed 19 days ago

https://github.com/kaelzhang/node-ignore

A pure JavaScript implementation of the .gitignore specification (v2.22.1) used for filtering and managing file paths based on ignore patterns. It provides a manager to add rules via .add(), check if paths are ignored using .ignores(), and filter arrays of paths. The library includes detailed inspection via .test() and .checkIgnore(), as well as a utility function isPathValid() to ensure paths follow the required relative path conventions.

Tokens
3.9K
Snippets
17
Records
19
Agent score
17%

What's inside ignore

  1. Pathname conventions for node-ignore

    master

    When using methods like .ignores(), .filter(), or .test(), the paths provided must follow these conventions:

    1. Must be relative paths: Paths should be the result of path.relative() to the directory containing the ignore rules.
      • WRONG: ./abc, /abc, or absolute Windows paths like C:\abc will throw errors.
      • RIGHT: abc or path.join('abc') (which resolves to a relative path).
    2. Files vs Directories: node-ignore does not perform filesystem checks (fs.stat). It relies on the string format to distinguish types:
      • foo is treated as a file.
      • foo/ is treated as a directory.

    To ensure you are passing directory paths correctly when using tools like glob, use the mark: true option to append a trailing slash to directory names.

    import glob from 'glob'
    import ignore from 'ignore'
    
    glob('**', { mark: true }, (err, files) => {
      if (err) return console.error(err)
      
      // 'files' will contain directory names with trailing slashes (e.g., 'config/')
      let filtered = ignore().add(['config/']).filter(files)
      console.log(filtered)
    })
  2. Migrate from ignore 5.x to 6.x (Handling invalid pathnames)

    master

    Starting from version 5.0.0, passing an invalid Pathname to .ignores() will throw an error. To prevent this, you can either pass options.allowRelative = true to the Ignore factory or manually validate paths using the isPathValid utility introduced in 5.0.0.

    Invalid pathnames include empty strings, non-string values (like false), relative paths starting with .., or the current directory ..

    import {isPathValid} from 'ignore'
    
    const paths = [
      '',
      false,
      '../foo',
      '.',
      'foo' // valid
    ].filter(isPathValid)
    
    // Now safe to use with your ignore instance
    ig.filter(paths)
  3. Migrate from ignore 2.x to 3.x

    master

    Several breaking changes occurred in version 3.0.0:

    • All options from 2.x were removed; they are no longer necessary.
    • The ignore() instance is no longer an EventEmitter; all event-based logic was removed.
    • The .addIgnoreFile() method was removed. Use the .add() method instead to add patterns.
  4. Migrate from ignore 4.x to 5.x

    master

    In version 5.0.0, the following methods were standardized to follow specific return value conventions for Pathname handling:

    • .ignores(pathname: Pathname): boolean
    • .filter(pathnames: Array<Pathname>): Array<Pathname>
    • .createFilter(): (pathname: Pathname) => boolean
    • .test(pathname: Pathname): {ignored: boolean, unignored: boolean}

    Users are responsible for converting or filtering invalid pathnames before passing them to these methods.

  5. Basic usage of ignore

    master

    You can initialize an ignore instance, add patterns (including negative patterns to unignore files), and then filter paths or check if specific paths are ignored.

    Note: ignore follows the .gitignore spec 2.22.1. If you need to parse .npmignore files, use minimatch instead, as npm uses minimatch for .npmignore and it does not follow the gitignore spec.

    import ignore from 'ignore'
    const ig = ignore().add(['.abc/*', '!.abc/d/'])
    
    const paths = [
      '.abc/a.js',    // filtered out
      '.abc/d/e.js'   // included
    ]
    
    ig.filter(paths)        // ['.abc/d/e.js']
    ig.ignores('.abc/a.js') // true
  6. Configure ignore case sensitivity

    master

    By default, ignore is case-insensitive (matching git-config behavior). You can change this via the constructor options.

    Options:

    • ignorecase (v4.0.0+): boolean. Set to false for case-sensitive matching. (Note: ignoreCase is an alias since v5.2.0).
    • allowRelativePaths (v5.2.0+): boolean. If true, it disables the check that ensures paths are path.relative()d. This is provided for backward compatibility with v4.x, but using ./foo or ../foo is not recommended.
    // Case-sensitive matching
    const ig = ignore({ ignorecase: false })
    ig.add('*.png')
    ig.ignores('image.PNG') // false
    
    // Allowing non-standard relative paths
    const igRel = ignore({ allowRelativePaths: true })
    ig.ignores('../foo/bar.js') // true (will not throw)
  7. Initialize node-ignore

    master

    To use node-ignore, call the default export (the factory function) with an optional configuration object. This returns an Ignore instance used to manage ignore patterns and test paths.

    Configuration Options:

    • ignorecase (boolean, default: true): Whether pattern matching should be case-insensitive.
    • allowRelativePaths (boolean, default: false): If false, the library will throw errors if paths are not relative (e.g., absolute paths or paths starting with . or ..).
    const factory = require('node-ignore');
    
    // Default configuration (case-insensitive, strict relative paths)
    const ignore = factory();
    
    // Custom configuration
    const ignoreCustom = factory({
      ignorecase: false,
      allowRelativePaths: true
    });
  8. How to use ignore as a filter function

    master

    Instead of calling .filter() manually, you can use .createFilter() to generate a function compatible with Array.prototype.filter.

    const ig = ignore().add(['node_modules/'])
    const paths = ['index.js', 'node_modules/lodash/index.js']
    
    // Use the created filter function directly in Array.filter
    const filtered = paths.filter(ig.createFilter())
    // Result: ['index.js']
  9. Debug ignore rules with .checkIgnore()

    master

    Introduced in v7.0.0, .checkIgnore(target) is designed to mimic git check-ignore -v. It returns a TestResult that includes the rule details, making it useful for debugging or implementing git-like CLI tools.

    Warning: This method does not have a strong built-in cache mechanism. Avoid using it in performance-critical loops.

    const ig = ignore().add({
      pattern: 'foo/*',
      mark: '60'
    })
    
    const { ignored, rule } = ig.checkIgnore('foo/bar.js')
    
    if (ignored) {
      // Example output format mimicking git check-ignore -v
      console.log(`.gitignore:${rule.mark}:${rule.pattern} foo/bar.js`)
    }
  10. Validate path format with isPathValid()

    master

    A static method used to check if a given pathname follows the required path.relative() convention. This does not validate if the ignore pattern itself is valid.

    import { isPathValid } from 'ignore'
    
    isPathValid('abc/def')   // true
    isPathValid('./abc/def') // false