Coder Social home page Coder Social logo

micromatch / anymatch Goto Github PK

View Code? Open in Web Editor NEW
379.0 13.0 48.0 94 KB

:bangbang: Matches strings against configurable strings, globs, regular expressions, and/or functions

License: ISC License

JavaScript 100.00%
matcher glob match fs micromatch minimatch multimatch node nodejs javascript

anymatch's Introduction

anymatch Build Status Coverage Status

Javascript module to match a string against a regular expression, glob, string, or function that takes the string as an argument and returns a truthy or falsy value. The matcher can also be an array of any or all of these. Useful for allowing a very flexible user-defined config to define things like file paths.

Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.

Usage

npm install anymatch

anymatch(matchers, testString, [returnIndex], [options])

  • matchers: (Array|String|RegExp|Function) String to be directly matched, string with glob patterns, regular expression test, function that takes the testString as an argument and returns a truthy value if it should be matched, or an array of any number and mix of these types.
  • testString: (String|Array) The string to test against the matchers. If passed as an array, the first element of the array will be used as the testString for non-function matchers, while the entire array will be applied as the arguments for function matchers.
  • options: (Object [optional]_) Any of the picomatch options.
    • returnIndex: (Boolean [optional]) If true, return the array index of the first matcher that that testString matched, or -1 if no match, instead of a boolean result.
const anymatch = require('anymatch');

const matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo.js$/, string => string.includes('bar') && string.length > 10 ] ;

anymatch(matchers, 'path/to/file.js'); // true
anymatch(matchers, 'path/anyjs/baz.js'); // true
anymatch(matchers, 'path/to/foo.js'); // true
anymatch(matchers, 'path/to/bar.js'); // true
anymatch(matchers, 'bar.js'); // false

// returnIndex = true
anymatch(matchers, 'foo.js', {returnIndex: true}); // 2
anymatch(matchers, 'path/anyjs/foo.js', {returnIndex: true}); // 1

// any picomatc

// using globs to match directories and their children
anymatch('node_modules', 'node_modules'); // true
anymatch('node_modules', 'node_modules/somelib/index.js'); // false
anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true
anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false
anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true

const matcher = anymatch(matchers);
['foo.js', 'bar.js'].filter(matcher);  // [ 'foo.js' ]
anymatch master* 

anymatch(matchers)

You can also pass in only your matcher(s) to get a curried function that has already been bound to the provided matching criteria. This can be used as an Array#filter callback.

var matcher = anymatch(matchers);

matcher('path/to/file.js'); // true
matcher('path/anyjs/baz.js', true); // 1

['foo.js', 'bar.js'].filter(matcher); // ['foo.js']

Changelog

See release notes page on GitHub

License

ISC

anymatch's People

Contributors

bpasero avatar code0x9 avatar es128 avatar genisysram avatar joscha avatar leonardodino avatar nerdstep avatar paulmillr avatar phated avatar shvaikalesh avatar the1mills avatar wormen 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

anymatch's Issues

Accept regexish strings

I am using anymatch to ignore stuff, I often pass the ignore parameter from CLI, all those cli parameters are parsed as string. It'd be nice to have anymatch convert /*.css/ to regex automatically.

Can this bump micromatch in a minor or patch?

@jonschlinkert @doowb Can this module bump to micromatch 3.x as a minor or patch bump? I believe it's stated that micromatch shouldn't have had any breaking changes.

I bring this up because I'm noticing a ton of duplication in my dependency graph due to this outdated version of micromatch.

Updating micromatch to 3.1.10 to prevent vulnerability

Hi,

There is vulneralibity issue with braces 2.3.0. The fix comes with braces version 2.3.1 or later. Micromatch is using braces and they have already updated their version of braces. Micromatch current version when I'm writing this issue is 3.1.10. This contains the updated version of braces. I noticed that you are currently using 3.1.4 of micromatch. Could you update Anymatch's micromatch version to 3.1.10?

More info about braces vulnerability at https://nodesecurity.io/advisories/786

Anymatch 3.1.3 represents a non backward compatible change and thus should increment the MAJOR version number.

Semver dictates that patch versions only fix issues, and do not add new functionality. It dictates that minor version incrementation represents an additional feature, with no breaking changes to existing APIs. It specifies that breaking, non-backward compatible changes should be reserved for updates that increment the major version only.

[email protected] vs [email protected] handle filepaths completely differently. One will strip trailing paths while the other passes the right on through. This breaks the semver spec above.

An example of a major project that was broken by the above change is brunch/brunch.

Please be aware of this when deciding which part of the version number to increment. The purpose of semver is to allow things like bugfixes and critical security updates to be rolled out in patches so that the prefix sigil "^" in package.json can be used with confidence.

If changes like this are rolled out in patch versions, developers will lose confidence in the automatic update structure of npm, and security holes will remain open in places they otherwise would not.

Please enforce semver when rolling out new releases. Its the responsible thing to do.

checking in...

just checking in to make sure you haven't had any problems with micromatch on gulp-watch/chokidar. feel free to close if not

No way to configure nocase

micromatch has nocase but anymatch doesn't. Would be nice to support options as a third argument, or second argument for currying…

When there is a midline, the result is wrong.

When there is a midline, the result is wrong.

const anymatch = require('anymatch');
const matchers = ['src/abc/**/*'];
anymatch(matchers, 'src/abc/index.js') // true
anymatch(matchers, 'src/abc_def/index.js') // false
anymatch(matchers, 'src/abc-def/index.js') // should be false,  but the result is true

Add an engine section in the package.json

It would be great if it was possible to indicate in the package.json what are the supported versions of this lib. I think right now it is node>=8 but it's not clear.

Falsy negated matcher negates falsy positive matcher but probably shouldn't

Given the following example:

anymatch([`**/*.hbs`], 'components/render/render.spec.js') // false
anymatch([`**/*.hbs`, `!**/*.config.hbs`], 'components/render/render.spec.js') // true

I would expect anymatch to return false for the second call but it returns true.

Note that this returned false for both calls in v2.0.0 but returns true for the second in v3.1.1. Not sure if this is an intentional breaking change or not. If it is, how can I accomplish the matching logic given in the example?

instanceof RegExp is not reliable

I have an API that runs in nodejs, and regexp matchers fail to run properly. I figured something is making instanceof RegExp to fail. If I do the following from the cli:

node
> anymatch([/conv/], 'conversations') // => true

everything is working as intended, but in the app console:

> anymatch([/conv/], 'conversations') // => false

I managed to isolate the issue to this line:

if (matcher instanceof RegExp) {

it seems like that is producing false even if it is a regexp. So what I did was install another small lib, 'kind-of' and do this on that line and everything works fine again.

// from this ...
if (matcher instanceof RegExp) { //...
// to ...
if (kindOf(matcher) === 'regexp') { //...

This resolves that issue.

I know this issue is not related to the lib per se, but I have tried to isolate code in the API and it seems like there is something deep in some lib in npm that is causing this issue on the RegExp class. It seems time wasting and futile to try and correct it that way, rather than make this lib detect the regexp another way. Will update if I somehow find out what is causing it, coz that in itself is a huge issue that something is messing with the Regexp prototype and causing this issue.
Note that most of the libs used in the backend and frontend are similar, and anymatch runs well in the browser ( we share code in the back and front ends of the whole stack) in which anymatch is used. So this leaves server specific libs faulty, of which there is nothing we are doing to mess with the Regxp prototype.

However, the reason why I am letting you guys know about this is that this lib may suffer with this bug just because of other libs that mess that prototype, meaning it could probably be common in many apps and people just don't know this as the cause. So instead, this lib should just avoid that pitfall and use another way to detect regexps, or just directly do this in this lib:

// shamelessly steal this util function to this lib 😉 beauty of open-source
function isRegexp(val) {
  if (val instanceof RegExp) return true;
  return typeof val.flags === 'string'
    && typeof val.ignoreCase === 'boolean'
    && typeof val.multiline === 'boolean'
    && typeof val.global === 'boolean';
}

// then use it on that offending line
if (isRegexp(matcher)) { //...

From the above code in kind-of, it clearly shows that, yes, they understood that instanceof is not perfect, it will fall through somehow and they then make it brutally get the type by checking known RegExp props. This modification will not impact performance under normal circumstances, just that it will make this lib more RELIABLE, though it will take just a few lines of performance hit when RegExp prototype is not working correctly with instanceof.

Matchers with an opening parenthesis do not work.

Matchers with an opening parenthesis do not work.

const anymatch = require('anymatch');

console.log(anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js')); // true

console.log(anymatch('**/node_modules(/**', '/absolute/path/to/node_modules(/somelib/index.js')); // I expect true but get false.

The only difference between the two anymatch() calls is that I added an opening parenthesis after "node_modules".

I have tried escaping the opening parenthesis with a \, but that didn't help.

resolve slash confusion on win32

when testing against regexes or strings on win32, try the path provided as well as a copy where backslashes are replaced with forward slashes

Travis Error: Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch

Just got this error in our Travis build from fetching micromatch, a dependency for anymatch (which is required in our build form karma)

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) fatal: ambiguous argument '2.3.0': unknown revision or path not in the working tree.

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) Use '--' to separate paths from revisions, like this:

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) 'git <command> [<revision>...] -- [<file>...]'

npm ERR! Failed resolving git HEAD (https://github.com/jonschlinkert/micromatch) 

This issue probably do not belong here, but I put it here for others to be aware of the issue

Could this be a version mismatch at your end, or is this a result of bad dep version range in a dependency?

Ref: micromatch/micromatch#46

Looking for anti-match / not-match ability

Re: paulmillr/chokidar#569

I am looking for a way to only match any file in my project that ends with with .tsx

however, it looks like chokidar only supports and ignored option.

so should mean that I need to ignore anything that does not match /\.tsx$/

can this be achieved with anymatch? Hope the question makes sense, thanks

String with tailing slash won't match self

Example:

> const anymatch = require('anymatch');
undefined
> var aaa = '/api/ad/union/sdk/get_ads/'
undefined
> anymatch([aaa], aaa)
false
> aaa = '/api/ad/union/sdk/getads/'
'/api/ad/union/sdk/getads/'
> anymatch([aaa], aaa)
false
> aaa = '/api/ad/union/sdk/getads'
'/api/ad/union/sdk/getads'
> anymatch([aaa], aaa)
true

Typescript doesn't like the types shipped with the module

The index.d.ts doesn't seem to play nice with Typescript v3.4.1. It results in the following errors:

Screen Shot 2019-04-16 at 3 58 13 PM

node_modules/anymatch/index.d.ts:5:20 - error TS7051: Parameter has a name but no type. Did you mean 'arg0: string'?

5 type AnymatchFn = (string) => boolean;
                     ~~~~~~

node_modules/anymatch/index.d.ts:8:73 - error TS2314: Generic type 'Array<T>' requires 1 type argument(s).

8 declare function anymatch(matchers: AnymatchMatcher, testString: string|Array, returnIndex?: boolean): boolean;
                                                                          ~~~~~

node_modules/anymatch/index.d.ts:9:75 - error TS2314: Generic type 'Array<T>' requires 1 type argument(s).

9 declare function anymatch(matchers: AnymatchMatcher): (testString: string|Array, returnIndex?: boolean) => number;
                                                                            ~~~~~

dot in testString as pathname or filename, can't match

use case is that, first new a matcher in anymatch, 2nd use the matcher to match teststring.
if teststring is path string and some path or file has dot symbol, will match failed, the example at flow:

const matcher = anymatch(["**/node_modules/**"]);
const str = "abs/node_modules/.path/file.js";
const str2 = "abs/node_modules/.file.js";
const result = matcher(str); // false
const result2 = matcher(str2); // false

then i review the source code of anymatch, and i found a solution:

const matcher = anymatch(["**/node_modules/**"], null, {dot: true});
const str = "abs/node_modules/.path/file.js";
const str2 = "abs/node_modules/.file.js";
const result = matcher(str); // true  // ts checker error
const result2 = matcher(str2); // true // ts checker error

but if this code is in ts, the ide tell me an error of checker at the line that match the test string, because anymatch/index.d.ts dosn't have this override, so we should add a comment to tell checker to ignore this line.

const matcher = anymatch(["**/node_modules/**"], null, {dot: true});
const str = "abs/node_modules/.path/file.js";
const str2 = "abs/node_modules/.file.js";
// @ts-ignore
const result = matcher(str); // true
// @ts-ignore
const result2 = matcher(str2); // true

pls include example of ignoring directory

Classic use case is to ignore any contents of any node_modules directory, where they may be many of these directories in a project.

For use with chokidar, I simply cannot say whether this:

const opts ={
  ignored: ['node_modules']
}

will ignore just the top-level node_modules dir, or any node_modules dir?
can this be documented with anymatch?

thank you!

Can't use Picomatch options with returnIndex in TypeScript

I was trying to do something like this:

const processorIndex = anymatch(this.processorGlobs, relativePath, {
    dot: true,
    returnIndex: true
});

But I get the following error:

error TS2345: Argument of type '{ dot: true; returnIndex: boolean; }' is not assignable to parameter of type 'true | PicomatchOptions'.
  Object literal may only specify known properties, and 'returnIndex' does not exist in type 'PicomatchOptions'.

26             returnIndex: true
               ~~~~~~~~~~~~~~~~~


Found 1 error.

I think the typings should be changed to allow this, e.g.:

-(matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number;
+(matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions & { returnIndex?: boolean }): number;

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.