Manager and filter for .gitignore rules, providing comprehensive gitignore-style pattern matching for file filtering.
npx @tessl/cli install tessl/npm-ignore@7.0.00
# Ignore
1
2
Ignore is a manager, filter and parser for .gitignore rules implemented in pure JavaScript according to the .gitignore specification 2.22.1. It provides comprehensive gitignore-style pattern matching for file filtering and is widely used by tools like ESLint, Gitbook, and many others.
3
4
## Package Information
5
6
- **Package Name**: ignore
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install ignore`
10
11
## Core Imports
12
13
```javascript
14
import ignore from 'ignore';
15
```
16
17
For CommonJS:
18
19
```javascript
20
const ignore = require('ignore');
21
```
22
23
For TypeScript with named imports:
24
25
```typescript
26
import ignore, { isPathValid } from 'ignore';
27
```
28
29
Named import for the main function (alternative syntax):
30
31
```typescript
32
import { default as ignore, isPathValid } from 'ignore';
33
```
34
35
## Basic Usage
36
37
```javascript
38
import ignore from 'ignore';
39
40
// Create an ignore instance
41
const ig = ignore().add(['.abc/*', '!.abc/d/']);
42
43
// Test individual paths
44
console.log(ig.ignores('.abc/a.js')); // true (ignored)
45
console.log(ig.ignores('.abc/d/e.js')); // false (not ignored due to negation)
46
47
// Filter arrays of paths
48
const paths = ['.abc/a.js', '.abc/d/e.js', 'other.js'];
49
const filtered = ig.filter(paths);
50
console.log(filtered); // ['.abc/d/e.js', 'other.js']
51
52
// Use as filter function
53
const nonIgnored = paths.filter(ig.createFilter());
54
```
55
56
## Architecture
57
58
The ignore package is built around several key components:
59
60
- **Factory Function**: The main `ignore()` function creates new Ignore instances with optional configuration
61
- **Rule Management**: Internal parsing and compilation of gitignore patterns into regex-based rules
62
- **Path Matching**: Efficient path testing against compiled rules with support for negation and hierarchy
63
- **Caching System**: Built-in result caching for improved performance on repeated path checks
64
- **Platform Support**: Automatic Windows path normalization and configurable case sensitivity
65
66
## Capabilities
67
68
### Factory and Configuration
69
70
Creates new ignore manager instances with optional configuration.
71
72
```javascript { .api }
73
/**
74
* Creates a new ignore manager instance
75
* @param options - Configuration options for the ignore instance
76
* @returns Ignore instance for managing gitignore rules
77
*/
78
function ignore(options?: Options): Ignore;
79
80
/**
81
* Legacy compatibility property (anti-pattern)
82
* @deprecated Use ignore() directly instead
83
*/
84
ignore.default: typeof ignore;
85
86
interface Options {
87
/** Case insensitive matching (default: true) */
88
ignorecase?: boolean;
89
/** Alternative name for ignorecase */
90
ignoreCase?: boolean;
91
/** Allow relative paths like './foo' (default: false) */
92
allowRelativePaths?: boolean;
93
}
94
```
95
96
**Usage Examples:**
97
98
```javascript
99
// Default case-insensitive behavior
100
const ig1 = ignore();
101
102
// Case-sensitive matching
103
const ig2 = ignore({ ignorecase: false });
104
105
// Allow relative paths (not recommended)
106
const ig3 = ignore({ allowRelativePaths: true });
107
```
108
109
### Pattern Management
110
111
Add ignore patterns to the manager using various input formats.
112
113
```javascript { .api }
114
/**
115
* Adds one or several rules to the current manager
116
* @param patterns - Pattern(s) to add - can be strings, arrays, or other ignore instances
117
* @returns The ignore instance for chaining
118
*/
119
add(patterns: string | Ignore | readonly (string | Ignore)[] | PatternParams): this;
120
121
/**
122
* Legacy alias for add method
123
* @param pattern - Pattern to add
124
* @returns The ignore instance for chaining
125
*/
126
addPattern(pattern: string | Ignore | readonly (string | Ignore)[]): this;
127
128
interface PatternParams {
129
/** The ignore pattern string */
130
pattern: string;
131
/** Optional marker for pattern tracking (e.g., line number) */
132
mark?: string;
133
}
134
```
135
136
**Usage Examples:**
137
138
```javascript
139
// Add single pattern
140
ig.add('*.log');
141
142
// Add multiple patterns
143
ig.add(['*.log', 'temp/', '!important.log']);
144
145
// Add from file content
146
ig.add(fs.readFileSync('.gitignore', 'utf8'));
147
148
// Add with marker for debugging
149
ig.add({ pattern: 'debug/*', mark: 'line:15' });
150
151
// Add another ignore instance
152
const baseIgnore = ignore().add('*.tmp');
153
ig.add(baseIgnore);
154
155
// Legacy addPattern method (use add() instead)
156
ig.addPattern('*.log');
157
ig.addPattern(['*.log', 'temp/']);
158
159
// Chaining
160
const ig = ignore()
161
.add('*.log')
162
.add('temp/')
163
.add('!important.log');
164
```
165
166
### Path Testing
167
168
Test individual paths against ignore rules with detailed results.
169
170
```javascript { .api }
171
/**
172
* Tests if a pathname should be ignored
173
* @param pathname - Relative path to test
174
* @returns Boolean indicating if path is ignored
175
*/
176
ignores(pathname: Pathname): boolean;
177
178
/**
179
* Tests path and returns detailed result including rule information
180
* @param pathname - Relative path to test
181
* @returns TestResult with ignored/unignored status and matching rule
182
*/
183
test(pathname: Pathname): TestResult;
184
185
/**
186
* Git check-ignore equivalent debugging method
187
* @param pathname - Relative path to test
188
* @returns TestResult for debugging ignore rules
189
*/
190
checkIgnore(pathname: Pathname): TestResult;
191
192
type Pathname = string;
193
194
interface TestResult {
195
/** Whether path is ignored */
196
ignored: boolean;
197
/** Whether path is unignored by negative pattern */
198
unignored: boolean;
199
/** The rule that matched (if any) */
200
rule?: IgnoreRule;
201
}
202
203
interface IgnoreRule {
204
/** Original pattern string */
205
pattern: string;
206
/** Optional marker (e.g., line number) */
207
mark?: string;
208
/** Whether this is a negation pattern */
209
negative: boolean;
210
}
211
```
212
213
**Usage Examples:**
214
215
```javascript
216
const ig = ignore().add(['*.log', '!important.log']);
217
218
// Simple boolean test
219
console.log(ig.ignores('debug.log')); // true
220
console.log(ig.ignores('important.log')); // false
221
222
// Detailed test result
223
const result = ig.test('debug.log');
224
console.log(result.ignored); // true
225
console.log(result.unignored); // false
226
console.log(result.rule); // { pattern: '*.log', negative: false }
227
228
// Check ignore for debugging (like git check-ignore -v)
229
const debugResult = ig.checkIgnore('temp/');
230
if (debugResult.ignored) {
231
console.log(`Ignored by rule: ${debugResult.rule.pattern}`);
232
}
233
```
234
235
### Path Filtering
236
237
Filter arrays of paths to remove ignored entries.
238
239
```javascript { .api }
240
/**
241
* Filters array of pathnames, removing ignored paths
242
* @param pathnames - Array of relative paths to filter
243
* @returns Filtered array containing only non-ignored paths
244
*/
245
filter(pathnames: readonly Pathname[]): Pathname[];
246
247
/**
248
* Creates filter function for use with Array.prototype.filter
249
* @returns Filter function that returns true for non-ignored paths
250
*/
251
createFilter(): (pathname: Pathname) => boolean;
252
```
253
254
**Usage Examples:**
255
256
```javascript
257
const ig = ignore().add(['*.log', 'temp/', '!important.log']);
258
259
const allFiles = [
260
'app.js',
261
'debug.log',
262
'important.log',
263
'temp/cache.tmp',
264
'src/index.js'
265
];
266
267
// Direct filtering
268
const kept = ig.filter(allFiles);
269
console.log(kept); // ['app.js', 'important.log', 'src/index.js']
270
271
// Using createFilter with Array methods
272
const filterFn = ig.createFilter();
273
const keptFiles = allFiles.filter(filterFn);
274
275
// Chaining with other array methods
276
const jsFiles = allFiles
277
.filter(ig.createFilter())
278
.filter(file => file.endsWith('.js'));
279
```
280
281
### Path Validation
282
283
Utility function to validate pathname format according to ignore conventions.
284
285
```javascript { .api }
286
/**
287
* Validates if pathname is a proper relative path according to ignore conventions
288
* @param pathname - Path string to validate
289
* @returns Boolean indicating if path format is valid
290
*/
291
function isPathValid(pathname: string): boolean;
292
```
293
294
**Usage Examples:**
295
296
```javascript
297
import { isPathValid } from 'ignore';
298
299
console.log(isPathValid('src/app.js')); // true
300
console.log(isPathValid('./src/app.js')); // false (relative prefix not allowed)
301
console.log(isPathValid('/src/app.js')); // false (absolute path not allowed)
302
console.log(isPathValid('')); // false (empty string not allowed)
303
304
// Validate before processing
305
const paths = ['src/app.js', './config.js', '/tmp/file.txt']
306
.filter(isPathValid);
307
// Result: ['src/app.js']
308
```
309
310
## Error Handling
311
312
The ignore package throws errors for invalid inputs:
313
314
- **TypeError**: When path is not a string or is empty
315
- **RangeError**: When path is not properly relativized (contains `./`, `../`, or is absolute)
316
317
```javascript
318
const ig = ignore();
319
320
try {
321
ig.ignores('/absolute/path'); // Throws RangeError
322
} catch (error) {
323
console.error(error.message); // "path should be a `path.relative()`d string"
324
}
325
326
try {
327
ig.ignores(''); // Throws TypeError
328
} catch (error) {
329
console.error(error.message); // "path must not be empty"
330
}
331
```
332
333
## Pattern Syntax
334
335
The ignore package follows the official .gitignore specification:
336
337
```javascript
338
const ig = ignore().add([
339
// Basic patterns
340
'*.log', // All .log files
341
'temp/', // Directory temp/ and contents
342
'/config', // Only config in root
343
344
// Wildcards
345
'cache/*', // Files directly in cache/
346
'cache/**', // All files under cache/ recursively
347
'cache/**/debug', // debug files anywhere under cache/
348
349
// Negation
350
'!important.log', // Don't ignore important.log
351
'*.tmp', // Ignore .tmp files
352
'!cache/*.tmp', // But keep .tmp files in cache/
353
354
// Character ranges
355
'temp[0-9].txt', // temp0.txt through temp9.txt
356
357
// Escaping
358
'\\#notes.txt', // Literal # character
359
'\\ spaced\\ file', // File with spaces
360
]);
361
```
362
363
## Platform Considerations
364
365
### Windows Path Handling
366
367
The package automatically handles Windows paths:
368
369
```javascript
370
const ig = ignore().add('temp/*');
371
372
// These are equivalent on Windows:
373
ig.ignores('temp/file.txt'); // true
374
ig.ignores('temp\\file.txt'); // true (automatically converted)
375
```
376
377
### Case Sensitivity
378
379
Configure case sensitivity based on filesystem:
380
381
```javascript
382
// Case insensitive (default - good for Windows/macOS)
383
const ig1 = ignore().add('*.TXT');
384
console.log(ig1.ignores('file.txt')); // true
385
386
// Case sensitive (good for Linux)
387
const ig2 = ignore({ ignorecase: false }).add('*.TXT');
388
console.log(ig2.ignores('file.txt')); // false
389
console.log(ig2.ignores('file.TXT')); // true
390
```
391
392
## Performance Notes
393
394
- Results are automatically cached for improved performance on repeated checks
395
- Use `createFilter()` when filtering the same paths multiple times
396
- The `checkIgnore()` method has weaker caching and should be used only for debugging
397
- Pattern compilation happens once when patterns are added
398
399
## Types
400
401
```typescript { .api }
402
type Pathname = string;
403
404
interface Options {
405
ignorecase?: boolean;
406
ignoreCase?: boolean;
407
allowRelativePaths?: boolean;
408
}
409
410
interface TestResult {
411
ignored: boolean;
412
unignored: boolean;
413
rule?: IgnoreRule;
414
}
415
416
interface IgnoreRule {
417
pattern: string;
418
mark?: string;
419
negative: boolean;
420
}
421
422
interface PatternParams {
423
pattern: string;
424
mark?: string;
425
}
426
427
interface Ignore {
428
add(patterns: string | Ignore | readonly (string | Ignore)[] | PatternParams): this;
429
addPattern(pattern: string | Ignore | readonly (string | Ignore)[]): this;
430
ignores(pathname: Pathname): boolean;
431
test(pathname: Pathname): TestResult;
432
checkIgnore(pathname: Pathname): TestResult;
433
filter(pathnames: readonly Pathname[]): Pathname[];
434
createFilter(): (pathname: Pathname) => boolean;
435
}
436
```