minimatch

repository·main·Indexed 26 days ago

https://github.com/isaacs/minimatch

A minimal glob matcher in JavaScript used internally by npm. It converts glob expressions into JavaScript Regular Expressions to perform pattern matching against file paths. Features include support for brace expansion, partial matching for directory walking, and specific configurations for Windows paths. Version 10.2.6.

Tokens
3K
Snippets
5
Records
24
Agent score
85%

What's inside minimatch

  1. Use minimatch for basic pattern matching

    main

    You can use the main minimatch function to test if a specific path matches a glob pattern. It supports both CommonJS (require) and ESM (import) syntax.

    import { minimatch } from 'minimatch'
    // or:
    const { minimatch } = require('minimatch')
    
    minimatch('bar.foo', '*.foo') // true
    minimatch('bar.foo', '*.bar') // false
    import { minimatch } from 'minimatch'
    
    minimatch('bar.foo', '*.foo') // true!
  2. Configure glob patterns for Windows

    main

    When working with Windows paths, follow these rules to ensure correct matching:

    1. Use forward-slashes in patterns: Always use / in your glob expressions. Backslashes (\) in patterns are interpreted as escape characters, not path separators.
    2. UNC Paths:
      • Patterns starting with //?/<drive letter>: treat the ? as a literal string, not a wildcard.
      • Patterns starting with //?/<drive letter>:/... match file paths starting with <drive letter>:/... (case-insensitively for the drive letter).
    3. Backslash support: To allow backslashes in the pattern argument as path separators, you must set the windowsPathsNoEscape: true option.
  3. Configure minimatch options

    main

    The minimatch function and Minimatch class accept an options object to customize matching behavior. All options are false by default.

    Common Matching Options

    • dot: Allow patterns to match filenames starting with a period (e.g., a/**/b will match a/.d/b).
    • nocase: Perform a case-insensitive match.
    • noglobstar: Disable ** matching against multiple folder names.
    • nobrace: Do not expand {a,b} and {1..3} brace sets.
    • noext: Disable "extglob" style patterns like +(a|b).
    • matchBase: If set, patterns without slashes match against the basename of the path (e.g., a?b matches /xyz/123/acb).
    • nonegate: Suppress treating a leading ! as negation.
    • nocomment: Suppress treating # at the start of a pattern as a comment.
    • partial: Compare a partial path to a pattern. Returns true if the existing parts of the path are not contradicted by the pattern. Useful for directory walking.

    Advanced Configuration

    • optimizationLevel: Controls pattern optimization (0-2).
      • 0: No changes. . and .. are maintained.
      • 1 (default): Removes .. following non-special pattern portions.
      • 2: Aggressive optimization for file-walking (removes empty/. portions, dedupes ** and * patterns).
    • platform: Set to win32 to trigger Windows-specific behaviors (UNC paths, \ as separators).
    • maxGlobstarRecursion: Max number of non-adjacent ** patterns to walk (default 200).
    • maxExtglobRecursion: Max depth for nested extglobs (default 2).
  4. Security Warning: ReDoS Risk

    main

    ⚠️ Important Security Consideration

    minimatch uses JavaScript regular expressions to perform matching. If you use untrusted user input to generate a glob pattern, your system may be vulnerable to Regular expression Denial of Service (ReDoS) attacks.

    Do not use user-provided input as the source of a pattern in a production system.

    Future versions of the library may implement a non-backtracking algorithm, but such changes will be breaking and will not be backported to legacy versions.

  5. Use partial matching for directory walking

    main

    The partial: true option allows you to check if a current path segment could potentially match a full pattern. This is useful when walking a file system to avoid entering directories that cannot satisfy a pattern.

    // Returns true, because /a/b might be part of /a/b/c/d
    minimatch('/a/b', '/a/*/c/d', { partial: true }) 
    
    // Returns true, because /a/b might be part of /a/b/.../d
    minimatch('/a/b', '/**/d', { partial: true }) 
    
    // Returns false, because x !== a
    minimatch('/x/y/z', '/a/**/z', { partial: true }) 
    minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
    minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
    minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
  6. Filter an array of files using minimatch.filter

    main

    The minimatch.filter method returns a predicate function that can be passed directly to Array.prototype.filter to extract files matching a pattern.

    var javascripts = fileList.filter(
      minimatch.filter('*.js', { matchBase: true }),
    )
  7. Match a list of files with minimatch.match

    main

    Use minimatch.match(list, pattern, options) to return an array of all items from a list that match the provided pattern. If no matches are found and the nonull option is set, it returns a list containing the pattern itself.

    var javascripts = minimatch.match(fileList, '*.js', { matchBase: true })
  8. Un-escape a glob string with minimatch.unescape

    main

    Use minimatch.unescape(pattern, options) to remove escape characters from a glob string.

    • Default behavior: Removes both brace escapes and backslash escapes.
    • With windowsPathsNoEscape: true: Removes square-brace escapes (e.g., [*] becomes *) but does not remove backslash escapes, as \ is treated as a path separator.
  9. Create a Minimatch instance

    main

    For more complex usage, you can instantiate the Minimatch class. This allows you to inspect properties like set (the expanded pattern parts) or regexp (the generated regular expression).

    var Minimatch = require('minimatch').Minimatch
    var mm = new Minimatch(pattern, options)
  10. Configure MinimatchOptions

    main

    When using minimatch or the Minimatch class, you can provide a MinimatchOptions object to customize matching behavior. Key options include:

    • nobrace: Do not expand {x,y} style braces.
    • nocomment: Do not treat patterns starting with # as a comment.
    • nonegate: Do not treat patterns starting with ! as a negation.
    • noglobstar: Treat ** the same as *.
    • noext: Do not expand extglobs like +(a|b).
    • nonull: Return the pattern if nothing matches.
    • dot: Allow matches that start with . even if the pattern does not.
    • nocase: Ignore case.
    • matchBase: If set, patterns without slashes will be matched against the basename of the path if it contains slashes.
    • flipNegate: Invert the results of negated matches.
    • preserveMultipleSlashes: Do not collapse multiple / into a single /.
    • optimizationLevel: A number indicating the level of optimization (0-2) for the pattern.
    • platform: The operating system platform (e.g., 'win32', 'linux', 'darwin').
    • braceExpandMax: Max number of {...} patterns to expand (Default: 100,000).
    • maxGlobstarRecursion: Max number of non-adjacent ** patterns to recursively walk down (Default: 200).
    • maxExtglobRecursion: Max depth to traverse for nested extglobs (Default: 2).
  11. Understand minimatch behavior differences

    main

    Minimatch has specific behaviors that differ from standard fnmatch or shell implementations:

    • Negation: A leading ! negates the pattern. Use nonegate: true to treat ! as a literal.
    • Comments: A leading # is treated as a comment. Use nocomment: true or escape it (\#) to match a literal #.
    • Globstar (**): Only has special significance if it is the only thing in a path part. a/**/b matches a/x/y/b, but a/**b does not.
    • Slash Handling: Unlike fnmatch(3), minimatch treats / specially. foo* will not match foo/bar.
    • Brace Expansion: Performed before other interpretations. Patterns like +(a|{b),c)} are expanded first and then validated.