Giter Club home page Giter Club logo

minimatch's Introduction

minimatch

A minimal matching utility.

This is the matching library used internally by npm.

It works by converting glob expressions into JavaScript RegExp objects.

Usage

// hybrid module, load with require() or import
import { minimatch } from 'minimatch'
// or:
const { minimatch } = require('minimatch')

minimatch('bar.foo', '*.foo') // true!
minimatch('bar.foo', '*.bar') // false!
minimatch('bar.foo', '*.+(bar|foo)', { debug: true }) // true, and noisy!

Features

Supports these glob features:

  • Brace Expansion
  • Extended glob matching
  • "Globstar" ** matching
  • Posix character classes, like [[:alpha:]], supporting the full range of Unicode characters. For example, [[:alpha:]] will match against 'é', though [a-zA-Z] will not. Collating symbol and set matching is not supported, so [[=e=]] will not match 'é' and [[.ch.]] will not match 'ch' in locales where ch is considered a single character.

See:

Windows

Please only use forward-slashes in glob expressions.

Though windows uses either / or \ as its path separator, only / characters are used by this glob implementation. You must use forward-slashes only in glob expressions. Back-slashes in patterns will always be interpreted as escape characters, not path separators.

Note that \ or / will be interpreted as path separators in paths on Windows, and will match against / in glob expressions.

So just always use / in patterns.

UNC Paths

On Windows, UNC paths like //?/c:/... or //ComputerName/Share/... are handled specially.

  • Patterns starting with a double-slash followed by some non-slash characters will preserve their double-slash. As a result, a pattern like //* will match //x, but not /x.
  • Patterns staring with //?/<drive letter>: will not treat the ? as a wildcard character. Instead, it will be treated as a normal string.
  • Patterns starting with //?/<drive letter>:/... will match file paths starting with <drive letter>:/..., and vice versa, as if the //?/ was not present. This behavior only is present when the drive letters are a case-insensitive match to one another. The remaining portions of the path/pattern are compared case sensitively, unless nocase:true is set.

Note that specifying a UNC path using \ characters as path separators is always allowed in the file path argument, but only allowed in the pattern argument when windowsPathsNoEscape: true is set in the options.

Minimatch Class

Create a minimatch object by instantiating the minimatch.Minimatch class.

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

Properties

  • pattern The original pattern the minimatch object represents.

  • options The options supplied to the constructor.

  • set A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern {a,b/c}/d would expand to a set of patterns like:

      [ [ a, d ]
      , [ b, c, d ] ]
    

    If a portion of the pattern doesn't have any "magic" in it (that is, it's something like "foo" rather than fo*o?), then it will be left as a string rather than converted to a regular expression.

  • regexp Created by the makeRe method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like fnmatch(3) with FNM_PATH enabled.

  • negate True if the pattern is negated.

  • comment True if the pattern is a comment.

  • empty True if the pattern is "".

Methods

  • makeRe() Generate the regexp member if necessary, and return it. Will return false if the pattern is invalid.

  • match(fname) Return true if the filename matches the pattern, or false otherwise.

  • matchOne(fileArray, patternArray, partial) Take a /-split filename, and match it against a single row in the regExpSet. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls.

  • hasMagic() Returns true if the parsed pattern contains any magic characters. Returns false if all comparator parts are string literals. If the magicalBraces option is set on the constructor, then it will consider brace expansions which are not otherwise magical to be magic. If not set, then a pattern like a{b,c}d will return false, because neither abd nor acd contain any special glob characters.

    This does not mean that the pattern string can be used as a literal filename, as it may contain magic glob characters that are escaped. For example, the pattern \\* or [*] would not be considered to have magic, as the matching portion parses to the literal string '*' and would match a path named '*', not '\\*' or '[*]'. The minimatch.unescape() method may be used to remove escape characters.

All other methods are internal, and will be called as necessary.

minimatch(path, pattern, options)

Main export. Tests a path against the pattern using the options.

var isJS = minimatch(file, '*.js', { matchBase: true })

minimatch.filter(pattern, options)

Returns a function that tests its supplied argument, suitable for use with Array.filter. Example:

var javascripts = fileList.filter(minimatch.filter('*.js', { matchBase: true }))

minimatch.escape(pattern, options = {})

Escape all magic characters in a glob pattern, so that it will only ever match literal strings

If the windowsPathsNoEscape option is used, then characters are escaped by wrapping in [], because a magic character wrapped in a character class can only be satisfied by that exact character.

Slashes (and backslashes in windowsPathsNoEscape mode) cannot be escaped or unescaped.

minimatch.unescape(pattern, options = {})

Un-escape a glob string that may contain some escaped characters.

If the windowsPathsNoEscape option is used, then square-brace escapes are removed, but not backslash escapes. For example, it will turn the string '[*]' into *, but it will not turn '\\*' into '*', because \ is a path separator in windowsPathsNoEscape mode.

When windowsPathsNoEscape is not set, then both brace escapes and backslash escapes are removed.

Slashes (and backslashes in windowsPathsNoEscape mode) cannot be escaped or unescaped.

minimatch.match(list, pattern, options)

Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself.

var javascripts = minimatch.match(fileList, '*.js', { matchBase: true })

minimatch.makeRe(pattern, options)

Make a regular expression object from the pattern.

Options

All options are false by default.

debug

Dump a ton of stuff to stderr.

nobrace

Do not expand {a,b} and {1..3} brace sets.

noglobstar

Disable ** matching against multiple folder names.

dot

Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot.

Note that by default, a/**/b will not match a/.d/b, unless dot is set.

noext

Disable "extglob" style patterns like +(a|b).

nocase

Perform a case-insensitive match.

nocaseMagicOnly

When used with {nocase: true}, create regular expressions that are case-insensitive, but leave string match portions untouched. Has no effect when used without {nocase: true}

Useful when some other form of case-insensitive matching is used, or if the original string representation is useful in some other way.

nonull

When a match is not found by minimatch.match, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches.

magicalBraces

This only affects the results of the Minimatch.hasMagic method.

If the pattern contains brace expansions, such as a{b,c}d, but no other magic characters, then the Minimatch.hasMagic() method will return false by default. When this option set, it will return true for brace expansion as well as other magic glob characters.

matchBase

If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123.

nocomment

Suppress the behavior of treating # at the start of a pattern as a comment.

nonegate

Suppress the behavior of treating a leading ! character as negation.

flipNegate

Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.)

partial

Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match.

For example,

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

windowsPathsNoEscape

Use \\ as a path separator only, and never as an escape character. If set, all \\ characters are replaced with / in the pattern. Note that this makes it impossible to match against paths containing literal glob pattern characters, but allows matching with patterns constructed using path.join() and path.resolve() on Windows platforms, mimicking the (buggy!) behavior of earlier versions on Windows. Please use with caution, and be mindful of the caveat about Windows paths.

For legacy reasons, this is also set if options.allowWindowsEscape is set to the exact value false.

windowsNoMagicRoot

When a pattern starts with a UNC path or drive letter, and in nocase:true mode, do not convert the root portions of the pattern into a case-insensitive regular expression, and instead leave them as strings.

This is the default when the platform is win32 and nocase:true is set.

preserveMultipleSlashes

By default, multiple / characters (other than the leading // in a UNC path, see "UNC Paths" above) are treated as a single /.

That is, a pattern like a///b will match the file path a/b.

Set preserveMultipleSlashes: true to suppress this behavior.

optimizationLevel

A number indicating the level of optimization that should be done to the pattern prior to parsing and using it for matches.

Globstar parts ** are always converted to * when noglobstar is set, and multiple adjascent ** parts are converted into a single ** (ie, a/**/**/b will be treated as a/**/b, as this is equivalent in all cases).

  • 0 - Make no further changes. In this mode, . and .. are maintained in the pattern, meaning that they must also appear in the same position in the test path string. Eg, a pattern like a/*/../c will match the string a/b/../c but not the string a/c.

  • 1 - (default) Remove cases where a double-dot .. follows a pattern portion that is not **, ., .., or empty ''. For example, the pattern ./a/b/../* is converted to ./a/*, and so it will match the path string ./a/c, but not the path string ./a/b/../c. Dots and empty path portions in the pattern are preserved.

  • 2 (or higher) - Much more aggressive optimizations, suitable for use with file-walking cases:

    • Remove cases where a double-dot .. follows a pattern portion that is not **, ., or empty ''. Remove empty and . portions of the pattern, where safe to do so (ie, anywhere other than the last position, the first position, or the second position in a pattern starting with /, as this may indicate a UNC path on Windows).
    • Convert patterns containing <pre>/**/../<p>/<rest> into the equivalent <pre>/{..,**}/<p>/<rest>, where <p> is a a pattern portion other than ., .., **, or empty ''.
    • Dedupe patterns where a ** portion is present in one and omitted in another, and it is not the final path portion, and they are otherwise equivalent. So {a/**/b,a/b} becomes a/**/b, because ** matches against an empty path portion.
    • Dedupe patterns where a * portion is present in one, and a non-dot pattern other than **, ., .., or '' is in the same position in the other. So a/{*,x}/b becomes a/*/b, because * can match against x.

    While these optimizations improve the performance of file-walking use cases such as glob (ie, the reason this module exists), there are cases where it will fail to match a literal string that would have been matched in optimization level 1 or 0.

    Specifically, while the Minimatch.match() method will optimize the file path string in the same ways, resulting in the same matches, it will fail when tested with the regular expression provided by Minimatch.makeRe(), unless the path string is first processed with minimatch.levelTwoFileOptimize() or similar.

platform

When set to win32, this will trigger all windows-specific behaviors (special handling for UNC paths, and treating \ as separators in file paths for comparison.)

Defaults to the value of process.platform.

Comparisons to other fnmatch/glob implementations

While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations. Some are intentional, and some are unavoidable.

If the pattern starts with a ! character, then it is negated. Set the nonegate flag to suppress this behavior, and treat leading ! characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like !(a|B). Multiple ! characters at the start of a pattern will negate the pattern multiple times.

If a pattern starts with #, then it is treated as a comment, and will not match anything. Use \# to match a literal # at the start of a line, or set the nocomment flag to suppress this behavior.

The double-star character ** is supported by default, unless the noglobstar flag is set. This is supported in the manner of bsdglob and bash 4.1, where ** only has special significance if it is the only thing in a path part. That is, a/**/b will match a/x/y/b, but a/**b will not.

If an escaped pattern has no matches, and the nonull flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, minimatch.match([], "\\*a\\?") will return "\\*a\\?" rather than "*a?". This is akin to setting the nullglob option in bash, except that it does not resolve escaped pattern characters.

If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like +(a|{b),c)}, which would not be valid in bash or zsh, is expanded first into the set of +(a|b) and +(a|c), and those patterns are checked for validity. Since those two are valid, matching proceeds.

Negated extglob patterns are handled as closely as possible to Bash semantics, but there are some cases with negative extglobs which are exceedingly difficult to express in a JavaScript regular expression. In particular the negated pattern <start>!(<pattern>*|)* will in bash match anything that does not start with <start><pattern>. However, <start>!(<pattern>*)* will match paths starting with <start><pattern>, because the empty string can match against the negated portion. In this library, <start>!(<pattern>*|)* will not match any pattern starting with <start>, due to a difference in precisely which patterns are considered "greedy" in Regular Expressions vs bash path expansion. This may be fixable, but not without incurring some complexity and performance costs, and the trade-off seems to not be worth pursuing.

Note that fnmatch(3) in libc is an extremely naive string comparison matcher, which does not do anything special for slashes. This library is designed to be used in glob searching and file walkers, and so it does do special things with /. Thus, foo* will not match foo/bar in this library, even though it would in fnmatch(3).

minimatch's People

Contributors

avivahl avatar commanderroot avatar djchie avatar erikkemperman avatar forivall avatar frandiox avatar gjtorikian avatar isaacs avatar jgillich avatar jonathanong avatar kevinsawicki avatar legobeat avatar litmit avatar ljharb avatar lukekarrys avatar maxg avatar mcandre avatar miguelcastillo avatar mrgriefs avatar nitoyon avatar peterdavehello avatar roggervalf avatar santoshyadavdev avatar stefanpenner avatar unchartedbull avatar wdavidw 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

minimatch's Issues

minimatch cache key computation seems wrong

  var cacheKey = pattern + "\n" + Object.keys(options).filter(function (k) {
    return options[k]
  }).join(":")

This creates a cachekey with the key names of all truthy options rather than their values (since it is using filter and not map).

Causes issues when two calls have the same pattern but only differ in the value of options.cwd

I guess it should be something like:

  var cacheKey = pattern + "\n" + Object.keys(options).map(function (k) {
    return k + '=' + options[k]
  }).join(":")

minimatch.makeRe ignores flipNegate

It appears minimatch.makeRe("*1.js", {"flipNegate":true, "matchBase":true}) for {a.js, a1.js} still returns a1.js instead of a.js when using it with filename.match(miniRegexp).

Is it ignoring it, or am I missing something?

extglob implicit *

In node repl:

var m = require('minimatch'),
f1 = 'name/asdf.md',
f2 = 'nameasdf/asdf.md',
f3 = 'ok/asdf.md';

pattern = '!(name)/*.md'

m(f1, pattern, {nonegate:true}) // false
m(f2, pattern, {nonegate:true}) // false
m(f3, pattern, {nonegate:true}) // true
$ grep version node_modules/minimatch/package.json 
  "version": "2.0.1",
$ node --version
v0.10.33

Is this expected?

Simpler exclusion pattern when globbing

When I try to exclude a directory (and its files) from a glob, I need to write out the pattern like this:

[
  'app/**',
  '!app/{_tmp,_tmp/**}'
]

Just using this:

[
  'app/**',
  '!app/_tmp/**'
]

would copy over the directory, but will not contain any files. While using this:

[
  'app/**',
  '!app/_tmp/'
]

would copy over _tmp and its files.

Is there any way to simplify this pattern? It seems like just using '!app/_tmp/**' should be sufficient to exclude the directory entirely.

(Referencing gulpjs/gulp#165)

package.json malformed JSON?

I got an error while running yeoman's angular generator, yo angular, which in turn installs minimatch as a dependency. The exact error has to do with parsing minimatch's package.json file which it doesn't seem to think is valid JSON.

yo-angular-minimatch-error

I tried require-ing package.json in a separate node instance and it seemed to be OK, so not sure if this is really a bug in minimatch or npm's fault despite it professing it's not in the error message.

If anyone can reproduce on their end I can take a more detailed look, or if anyone knows why this may be happening we can can this issue.

negative matches problem for .min.js like paths

I am trying to filter files by extnames:

var minimatch = require('minimatch');
console.log(minimatch('foo/bar.min.js', '*.!(js|css)', {matchBase: true})); // true
console.log(minimatch('foo/bar.min.js', '!*.+(js|css)', {matchBase: true}));    // false

Are the results expected?

Build tests

Any reason why the build tests were paused? This library is downloaded quite a bit (46k/day according to npmjs). Could we get those re-enabled and/or the tests updated?

README needs some links to manpages or regex patterns

I'm honestly lost as to what is available to me and how to negate a pattern and I've been using GNU/Linux for the last decade and have seen all sorts of hairy regexp patterns and can't make heads or tails what I can use here.

How about some links to manpages or regex patterns or some more examples or something?

browser version

Hi! Why publish browser version on npm? It just increased size of package.

Give some examples

It would help to have a handful of example patterns at the top of the readme (each with examples of paths they match and do not match), to show how things like globstars, brace expansion and parentheses work. I imagine this is the main thing people come here for, and the readme barely touches on it.

Problem with exclusion syntax

I am currently facing a problem using minimatch syntax through gulp for a simple task.

Here is how my files are organized :

public/
____app/
________file4.txt
________js/
____________admin/
________________files1.txt
________________files2.txt
____________otherfolder/
________________files3.txt
____________file4.txt

I am trying to get all files included in app (only file4.txt in my example) and in the app/js/admin folder (files1.txt & files2.txt).

Here is my glob syntax :

['public/app/js/admin/**/*.txt', '!public/app/js/**', 'public/app/**']

With this command, it only return file4.txt and an empty js folder.

Thanks for your help !

Incorrect extended glob results

When an extended glob pattern ends in a special character, it seems that non-matching strings can be erroneously matched. E.g.:

> var m = require('minimatch')
> m('testing', 'test')
false // ok
> m('testing', 'test@(x*)')
false // ok
> m('testing', 'test?(x*)')
true  // :(
> m('testing', 'test*(x*)')
true  // :(

As a sanity check, Bash thinks differently:

$ touch testing 
$ ls test?(x*)
ls: cannot access test?(x*): No such file or directory
$ ls test*(x*)
ls: cannot access test*(x*): No such file or directory

From the output with debug: true, it looks like the special is getting translated outside of the parentheses when it should be inside:

> m('testing', 'test?(x*)', { debug:true })

… resulting pattern: /^(?=.)test(?:x)?[^/]*?$/

Compare with:

> m('testing', 'test?(x*y)', { debug:true })

… resulting pattern: /^(?=.)test(?:x[^/]*?y)?$/

pattern `**/.svn/**` doesn't work as expected when using `minimatch()`

if I do find . -path "**/.svn/**" it will log all the files inside all .svn folders, no matter how deep they are, shouldn't minimatch() also match these paths?

js/lib/.svn/tmp
js/lib/.svn/tmp/prop-base
js/lib/.svn/tmp/props
js/lib/.svn/tmp/text-base
js/lib/.svn/tmp/text-base/foo.js.svn-base
js/lib/.svn/tmp/text-base/bar.js.svn-base
js/widgets/templates/.svn/all-wcprops
js/widgets/templates/.svn/entries

the weird thing is that if I use minimatch.makeRe() it generates the proper RegExp... simple test:

var minimatch = require('minimatch');
minimatch('js/lib/.svn/tmp', '**/.svn/**'); // false
minimatch.makeRe('**/.svn/**').test('js/lib/.svn/tmp'); // true

am I missing something? I ended up using the makeRe() since it does work as I expect.

Should this fail?

minimatch.makeRe('*((*.py|*.js)|!(*.json))das*(*.js|!(*.json))')

I get this error:

SyntaxError: Invalid regular expression: /^(?!\.)(?=.)(?:\([^/]*?\.py|[^/]*?\.js)*\|(?:(?!(?:[^/]*?\.json)\das(?:[^/]*?\.js|(?:(?!(?:[^/]*?\.json$)[^/]*?))*)[^/]*?)\)das(?:[^/]*?\.js|(?:(?!(?:[^/]*?\.json)$)[^/]*?))*$/: Unterminated group
    at new RegExp (native)
    at Minimatch.parse (/home/zane/test/node_modules/minimatch/minimatch.js:618:16)
    at Array.map (native)
    at Minimatch.<anonymous> (/home/zane/test/node_modules/minimatch/minimatch.js:174:14)
    at Array.map (native)
    at Minimatch.make (/home/zane/test/node_modules/minimatch/minimatch.js:173:13)
    at new Minimatch (/home/zane/test/node_modules/minimatch/minimatch.js:128:8)
    at Function.minimatch.makeRe (/home/zane/test/node_modules/minimatch/minimatch.js:627:10)
    at repl:1:11
    at REPLServer.defaultEval (repl.js:124:27)

I think it has to do with this code:

   var openParensBefore = nlBefore.split('(').length - 1
    var cleanAfter = nlAfter
    for (i = 0; i < openParensBefore; i++) {
      cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
    }
    nlAfter = cleanAfter

It removes all closing parentheses, even if they encapsulate another group

Globstar breaks if folder names start with .

I suspect this is the same bug as #30 but can't be certain:

var pattern = '**/.DS_Store';

minimatch( '.DS_Store', pattern );      // true
minimatch( 'foo/.DS_Store', pattern );  // true
minimatch( '.foo/.DS_Store', pattern ); // false

Incorrect slash substitution on Windows platform

In minimatch.js, function Minimatch back-slash characters in the pattern get replaced by forward-slashes when running on Windows platform. This isn't necessary since glob requires that only forward-slashes are used in paths. It is also wrong because patterns can contain back-slashes. For example it breaks 'npm help npm' on Windows (no man pages are found) because help.js, line 66 uses a pattern with a back-slash that mustn't be converted to a forward-slash (which is then interpreted as a path separator and breaks the pattern).

I suggest not to convert slashes in minimatch because it would be hard to distinguish slashes in paths from slashes in patterns but to leave path conversion to the caller, e.g.
var manroot = path.resolve(__dirname, "..", "man").split("\\").join("/")
in help.js, line 59.

negative matches unclear

I want to

match "design/**/*"
except "design/templates/*"

maybe something like this could work

"design/!(templates)**/*"

but that's really not clear from the docs.

Directories can contain square brakets

This is continuation of issue, started in gulp-watch. Minimatch translates [ and ] as class pattern, but in fact you can execute mkdir such[dir] and create folder with name that includes brackets. Seems like minimatch is lacking of ability to escape square brackets, because writing \[ does not help.

won't match input containing / correctly

minimatch("_video_", "*video*")   // true
minimatch("/video/", "/video/")   // true
minimatch("/video/", "/video*")   // true
minimatch("/video/", "*video/")   // false ???
minimatch("/video/", "*video*")   // false ???

"**/" pattern doesn't match "./" path part

This seems like a bug to me, intuitively, but I don't see it addressed in the docs anywhere:

var minimatch = require("minimatch");

minimatch("foo/bar.js", "**/foo/**")     // true
minimatch("./foo/bar.js", "./**/foo/**") // true
minimatch("./foo/bar.js", "**/foo/**")   // false

Shouldn't the last example return true because **/ should match ./?

Ref. cowboy/node-globule#11

Invalid ranges cause throw

Invalid ranges like [z-a] are allowed in globs, and interpreted as their literal value, but this module throws.

2.0.8 -> 2.0.9 regression for weird nested *(!(pattern))

The upgrade to 2.0.9 from 2.0.8 (which happened automatically for us on install with gulp -> vinyl-fs -> glob-stream -> minimatch) introduces a failure generating valid regexes for our pattern src/**/*(*.json|!(*.js)). Granted, that pattern is a bit wonky, but it was working before and now it is not.

I have a PR with the test added -- it passes on 2.0.8 but showcases the error in 2.0.9. I didn't pull against your master since it doesn't include a solution, just a failing test.

play-co#1

@isaacs - let me know if you want me to PR this against your master

TypeError when using * in pattern

I'm having trouble using *.txt pattern for matching. Same error seems to apply to any pattern containing * or ?. This is on a Windows system (node 0.69, minimatch 0.1.4, lru-cache 1.0.5):

var mm = require("minimatch");
mm("something.txt", "*.txt");

This results in:

TypeError: Object /^(?!.)(?=.)[^/]*?.txt$/ has no method 'match'
at E:\workdir\node_modules\minimatch\minimatch.js:173:18
at Array.map (native)
at Minimatch.make (E:\jaketest\node_modules\minimatch\minimatch.js:170:13)
at new Minimatch (E:\jaketest\node_modules\minimatch\minimatch.js:108:8)
at minimatch (E:\jaketest\node_modules\minimatch\minimatch.js:74:10)
at repl:1:1
at REPLServer.eval (repl.js:80:21)
at repl.js:190:20
at REPLServer.eval (repl.js:87:5)
at Interface. (repl.js:182:12)

makeRe() doesn't match same things as original object

Example:

var filter = "{*,**/**/**}/foo/{*,**/**/**}";
var path = "c:/aaa/foo/bbb.js";

var mm = new minimatch.Minimatch(filter, {matchBase: true, noext: true});
var re = mm.makeRe();

console.log(mm.match(path));
console.log(path.match(re));

Result:

true
null

The original Minimatch object matches this particular path, but the generated regexp does not.

consider a PR to replace brace expansion?

If you're open to it, I'd like to do a PR to replace the current brace expansion logic with braces.

The primary reason I'd like to make this PR is b/c we use minimatch and glob extensively, so - for selfish reasons - I'm attempting to make it easier for me (and hopefully others) to contribute by modularizing/streamlining some of the code.

I already converted everything locally and all related tests pass. Braces has better test coverage if you want to see those tests as well. I also created some basic benchmarks:

image

I'd be happy to do a PR for your review first if you're open to this.

Add some examples

It would be useful if the readme had a handful of pattern examples at the top (just a few, to illustrate how to do brace expansion, negation, etc). Currently it just dives into very in-depth documentation, but I would guess most people visiting this page are just looking for a reminder of the syntax.

minimatch doesn't match contents of directories

From eslint/eslint#1069.

Unsure if this is intended or not, so opening this just to make sure it's been considered (couldn't find any tests).

.gitignore will match all of the contents of a directory even without a **glob. The following would all be (mostly) equivalent:

foo/bar
foo/bar/
foo/bar/**

This isn't the case for minimatch. The first two will only match the directory itself, while the last one will match all the contents.

Strange context switch around line 215 in make function

I hit this error [TypeError: undefined is not a function] in the Minimatch constructor.

  console.log(this);

  // make the set of regexps etc.
  this.make()  // <-- the bomb is here

around line 165. that log gave me this

{ options: { debug: true, sync: true },
  set: [],
  pattern: './src/jsdoccer.js',
  regexp: null,
  negate: false,
  comment: false,
  empty: false }

fyi, it was called from node-glob.

Glob patterns with `**` are not properly converted to regular expressions

> minimatch('node_modules/foobar/foo.bar', 'node_modules/foobar/**/*.bar')
> true

> var re = minimatch.makeRe('node_modules/foobar/**/*.bar', { nocase: true });
/^(?:(?=.)node_modules\/(?=.)foobar\/(?:(?!(?:\/|^)\.).)*?\/(?!\.)(?=.)[^/]*?\.bar)$/i
> re.test('node_modules/foobar/foo.bar')
false

Backslashes not supported as path separators

If I use minimatch (or glob) with forward slashes in my pattern, everything works as expected. But if I use backslashes as path separators in my pattern, minimatch always returns false -- it never matches anything. This means I can't use path.join to build my pattern string (even though it's an obvious choice), because path.join uses backslashes on Windows.

minimatch should work correctly with patterns that use the current platform's path separator. (It'd be even better if it always accepted either kind of path separator, regardless of the current platform.)

Example:

mm = require('minimatch');

// Simple match. Returns true, as expected.
mm('foo/bar/baz', 'foo/**/baz')

// Same match, but now using path.join.
// Expected: Should return true.
// Actual: returns false (on Windows).
path = require('path');
mm('foo/bar/baz', path.join('foo', '**', 'baz'))

// Equivalent to the previous example.
// Should return true, but instead returns false.
mm('foo/bar/baz', 'foo\\**\\baz')

Fixing this would probably just be a matter of making minimatch normalize the test string to use forward slashes instead of backslashes.

npm ERR! building projects with subdependencies on minimatch in node v0.8.26/OSX

I first encountered this issue in my Travis builds of https://github.com/shutterstock/armrest for node v0.8.26. After installing nvm and v0.8.26, I am able to replicate locally and for multiple other projects.

The thing I cannot figure out about the error is that minimatch@'^0.3.0' as I understand it should match against 0.3.0

npm ERR! Error: No compatible version found: minimatch@'^0.3.0'
npm ERR! Valid install targets:
npm ERR! ["0.0.1","0.0.2","0.0.4","0.0.5","0.1.1","0.1.2","0.1.3","0.1.4","0.1.5","0.2.0","0.2.2","0.2.3","0.2.4","0.2.5","0.2.6","0.2.7","0.2.8","0.2.9","0.2.10","0.2.11","0.2.12","0.2.13","0.2.14","0.3.0"]
npm ERR!     at installTargetsError (/Users/Rubikzube/.nvm/v0.8.26/lib/node_modules/npm/lib/cache.js:719:10)
npm ERR!     at /Users/Rubikzube/.nvm/v0.8.26/lib/node_modules/npm/lib/cache.js:641:10
npm ERR!     at saved (/Users/Rubikzube/.nvm/v0.8.26/lib/node_modules/npm/node_modules/npm-registry-client/lib/get.js:138:7)
npm ERR!     at Object.oncomplete (fs.js:297:15)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <[email protected]>

npm ERR! System Darwin 13.1.0
npm ERR! node -v v0.8.26
npm ERR! npm -v 1.2.30

Match specific files in directory

I'm tying to match particular files in directory

I'm trying to use path/to/directory/{ajax.js,data.js} pattern but doesn't work. Would it be able to use such a patter?

Regex with dot: true does not match original

Please take a look at this:

var minimatch = require('minimatch');

var Minimatch = minimatch.Minimatch

var mm = new Minimatch("a/*/b", {dot: true})
var re = mm.makeRe();

var files = [
  "a/./b",
  "a/../b",
  "a/c/b",
  "a/.d/b"
]

var withRegex = [];

files.forEach(function(file) {
  if (file.match(re)) {
    withRegex.push(file)
  }
})

console.log(withRegex)
// => [ 'a/./b', 'a/../b', 'a/c/b', 'a/.d/b' ]

var withOutRegex = [];

files.forEach(function(file) {
  if (minimatch(file, "a/*/b", {dot: true})) {
    withOutRegex.push(file)
  }
})

console.log(withOutRegex)
// => [ 'a/c/b', 'a/.d/b' ]

And if I understand this correctly, the regex version is actually correct?

Brace expansion does not support number padding

in bash, echo {00..01} => 00 01

in minimatch, mm = new Minimatch('{00..01})' got:

{ options: {},
  set: [ [ '0' ], [ '1' ] ],
  pattern: '{00..01}',
  regexp: null,
  negate: false,
  comment: false,
  empty: false,
  globSet: [ '0', '1' ],
  globParts: [ [ '0' ], [ '1' ] ] }

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.