• Stars
    star
    393
  • Rank 108,876 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 11 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🔍 node-ignore is the manager and filter for .gitignore rules, the one used by eslint, prettier and many others.
Linux OS X Windows Coverage Downloads
Build Status Windows Build Status Coverage Status npm module downloads per month

ignore

ignore is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore spec 2.22.1.

ignore is used by eslint, gitbook and many others.

Pay ATTENTION that minimatch (which used by fstream-ignore) does not follow the gitignore spec.

To filter filenames according to a .gitignore file, I recommend this npm package, ignore.

To parse an .npmignore file, you should use minimatch, because an .npmignore file is parsed by npm using minimatch and it does not work in the .gitignore way.

Tested on

ignore is fully tested, and has more than five hundreds of unit tests.

  • Linux + Node: 0.8 - 7.x
  • Windows + Node: 0.10 - 7.x, node < 0.10 is not tested due to the lack of support of appveyor.

Actually, ignore does not rely on any versions of node specially.

Since 4.0.0, ignore will no longer support node < 6 by default, to use in node < 6, require('ignore/legacy'). For details, see CHANGELOG.

Table Of Main Contents

Install

npm i ignore

Usage

import ignore from 'ignore'
const ig = ignore().add(['.abc/*', '!.abc/d/'])

Filter the given paths

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

As the filter function

paths.filter(ig.createFilter()); // ['.abc/d/e.js']

Win32 paths will be handled

ig.filter(['.abc\\a.js', '.abc\\d\\e.js'])
// if the code above runs on windows, the result will be
// ['.abc\\d\\e.js']

Why another ignore?

  • ignore is a standalone module, and is much simpler so that it could easy work with other programs, unlike isaacs's fstream-ignore which must work with the modules of the fstream family.

  • ignore only contains utility methods to filter paths according to the specified ignore rules, so

    • ignore never try to find out ignore rules by traversing directories or fetching from git configurations.
    • ignore don't cares about sub-modules of git projects.
  • Exactly according to gitignore man page, fixes some known matching issues of fstream-ignore, such as:

    • '/*.js' should only match 'a.js', but not 'abc/a.js'.
    • '**/foo' should match 'foo' anywhere.
    • Prevent re-including a file if a parent directory of that file is excluded.
    • Handle trailing whitespaces:
      • 'a '(one space) should not match 'a '(two spaces).
      • 'a \ ' matches 'a '
    • All test cases are verified with the result of git check-ignore.

Methods

.add(pattern: string | Ignore): this

.add(patterns: Array<string | Ignore>): this

  • pattern String | Ignore An ignore pattern string, or the Ignore instance
  • patterns Array<String | Ignore> Array of ignore patterns.

Adds a rule or several rules to the current manager.

Returns this

Notice that a line starting with '#'(hash) is treated as a comment. Put a backslash ('\') in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename.

ignore().add('#abc').ignores('#abc')    // false
ignore().add('\\#abc').ignores('#abc')   // true

pattern could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just ignore().add() the content of a ignore file:

ignore()
.add(fs.readFileSync(filenameOfGitignore).toString())
.filter(filenames)

pattern could also be an ignore instance, so that we could easily inherit the rules of another Ignore instance.

.addIgnoreFile(path)

REMOVED in 3.x for now.

To upgrade [email protected] up to 3.x, use

import fs from 'fs'

if (fs.existsSync(filename)) {
  ignore().add(fs.readFileSync(filename).toString())
}

instead.

.filter(paths: Array<Pathname>): Array<Pathname>

type Pathname = string

Filters the given array of pathnames, and returns the filtered array.

  • paths Array.<Pathname> The array of pathnames to be filtered.

Pathname Conventions:

1. Pathname should be a path.relative()d pathname

Pathname should be a string that have been path.join()ed, or the return value of path.relative() to the current directory,

// WRONG, an error will be thrown
ig.ignores('./abc')

// WRONG, for it will never happen, and an error will be thrown
// If the gitignore rule locates at the root directory,
// `'/abc'` should be changed to `'abc'`.
// ```
// path.relative('/', '/abc')  -> 'abc'
// ```
ig.ignores('/abc')

// WRONG, that it is an absolute path on Windows, an error will be thrown
ig.ignores('C:\\abc')

// Right
ig.ignores('abc')

// Right
ig.ignores(path.join('./abc'))  // path.join('./abc') -> 'abc'

In other words, each Pathname here should be a relative path to the directory of the gitignore rules.

Suppose the dir structure is:

/path/to/your/repo
    |-- a
    |   |-- a.js
    |
    |-- .b
    |
    |-- .c
         |-- .DS_store

Then the paths might be like this:

[
  'a/a.js'
  '.b',
  '.c/.DS_store'
]

2. filenames and dirnames

node-ignore does NO fs.stat during path matching, so for the example below:

// First, we add a ignore pattern to ignore a directory
ig.add('config/')

// `ig` does NOT know if 'config', in the real world,
//   is a normal file, directory or something.

ig.ignores('config')
// `ig` treats `config` as a file, so it returns `false`

ig.ignores('config/')
// returns `true`

Specially for people who develop some library based on node-ignore, it is important to understand that.

Usually, you could use glob with option.mark = true to fetch the structure of the current directory:

import glob from 'glob'

glob('**', {
  // Adds a / character to directory matches.
  mark: true
}, (err, files) => {
  if (err) {
    return console.error(err)
  }

  let filtered = ignore().add(patterns).filter(files)
  console.log(filtered)
})

.ignores(pathname: Pathname): boolean

new in 3.2.0

Returns Boolean whether pathname should be ignored.

ig.ignores('.abc/a.js')    // true

.createFilter()

Creates a filter function which could filter an array of paths with Array.prototype.filter.

Returns function(path) the filter function.

.test(pathname: Pathname) since 5.0.0

Returns TestResult

interface TestResult {
  ignored: boolean
  // true if the `pathname` is finally unignored by some negative pattern
  unignored: boolean
}
  • {ignored: true, unignored: false}: the pathname is ignored
  • {ignored: false, unignored: true}: the pathname is unignored
  • {ignored: false, unignored: false}: the pathname is never matched by any ignore rules.

static ignore.isPathValid(pathname): boolean since 5.0.0

Check whether the pathname is an valid path.relative()d path according to the convention.

This method is NOT used to check if an ignore pattern is valid.

ignore.isPathValid('./foo')  // false

ignore(options)

options.ignorecase since 4.0.0

Similar as the core.ignorecase option of git-config, node-ignore will be case insensitive if options.ignorecase is set to true (the default value), otherwise case sensitive.

const ig = ignore({
  ignorecase: false
})

ig.add('*.png')

ig.ignores('*.PNG')  // false

options.ignoreCase?: boolean since 5.2.0

Which is alternative to options.ignoreCase

options.allowRelativePaths?: boolean since 5.2.0

This option brings backward compatibility with projects which based on [email protected]. If options.allowRelativePaths is true, ignore will not check whether the given path to be tested is path.relative()d.

However, passing a relative path, such as './foo' or '../foo', to test if it is ignored or not is not a good practise, which might lead to unexpected behavior

ignore({
  allowRelativePaths: true
}).ignores('../foo/bar.js') // And it will not throw

Upgrade Guide

Upgrade 4.x -> 5.x

Since 5.0.0, if an invalid Pathname passed into ig.ignores(), an error will be thrown, unless options.allowRelative = true is passed to the Ignore factory.

While ignore < 5.0.0 did not make sure what the return value was, as well as

.ignores(pathname: Pathname): boolean

.filter(pathnames: Array<Pathname>): Array<Pathname>

.createFilter(): (pathname: Pathname) => boolean

.test(pathname: Pathname): {ignored: boolean, unignored: boolean}

See the convention here for details.

If there are invalid pathnames, the conversion and filtration should be done by users.

import {isPathValid} from 'ignore' // introduced in 5.0.0

const paths = [
  // invalid
  //////////////////
  '',
  false,
  '../foo',
  '.',
  //////////////////

  // valid
  'foo'
]
.filter(isValidPath)

ig.filter(paths)

Upgrade 3.x -> 4.x

Since 4.0.0, ignore will no longer support node < 6, to use ignore in node < 6:

var ignore = require('ignore/legacy')

Upgrade 2.x -> 3.x

  • All options of 2.x are unnecessary and removed, so just remove them.
  • ignore() instance is no longer an EventEmitter, and all events are unnecessary and removed.
  • .addIgnoreFile() is removed, see the .addIgnoreFile section for details.

Collaborators

More Repositories

1

shell-safe-rm

😎 Safe-rm: A drop-in and much safer replacement of bash rm with nearly full functionalities and options of the rm command! Safe-rm will act exactly the same as the original rm command.
Shell
379
star
2

skema

🛰 Skema provides a handy & composable way to validate / transform / purify the input data.
JavaScript
359
star
3

node-comment-json

Parse and stringify JSON with comments. It will retain comments even when after saved!
JavaScript
138
star
4

stock-pandas

🚀 The production-ready subclass of `pandas.DataFrame` to support stock statistics and indicators
Python
114
star
5

penteract-ocr

⭐️ The native node.js bindings to the Tesseract OCR project.
C++
108
star
6

neuron.js

:shipit: A Full Feature CommonJS Module Manager, Dependency Graph Handler and Loader for Browsers
JavaScript
63
star
7

ctrip-apollo

The most delightful and handy Node.js client for ctrip apollo configuration service.
JavaScript
56
star
8

finmath

The collections of simple, weighted, exponential, smoothed moving averages.
JavaScript
53
star
9

egg-wechat-pay

Wechat pay plugin for egg(WIP)
JavaScript
34
star
10

DA-RNN-in-Tensorflow-2-and-PyTorch

A Tensorflow 2 (Keras) implementation of DA-RNN (A Dual-Stage Attention-Based Recurrent Neural Network for Time Series Prediction, arXiv:1704.02971)
Jupyter Notebook
26
star
11

node-dubbo

Dubbo client for node.
JavaScript
25
star
12

moving-averages

The collections of simple, weighted, exponential, smoothed moving averages.
JavaScript
23
star
13

macd

FinTech utility to calculate MACD, the Moving Average Convergence / Divergence.
JavaScript
22
star
14

b2a

btoa and atob support for node.js or old browsers, with the Unicode Problems fixed
JavaScript
20
star
15

document

Create your document site by one command.
CSS
19
star
16

bollinger-bands

Utilities to draw and calculate bollinger bands
JavaScript
19
star
17

express-to-koa

Use express middlewares in Koa2, the one that really works.
JavaScript
19
star
18

node-glob-gitignore

Extends `glob` with support for filtering files according to gitignore rules and exposes an optional Promise API
JavaScript
16
star
19

git-cloc

Count Lines of Code for Git
Shell
14
star
20

node-fs-sync

Synchronous fs with more fun
JavaScript
13
star
21

cert-manager-webhook-dnspod

Cert-manager webhook for DNSPod
Go
12
star
22

dianping-bootcamp-summer-2013

Resources, homework, and discussion
JavaScript
11
star
23

python-aioretry

Asyncio retry utility for Python 3.7+
Python
10
star
24

node-argv-split

Split argv(argument vector) and handle special cases.
JavaScript
10
star
25

node-scaffold-generator

Generates a repo from a specified template and data.
JavaScript
10
star
26

helm-stable-charts-mirror

国内镜像 A mirror of helm stable charts, the drop-in replacement of https://kubernetes-charts.storage.googleapis.com
JavaScript
9
star
27

178manga-reader

你,懂的!Manga reader!
JavaScript
9
star
28

egg-snowflake

Egg plugin to generate unique and increased twitter-snowflake uuid.
JavaScript
8
star
29

node-socket-pool

Persistent socket connections with pool for node server side.
JavaScript
8
star
30

easing-functions

Robert Penner's easing functions
JavaScript
8
star
31

comfort-legacy

Comfort is a much better node.js commander solution for sub commands, such as `git xxx` or `npm xxx`
JavaScript
7
star
32

node-json-parser

JSON parser to parse JSON object and MAINTAIN comments.
JavaScript
7
star
33

stock-pandas-examples

Examples for stock-pandas
Jupyter Notebook
6
star
34

node-finmath

Fintech mathematics
JavaScript
6
star
35

ngx

Data-driven nginx configuration manager.
JavaScript
5
star
36

node-code-stringify

The node.js module that converts JavaScript variables into source codes. Unlike `JSON.stringify`, code-stringify also deals with reference(object) types of variables.
JavaScript
5
star
37

node-semver-extra

semver-extra contains methods that aren't included in the vanilla semver package.
JavaScript
5
star
38

node-commonjs-walker

Analyzer and tree walker for commonjs
JavaScript
5
star
39

bot-state-machine

Finite state machine for chat bot
JavaScript
5
star
40

node-engine-x

engine-x, nginx the node version.
JavaScript
4
star
41

node-semver-stable

Manage stable semver versions
JavaScript
4
star
42

node-modified

Modified is a simple request client to deal with http local cache.
JavaScript
4
star
43

hippo

Simple analytics client.
JavaScript
4
star
44

stock-charts

Stock charts based on D3(STILL WORKING IN PROGRESS)
JavaScript
4
star
45

aya

Just a wrapped tap, more fun.
JavaScript
3
star
46

lua-gaia

Gaia, the NginX cache addons in Lua based on OpenResty.
Harbour
3
star
47

gaia

Gaia, the framework to make gRPC services
JavaScript
3
star
48

generator-py

Yeoman generator to create a python project with test/coverage ready
Python
3
star
49

promise-faker

Provides promise-like APIs but does the synchronous things.
JavaScript
3
star
50

node-array-timsort

Fast JavaScript array sorting by implementing Python's Timsort algorithm
JavaScript
3
star
51

node-typo

typo is an extendable template engine designed for the future
JavaScript
3
star
52

node-ambassador

Ambassador provides a way to communicate between node.js processes
JavaScript
3
star
53

Kubernetes-Tips

Tips for usage of kubernetes and helm
3
star
54

error-stack

Parse and manipulate error-stack
JavaScript
3
star
55

node-ssh-url

Utilities to resolute and parse ssh url.
JavaScript
3
star
56

node-hashed-fs

Handle file system with content hashing
JavaScript
3
star
57

vue-stock-chart

Vue stock chart component
JavaScript
3
star
58

node-home

Resolves home directories, `resolve('~/path/to')`
JavaScript
3
star
59

atta

Server-side UI rendering framework in Go
2
star
60

node-candlesticks

The thing to manage candlesticks
JavaScript
2
star
61

docker-image-futuopend

Docker image for FutuOpenD
Dockerfile
2
star
62

node-time-spans

Time spans especially for financial technology.
JavaScript
2
star
63

atta.js

(WIP) The node graphics library
JavaScript
2
star
64

tpl

A simple JavaScript template engine
JavaScript
2
star
65

node-util-inherits

node util.inherits with compatibility
JavaScript
2
star
66

contenthash-html-webpack-plugin

Makes [contenthash] available for html-webpack-plugin
JavaScript
2
star
67

node-math-array

Math utility to calculate with two arrays.
JavaScript
2
star
68

promise.extra

Promise.series, Promise.waterfall with vanilla Promise.
JavaScript
2
star
69

node-deferrer

Deferrer is a fast node.js promise-object generator.
JavaScript
2
star
70

node-fs-expand

An extended fs glob
JavaScript
2
star
71

node-err-object

Custom error object.
JavaScript
2
star
72

s-deviation

Utility to calculate standard deviation.
JavaScript
2
star
73

node-githuburl

Parse a github repo url into an object of repo information and convert to several types of clone URL.
JavaScript
2
star
74

node-tmp-sync

The sync version of tmp just for test cases, making it much easier.
JavaScript
2
star
75

graceful-instanceof

The instanceof mechanism cross package/module versions.
JavaScript
2
star
76

git-perm-rm

Permanently remove a file or directory from a git repo.
Shell
2
star
77

node-logical-promise

Javascript logical operators on Promises
JavaScript
2
star
78

babel-transform-dir

Transforms javascript files within a directory by babel, and expose a Promise API.
JavaScript
2
star
79

node-ip-address

Get the local ip address
JavaScript
2
star
80

node-cookie-store

An RFC-6265 cookie store to implement the mechanism of HTTP cookie and Set-Cookie header fields as a browser does.
JavaScript
2
star
81

node-object-access

Access(read and write) an object hierachically.
JavaScript
2
star
82

node-ocr

Optical character recognition for node.js
JavaScript
2
star
83

node-rar

Node utility and command-line tool to pack and unpack rar files.
JavaScript
2
star
84

js-bridge

A JavaScript bridge for sending messages between JavaScript and native code(Obj-C/Java) in WebViews.
Shell
2
star
85

node-nodeinit

Creates a most frequent scaffold of your node.js project for the first commit.
JavaScript
2
star
86

modified-lru-cache

Lru-cache for `modified`: npmjs.org/package/modified
JavaScript
1
star
87

module-walker

JavaScript module traverser
JavaScript
1
star
88

node-print-code

Print visualized slice of code from its content, line and column for CLI
JavaScript
1
star
89

node-xconfig

Node.js Configurations
JavaScript
1
star
90

weixin-auth

Wechat authorization
JavaScript
1
star
91

neuron-cli

Command line tools for neuron
JavaScript
1
star
92

nginx-ingress-controller

Just wrap the original nginx-ingress-controller for cloud registry
Dockerfile
1
star
93

tiller

Rewrap the gcr.io/kubernetes-helm/tiller to cross the wall
Shell
1
star
94

p-async-cache

Cache the async promise lookups and avoid fetching the same thing more than necessary.
JavaScript
1
star
95

cortex-dashboard

GUI dashboard to play with [cortex](https://github.com/kaelzhang/cortex)
1
star
96

model

JavaScript
1
star
97

node-booker

Booker is a lovely logger for node.js which is SMART, SMALL, and EASY-TO-USE.
JavaScript
1
star
98

creeper

Creepy spider
1
star
99

egg-ctrip-apollo

Egg plugin for Ctrip's apollo configuration service
JavaScript
1
star
100

node-asks

A collection of common interactive command line user interfaces. An altered version of inquirer.js
JavaScript
1
star