format: prettify entire project

This commit is contained in:
Rim
2025-04-02 06:50:39 -04:00
parent 86f0782a98
commit 7ccc0be712
1711 changed files with 755867 additions and 235931 deletions

View File

@ -1,40 +1,65 @@
/// <reference types="node" />
import * as taskManager from './managers/tasks';
import { Options as OptionsInternal } from './settings';
import { Entry as EntryInternal, FileSystemAdapter as FileSystemAdapterInternal, Pattern as PatternInternal } from './types';
import {
Entry as EntryInternal,
FileSystemAdapter as FileSystemAdapterInternal,
Pattern as PatternInternal,
} from './types';
type EntryObjectModePredicate = {
[TKey in keyof Pick<OptionsInternal, 'objectMode'>]-?: true;
[TKey in keyof Pick<OptionsInternal, 'objectMode'>]-?: true;
};
type EntryStatsPredicate = {
[TKey in keyof Pick<OptionsInternal, 'stats'>]-?: true;
[TKey in keyof Pick<OptionsInternal, 'stats'>]-?: true;
};
type EntryObjectPredicate = EntryObjectModePredicate | EntryStatsPredicate;
declare function FastGlob(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): Promise<EntryInternal[]>;
declare function FastGlob(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Promise<string[]>;
declare function FastGlob(
source: PatternInternal | PatternInternal[],
options: OptionsInternal & EntryObjectPredicate
): Promise<EntryInternal[]>;
declare function FastGlob(
source: PatternInternal | PatternInternal[],
options?: OptionsInternal
): Promise<string[]>;
declare namespace FastGlob {
type Options = OptionsInternal;
type Entry = EntryInternal;
type Task = taskManager.Task;
type Pattern = PatternInternal;
type FileSystemAdapter = FileSystemAdapterInternal;
const glob: typeof FastGlob;
const globSync: typeof sync;
const globStream: typeof stream;
const async: typeof FastGlob;
function sync(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): EntryInternal[];
function sync(source: PatternInternal | PatternInternal[], options?: OptionsInternal): string[];
function stream(source: PatternInternal | PatternInternal[], options?: OptionsInternal): NodeJS.ReadableStream;
function generateTasks(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Task[];
function isDynamicPattern(source: PatternInternal, options?: OptionsInternal): boolean;
type Options = OptionsInternal;
type Entry = EntryInternal;
type Task = taskManager.Task;
type Pattern = PatternInternal;
type FileSystemAdapter = FileSystemAdapterInternal;
const glob: typeof FastGlob;
const globSync: typeof sync;
const globStream: typeof stream;
const async: typeof FastGlob;
function sync(
source: PatternInternal | PatternInternal[],
options: OptionsInternal & EntryObjectPredicate
): EntryInternal[];
function sync(
source: PatternInternal | PatternInternal[],
options?: OptionsInternal
): string[];
function stream(
source: PatternInternal | PatternInternal[],
options?: OptionsInternal
): NodeJS.ReadableStream;
function generateTasks(
source: PatternInternal | PatternInternal[],
options?: OptionsInternal
): Task[];
function isDynamicPattern(
source: PatternInternal,
options?: OptionsInternal
): boolean;
function escapePath(source: string): PatternInternal;
function convertPathToPattern(source: string): PatternInternal;
namespace posix {
function escapePath(source: string): PatternInternal;
function convertPathToPattern(source: string): PatternInternal;
namespace posix {
function escapePath(source: string): PatternInternal;
function convertPathToPattern(source: string): PatternInternal;
}
namespace win32 {
function escapePath(source: string): PatternInternal;
function convertPathToPattern(source: string): PatternInternal;
}
}
namespace win32 {
function escapePath(source: string): PatternInternal;
function convertPathToPattern(source: string): PatternInternal;
}
}
export = FastGlob;

186
node_modules/fast-glob/out/index.js generated vendored
View File

@ -1,102 +1,106 @@
"use strict";
const taskManager = require("./managers/tasks");
const async_1 = require("./providers/async");
const stream_1 = require("./providers/stream");
const sync_1 = require("./providers/sync");
const settings_1 = require("./settings");
const utils = require("./utils");
'use strict';
const taskManager = require('./managers/tasks');
const async_1 = require('./providers/async');
const stream_1 = require('./providers/stream');
const sync_1 = require('./providers/sync');
const settings_1 = require('./settings');
const utils = require('./utils');
async function FastGlob(source, options) {
assertPatternsInput(source);
const works = getWorks(source, async_1.default, options);
const result = await Promise.all(works);
return utils.array.flatten(result);
assertPatternsInput(source);
const works = getWorks(source, async_1.default, options);
const result = await Promise.all(works);
return utils.array.flatten(result);
}
// https://github.com/typescript-eslint/typescript-eslint/issues/60
// eslint-disable-next-line no-redeclare
(function (FastGlob) {
FastGlob.glob = FastGlob;
FastGlob.globSync = sync;
FastGlob.globStream = stream;
FastGlob.async = FastGlob;
function sync(source, options) {
assertPatternsInput(source);
const works = getWorks(source, sync_1.default, options);
return utils.array.flatten(works);
}
FastGlob.sync = sync;
function stream(source, options) {
assertPatternsInput(source);
const works = getWorks(source, stream_1.default, options);
/**
* The stream returned by the provider cannot work with an asynchronous iterator.
* To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
* This affects performance (+25%). I don't see best solution right now.
*/
return utils.stream.merge(works);
}
FastGlob.stream = stream;
function generateTasks(source, options) {
assertPatternsInput(source);
const patterns = [].concat(source);
const settings = new settings_1.default(options);
return taskManager.generate(patterns, settings);
}
FastGlob.generateTasks = generateTasks;
function isDynamicPattern(source, options) {
assertPatternsInput(source);
const settings = new settings_1.default(options);
return utils.pattern.isDynamicPattern(source, settings);
}
FastGlob.isDynamicPattern = isDynamicPattern;
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escape(source);
}
FastGlob.escapePath = escapePath;
function convertPathToPattern(source) {
assertPatternsInput(source);
return utils.path.convertPathToPattern(source);
}
FastGlob.convertPathToPattern = convertPathToPattern;
let posix;
(function (posix) {
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escapePosixPath(source);
}
posix.escapePath = escapePath;
function convertPathToPattern(source) {
assertPatternsInput(source);
return utils.path.convertPosixPathToPattern(source);
}
posix.convertPathToPattern = convertPathToPattern;
})(posix = FastGlob.posix || (FastGlob.posix = {}));
let win32;
(function (win32) {
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escapeWindowsPath(source);
}
win32.escapePath = escapePath;
function convertPathToPattern(source) {
assertPatternsInput(source);
return utils.path.convertWindowsPathToPattern(source);
}
win32.convertPathToPattern = convertPathToPattern;
})(win32 = FastGlob.win32 || (FastGlob.win32 = {}));
})(FastGlob || (FastGlob = {}));
function getWorks(source, _Provider, options) {
FastGlob.glob = FastGlob;
FastGlob.globSync = sync;
FastGlob.globStream = stream;
FastGlob.async = FastGlob;
function sync(source, options) {
assertPatternsInput(source);
const works = getWorks(source, sync_1.default, options);
return utils.array.flatten(works);
}
FastGlob.sync = sync;
function stream(source, options) {
assertPatternsInput(source);
const works = getWorks(source, stream_1.default, options);
/**
* The stream returned by the provider cannot work with an asynchronous iterator.
* To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
* This affects performance (+25%). I don't see best solution right now.
*/
return utils.stream.merge(works);
}
FastGlob.stream = stream;
function generateTasks(source, options) {
assertPatternsInput(source);
const patterns = [].concat(source);
const settings = new settings_1.default(options);
const tasks = taskManager.generate(patterns, settings);
const provider = new _Provider(settings);
return tasks.map(provider.read, provider);
return taskManager.generate(patterns, settings);
}
FastGlob.generateTasks = generateTasks;
function isDynamicPattern(source, options) {
assertPatternsInput(source);
const settings = new settings_1.default(options);
return utils.pattern.isDynamicPattern(source, settings);
}
FastGlob.isDynamicPattern = isDynamicPattern;
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escape(source);
}
FastGlob.escapePath = escapePath;
function convertPathToPattern(source) {
assertPatternsInput(source);
return utils.path.convertPathToPattern(source);
}
FastGlob.convertPathToPattern = convertPathToPattern;
let posix;
(function (posix) {
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escapePosixPath(source);
}
posix.escapePath = escapePath;
function convertPathToPattern(source) {
assertPatternsInput(source);
return utils.path.convertPosixPathToPattern(source);
}
posix.convertPathToPattern = convertPathToPattern;
})((posix = FastGlob.posix || (FastGlob.posix = {})));
let win32;
(function (win32) {
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escapeWindowsPath(source);
}
win32.escapePath = escapePath;
function convertPathToPattern(source) {
assertPatternsInput(source);
return utils.path.convertWindowsPathToPattern(source);
}
win32.convertPathToPattern = convertPathToPattern;
})((win32 = FastGlob.win32 || (FastGlob.win32 = {})));
})(FastGlob || (FastGlob = {}));
function getWorks(source, _Provider, options) {
const patterns = [].concat(source);
const settings = new settings_1.default(options);
const tasks = taskManager.generate(patterns, settings);
const provider = new _Provider(settings);
return tasks.map(provider.read, provider);
}
function assertPatternsInput(input) {
const source = [].concat(input);
const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
if (!isValidSource) {
throw new TypeError('Patterns must be a string (non empty) or an array of strings');
}
const source = [].concat(input);
const isValidSource = source.every(
(item) => utils.string.isString(item) && !utils.string.isEmpty(item)
);
if (!isValidSource) {
throw new TypeError(
'Patterns must be a string (non empty) or an array of strings'
);
}
}
module.exports = FastGlob;

View File

@ -1,11 +1,11 @@
import Settings from '../settings';
import { Pattern, PatternsGroup } from '../types';
export type Task = {
base: string;
dynamic: boolean;
patterns: Pattern[];
positive: Pattern[];
negative: Pattern[];
base: string;
dynamic: boolean;
patterns: Pattern[];
positive: Pattern[];
negative: Pattern[];
};
export declare function generate(input: Pattern[], settings: Settings): Task[];
/**
@ -14,9 +14,27 @@ export declare function generate(input: Pattern[], settings: Settings): Task[];
* Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
* This is necessary because directory traversal starts at the base directory and goes deeper.
*/
export declare function convertPatternsToTasks(positive: Pattern[], negative: Pattern[], dynamic: boolean): Task[];
export declare function convertPatternsToTasks(
positive: Pattern[],
negative: Pattern[],
dynamic: boolean
): Task[];
export declare function getPositivePatterns(patterns: Pattern[]): Pattern[];
export declare function getNegativePatternsAsPositive(patterns: Pattern[], ignore: Pattern[]): Pattern[];
export declare function groupPatternsByBaseDirectory(patterns: Pattern[]): PatternsGroup;
export declare function convertPatternGroupsToTasks(positive: PatternsGroup, negative: Pattern[], dynamic: boolean): Task[];
export declare function convertPatternGroupToTask(base: string, positive: Pattern[], negative: Pattern[], dynamic: boolean): Task;
export declare function getNegativePatternsAsPositive(
patterns: Pattern[],
ignore: Pattern[]
): Pattern[];
export declare function groupPatternsByBaseDirectory(
patterns: Pattern[]
): PatternsGroup;
export declare function convertPatternGroupsToTasks(
positive: PatternsGroup,
negative: Pattern[],
dynamic: boolean
): Task[];
export declare function convertPatternGroupToTask(
base: string,
positive: Pattern[],
negative: Pattern[],
dynamic: boolean
): Task;

View File

@ -1,46 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
const utils = require("../utils");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.convertPatternGroupToTask =
exports.convertPatternGroupsToTasks =
exports.groupPatternsByBaseDirectory =
exports.getNegativePatternsAsPositive =
exports.getPositivePatterns =
exports.convertPatternsToTasks =
exports.generate =
void 0;
const utils = require('../utils');
function generate(input, settings) {
const patterns = processPatterns(input, settings);
const ignore = processPatterns(settings.ignore, settings);
const positivePatterns = getPositivePatterns(patterns);
const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings));
const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings));
const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
return staticTasks.concat(dynamicTasks);
const patterns = processPatterns(input, settings);
const ignore = processPatterns(settings.ignore, settings);
const positivePatterns = getPositivePatterns(patterns);
const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
const staticPatterns = positivePatterns.filter((pattern) =>
utils.pattern.isStaticPattern(pattern, settings)
);
const dynamicPatterns = positivePatterns.filter((pattern) =>
utils.pattern.isDynamicPattern(pattern, settings)
);
const staticTasks = convertPatternsToTasks(
staticPatterns,
negativePatterns,
/* dynamic */ false
);
const dynamicTasks = convertPatternsToTasks(
dynamicPatterns,
negativePatterns,
/* dynamic */ true
);
return staticTasks.concat(dynamicTasks);
}
exports.generate = generate;
function processPatterns(input, settings) {
let patterns = input;
/**
* The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry
* and some problems with the micromatch package (see fast-glob issues: #365, #394).
*
* To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown
* in matching in the case of a large set of patterns after expansion.
*/
if (settings.braceExpansion) {
patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns);
}
/**
* If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used
* at any nesting level.
*
* We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change
* the pattern in the filter before creating a regular expression. There is no need to change the patterns
* in the application. Only on the input.
*/
if (settings.baseNameMatch) {
patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`);
}
/**
* This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion.
*/
return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern));
let patterns = input;
/**
* The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry
* and some problems with the micromatch package (see fast-glob issues: #365, #394).
*
* To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown
* in matching in the case of a large set of patterns after expansion.
*/
if (settings.braceExpansion) {
patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns);
}
/**
* If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used
* at any nesting level.
*
* We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change
* the pattern in the filter before creating a regular expression. There is no need to change the patterns
* in the application. Only on the input.
*/
if (settings.baseNameMatch) {
patterns = patterns.map((pattern) =>
pattern.includes('/') ? pattern : `**/${pattern}`
);
}
/**
* This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion.
*/
return patterns.map((pattern) =>
utils.pattern.removeDuplicateSlashes(pattern)
);
}
/**
* Returns tasks grouped by basic pattern directories.
@ -49,62 +72,88 @@ function processPatterns(input, settings) {
* This is necessary because directory traversal starts at the base directory and goes deeper.
*/
function convertPatternsToTasks(positive, negative, dynamic) {
const tasks = [];
const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive);
const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive);
const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
/*
* For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
* into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
*/
if ('.' in insideCurrentDirectoryGroup) {
tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
}
else {
tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
}
return tasks;
const tasks = [];
const patternsOutsideCurrentDirectory =
utils.pattern.getPatternsOutsideCurrentDirectory(positive);
const patternsInsideCurrentDirectory =
utils.pattern.getPatternsInsideCurrentDirectory(positive);
const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(
patternsOutsideCurrentDirectory
);
const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(
patternsInsideCurrentDirectory
);
tasks.push(
...convertPatternGroupsToTasks(
outsideCurrentDirectoryGroup,
negative,
dynamic
)
);
/*
* For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
* into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
*/
if ('.' in insideCurrentDirectoryGroup) {
tasks.push(
convertPatternGroupToTask(
'.',
patternsInsideCurrentDirectory,
negative,
dynamic
)
);
} else {
tasks.push(
...convertPatternGroupsToTasks(
insideCurrentDirectoryGroup,
negative,
dynamic
)
);
}
return tasks;
}
exports.convertPatternsToTasks = convertPatternsToTasks;
function getPositivePatterns(patterns) {
return utils.pattern.getPositivePatterns(patterns);
return utils.pattern.getPositivePatterns(patterns);
}
exports.getPositivePatterns = getPositivePatterns;
function getNegativePatternsAsPositive(patterns, ignore) {
const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore);
const positive = negative.map(utils.pattern.convertToPositivePattern);
return positive;
const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore);
const positive = negative.map(utils.pattern.convertToPositivePattern);
return positive;
}
exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
function groupPatternsByBaseDirectory(patterns) {
const group = {};
return patterns.reduce((collection, pattern) => {
const base = utils.pattern.getBaseDirectory(pattern);
if (base in collection) {
collection[base].push(pattern);
}
else {
collection[base] = [pattern];
}
return collection;
}, group);
const group = {};
return patterns.reduce((collection, pattern) => {
const base = utils.pattern.getBaseDirectory(pattern);
if (base in collection) {
collection[base].push(pattern);
} else {
collection[base] = [pattern];
}
return collection;
}, group);
}
exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
function convertPatternGroupsToTasks(positive, negative, dynamic) {
return Object.keys(positive).map((base) => {
return convertPatternGroupToTask(base, positive[base], negative, dynamic);
});
return Object.keys(positive).map((base) => {
return convertPatternGroupToTask(base, positive[base], negative, dynamic);
});
}
exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
function convertPatternGroupToTask(base, positive, negative, dynamic) {
return {
dynamic,
positive,
negative,
base,
patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern))
};
return {
dynamic,
positive,
negative,
base,
patterns: [].concat(
positive,
negative.map(utils.pattern.convertToNegativePattern)
),
};
}
exports.convertPatternGroupToTask = convertPatternGroupToTask;

View File

@ -3,7 +3,7 @@ import { Entry, EntryItem, ReaderOptions } from '../types';
import ReaderAsync from '../readers/async';
import Provider from './provider';
export default class ProviderAsync extends Provider<Promise<EntryItem[]>> {
protected _reader: ReaderAsync;
read(task: Task): Promise<EntryItem[]>;
api(root: string, task: Task, options: ReaderOptions): Promise<Entry[]>;
protected _reader: ReaderAsync;
read(task: Task): Promise<EntryItem[]>;
api(root: string, task: Task, options: ReaderOptions): Promise<Entry[]>;
}

View File

@ -1,23 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const async_1 = require("../readers/async");
const provider_1 = require("./provider");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const async_1 = require('../readers/async');
const provider_1 = require('./provider');
class ProviderAsync extends provider_1.default {
constructor() {
super(...arguments);
this._reader = new async_1.default(this._settings);
}
async read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const entries = await this.api(root, task, options);
return entries.map((entry) => options.transform(entry));
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
constructor() {
super(...arguments);
this._reader = new async_1.default(this._settings);
}
async read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const entries = await this.api(root, task, options);
return entries.map((entry) => options.transform(entry));
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
}
}
exports.default = ProviderAsync;

View File

@ -1,16 +1,20 @@
import { MicromatchOptions, EntryFilterFunction, Pattern } from '../../types';
import Settings from '../../settings';
export default class DeepFilter {
private readonly _settings;
private readonly _micromatchOptions;
constructor(_settings: Settings, _micromatchOptions: MicromatchOptions);
getFilter(basePath: string, positive: Pattern[], negative: Pattern[]): EntryFilterFunction;
private _getMatcher;
private _getNegativePatternsRe;
private _filter;
private _isSkippedByDeep;
private _getEntryLevel;
private _isSkippedSymbolicLink;
private _isSkippedByPositivePatterns;
private _isSkippedByNegativePatterns;
private readonly _settings;
private readonly _micromatchOptions;
constructor(_settings: Settings, _micromatchOptions: MicromatchOptions);
getFilter(
basePath: string,
positive: Pattern[],
negative: Pattern[]
): EntryFilterFunction;
private _getMatcher;
private _getNegativePatternsRe;
private _filter;
private _isSkippedByDeep;
private _getEntryLevel;
private _isSkippedSymbolicLink;
private _isSkippedByPositivePatterns;
private _isSkippedByNegativePatterns;
}

View File

@ -1,62 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils = require("../../utils");
const partial_1 = require("../matchers/partial");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const utils = require('../../utils');
const partial_1 = require('../matchers/partial');
class DeepFilter {
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
}
getFilter(basePath, positive, negative) {
const matcher = this._getMatcher(positive);
const negativeRe = this._getNegativePatternsRe(negative);
return (entry) => this._filter(basePath, entry, matcher, negativeRe);
}
_getMatcher(patterns) {
return new partial_1.default(
patterns,
this._settings,
this._micromatchOptions
);
}
_getNegativePatternsRe(patterns) {
const affectDepthOfReadingPatterns = patterns.filter(
utils.pattern.isAffectDepthOfReadingPattern
);
return utils.pattern.convertPatternsToRe(
affectDepthOfReadingPatterns,
this._micromatchOptions
);
}
_filter(basePath, entry, matcher, negativeRe) {
if (this._isSkippedByDeep(basePath, entry.path)) {
return false;
}
getFilter(basePath, positive, negative) {
const matcher = this._getMatcher(positive);
const negativeRe = this._getNegativePatternsRe(negative);
return (entry) => this._filter(basePath, entry, matcher, negativeRe);
if (this._isSkippedSymbolicLink(entry)) {
return false;
}
_getMatcher(patterns) {
return new partial_1.default(patterns, this._settings, this._micromatchOptions);
const filepath = utils.path.removeLeadingDotSegment(entry.path);
if (this._isSkippedByPositivePatterns(filepath, matcher)) {
return false;
}
_getNegativePatternsRe(patterns) {
const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern);
return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
return this._isSkippedByNegativePatterns(filepath, negativeRe);
}
_isSkippedByDeep(basePath, entryPath) {
/**
* Avoid unnecessary depth calculations when it doesn't matter.
*/
if (this._settings.deep === Infinity) {
return false;
}
_filter(basePath, entry, matcher, negativeRe) {
if (this._isSkippedByDeep(basePath, entry.path)) {
return false;
}
if (this._isSkippedSymbolicLink(entry)) {
return false;
}
const filepath = utils.path.removeLeadingDotSegment(entry.path);
if (this._isSkippedByPositivePatterns(filepath, matcher)) {
return false;
}
return this._isSkippedByNegativePatterns(filepath, negativeRe);
}
_isSkippedByDeep(basePath, entryPath) {
/**
* Avoid unnecessary depth calculations when it doesn't matter.
*/
if (this._settings.deep === Infinity) {
return false;
}
return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
}
_getEntryLevel(basePath, entryPath) {
const entryPathDepth = entryPath.split('/').length;
if (basePath === '') {
return entryPathDepth;
}
const basePathDepth = basePath.split('/').length;
return entryPathDepth - basePathDepth;
}
_isSkippedSymbolicLink(entry) {
return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
}
_isSkippedByPositivePatterns(entryPath, matcher) {
return !this._settings.baseNameMatch && !matcher.match(entryPath);
}
_isSkippedByNegativePatterns(entryPath, patternsRe) {
return !utils.pattern.matchAny(entryPath, patternsRe);
return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
}
_getEntryLevel(basePath, entryPath) {
const entryPathDepth = entryPath.split('/').length;
if (basePath === '') {
return entryPathDepth;
}
const basePathDepth = basePath.split('/').length;
return entryPathDepth - basePathDepth;
}
_isSkippedSymbolicLink(entry) {
return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
}
_isSkippedByPositivePatterns(entryPath, matcher) {
return !this._settings.baseNameMatch && !matcher.match(entryPath);
}
_isSkippedByNegativePatterns(entryPath, patternsRe) {
return !utils.pattern.matchAny(entryPath, patternsRe);
}
}
exports.default = DeepFilter;

View File

@ -1,17 +1,17 @@
import Settings from '../../settings';
import { EntryFilterFunction, MicromatchOptions, Pattern } from '../../types';
export default class EntryFilter {
private readonly _settings;
private readonly _micromatchOptions;
readonly index: Map<string, undefined>;
constructor(_settings: Settings, _micromatchOptions: MicromatchOptions);
getFilter(positive: Pattern[], negative: Pattern[]): EntryFilterFunction;
private _filter;
private _isDuplicateEntry;
private _createIndexRecord;
private _onlyFileFilter;
private _onlyDirectoryFilter;
private _isMatchToPatternsSet;
private _isMatchToAbsoluteNegative;
private _isMatchToPatterns;
private readonly _settings;
private readonly _micromatchOptions;
readonly index: Map<string, undefined>;
constructor(_settings: Settings, _micromatchOptions: MicromatchOptions);
getFilter(positive: Pattern[], negative: Pattern[]): EntryFilterFunction;
private _filter;
private _isDuplicateEntry;
private _createIndexRecord;
private _onlyFileFilter;
private _onlyDirectoryFilter;
private _isMatchToPatternsSet;
private _isMatchToAbsoluteNegative;
private _isMatchToPatterns;
}

View File

@ -1,85 +1,115 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils = require("../../utils");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const utils = require('../../utils');
class EntryFilter {
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this.index = new Map();
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this.index = new Map();
}
getFilter(positive, negative) {
const [absoluteNegative, relativeNegative] =
utils.pattern.partitionAbsoluteAndRelative(negative);
const patterns = {
positive: {
all: utils.pattern.convertPatternsToRe(
positive,
this._micromatchOptions
),
},
negative: {
absolute: utils.pattern.convertPatternsToRe(
absoluteNegative,
Object.assign(Object.assign({}, this._micromatchOptions), {
dot: true,
})
),
relative: utils.pattern.convertPatternsToRe(
relativeNegative,
Object.assign(Object.assign({}, this._micromatchOptions), {
dot: true,
})
),
},
};
return (entry) => this._filter(entry, patterns);
}
_filter(entry, patterns) {
const filepath = utils.path.removeLeadingDotSegment(entry.path);
if (this._settings.unique && this._isDuplicateEntry(filepath)) {
return false;
}
getFilter(positive, negative) {
const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative);
const patterns = {
positive: {
all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions)
},
negative: {
absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })),
relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true }))
}
};
return (entry) => this._filter(entry, patterns);
if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
return false;
}
_filter(entry, patterns) {
const filepath = utils.path.removeLeadingDotSegment(entry.path);
if (this._settings.unique && this._isDuplicateEntry(filepath)) {
return false;
}
if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
return false;
}
const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory());
if (this._settings.unique && isMatched) {
this._createIndexRecord(filepath);
}
return isMatched;
const isMatched = this._isMatchToPatternsSet(
filepath,
patterns,
entry.dirent.isDirectory()
);
if (this._settings.unique && isMatched) {
this._createIndexRecord(filepath);
}
_isDuplicateEntry(filepath) {
return this.index.has(filepath);
return isMatched;
}
_isDuplicateEntry(filepath) {
return this.index.has(filepath);
}
_createIndexRecord(filepath) {
this.index.set(filepath, undefined);
}
_onlyFileFilter(entry) {
return this._settings.onlyFiles && !entry.dirent.isFile();
}
_onlyDirectoryFilter(entry) {
return this._settings.onlyDirectories && !entry.dirent.isDirectory();
}
_isMatchToPatternsSet(filepath, patterns, isDirectory) {
const isMatched = this._isMatchToPatterns(
filepath,
patterns.positive.all,
isDirectory
);
if (!isMatched) {
return false;
}
_createIndexRecord(filepath) {
this.index.set(filepath, undefined);
const isMatchedByRelativeNegative = this._isMatchToPatterns(
filepath,
patterns.negative.relative,
isDirectory
);
if (isMatchedByRelativeNegative) {
return false;
}
_onlyFileFilter(entry) {
return this._settings.onlyFiles && !entry.dirent.isFile();
const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(
filepath,
patterns.negative.absolute,
isDirectory
);
if (isMatchedByAbsoluteNegative) {
return false;
}
_onlyDirectoryFilter(entry) {
return this._settings.onlyDirectories && !entry.dirent.isDirectory();
return true;
}
_isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) {
if (patternsRe.length === 0) {
return false;
}
_isMatchToPatternsSet(filepath, patterns, isDirectory) {
const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory);
if (!isMatched) {
return false;
}
const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory);
if (isMatchedByRelativeNegative) {
return false;
}
const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory);
if (isMatchedByAbsoluteNegative) {
return false;
}
return true;
const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath);
return this._isMatchToPatterns(fullpath, patternsRe, isDirectory);
}
_isMatchToPatterns(filepath, patternsRe, isDirectory) {
if (patternsRe.length === 0) {
return false;
}
_isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) {
if (patternsRe.length === 0) {
return false;
}
const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath);
return this._isMatchToPatterns(fullpath, patternsRe, isDirectory);
}
_isMatchToPatterns(filepath, patternsRe, isDirectory) {
if (patternsRe.length === 0) {
return false;
}
// Trying to match files and directories by patterns.
const isMatched = utils.pattern.matchAny(filepath, patternsRe);
// A pattern with a trailling slash can be used for directory matching.
// To apply such pattern, we need to add a tralling slash to the path.
if (!isMatched && isDirectory) {
return utils.pattern.matchAny(filepath + '/', patternsRe);
}
return isMatched;
// Trying to match files and directories by patterns.
const isMatched = utils.pattern.matchAny(filepath, patternsRe);
// A pattern with a trailling slash can be used for directory matching.
// To apply such pattern, we need to add a tralling slash to the path.
if (!isMatched && isDirectory) {
return utils.pattern.matchAny(filepath + '/', patternsRe);
}
return isMatched;
}
}
exports.default = EntryFilter;

View File

@ -1,8 +1,8 @@
import Settings from '../../settings';
import { ErrorFilterFunction } from '../../types';
export default class ErrorFilter {
private readonly _settings;
constructor(_settings: Settings);
getFilter(): ErrorFilterFunction;
private _isNonFatalError;
private readonly _settings;
constructor(_settings: Settings);
getFilter(): ErrorFilterFunction;
private _isNonFatalError;
}

View File

@ -1,15 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils = require("../../utils");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const utils = require('../../utils');
class ErrorFilter {
constructor(_settings) {
this._settings = _settings;
}
getFilter() {
return (error) => this._isNonFatalError(error);
}
_isNonFatalError(error) {
return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
}
constructor(_settings) {
this._settings = _settings;
}
getFilter() {
return (error) => this._isNonFatalError(error);
}
_isNonFatalError(error) {
return (
utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors
);
}
}
exports.default = ErrorFilter;

View File

@ -2,32 +2,36 @@ import { Pattern, MicromatchOptions, PatternRe } from '../../types';
import Settings from '../../settings';
export type PatternSegment = StaticPatternSegment | DynamicPatternSegment;
type StaticPatternSegment = {
dynamic: false;
pattern: Pattern;
dynamic: false;
pattern: Pattern;
};
type DynamicPatternSegment = {
dynamic: true;
pattern: Pattern;
patternRe: PatternRe;
dynamic: true;
pattern: Pattern;
patternRe: PatternRe;
};
export type PatternSection = PatternSegment[];
export type PatternInfo = {
/**
* Indicates that the pattern has a globstar (more than a single section).
*/
complete: boolean;
pattern: Pattern;
segments: PatternSegment[];
sections: PatternSection[];
/**
* Indicates that the pattern has a globstar (more than a single section).
*/
complete: boolean;
pattern: Pattern;
segments: PatternSegment[];
sections: PatternSection[];
};
export default abstract class Matcher {
private readonly _patterns;
private readonly _settings;
private readonly _micromatchOptions;
protected readonly _storage: PatternInfo[];
constructor(_patterns: Pattern[], _settings: Settings, _micromatchOptions: MicromatchOptions);
private _fillStorage;
private _getPatternSegments;
private _splitSegmentsIntoSections;
private readonly _patterns;
private readonly _settings;
private readonly _micromatchOptions;
protected readonly _storage: PatternInfo[];
constructor(
_patterns: Pattern[],
_settings: Settings,
_micromatchOptions: MicromatchOptions
);
private _fillStorage;
private _getPatternSegments;
private _splitSegmentsIntoSections;
}
export {};

View File

@ -1,45 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils = require("../../utils");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const utils = require('../../utils');
class Matcher {
constructor(_patterns, _settings, _micromatchOptions) {
this._patterns = _patterns;
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this._storage = [];
this._fillStorage();
}
_fillStorage() {
for (const pattern of this._patterns) {
const segments = this._getPatternSegments(pattern);
const sections = this._splitSegmentsIntoSections(segments);
this._storage.push({
complete: sections.length <= 1,
pattern,
segments,
sections
});
}
}
_getPatternSegments(pattern) {
const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions);
return parts.map((part) => {
const dynamic = utils.pattern.isDynamicPattern(part, this._settings);
if (!dynamic) {
return {
dynamic: false,
pattern: part
};
}
return {
dynamic: true,
pattern: part,
patternRe: utils.pattern.makeRe(part, this._micromatchOptions)
};
});
}
_splitSegmentsIntoSections(segments) {
return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern));
constructor(_patterns, _settings, _micromatchOptions) {
this._patterns = _patterns;
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this._storage = [];
this._fillStorage();
}
_fillStorage() {
for (const pattern of this._patterns) {
const segments = this._getPatternSegments(pattern);
const sections = this._splitSegmentsIntoSections(segments);
this._storage.push({
complete: sections.length <= 1,
pattern,
segments,
sections,
});
}
}
_getPatternSegments(pattern) {
const parts = utils.pattern.getPatternParts(
pattern,
this._micromatchOptions
);
return parts.map((part) => {
const dynamic = utils.pattern.isDynamicPattern(part, this._settings);
if (!dynamic) {
return {
dynamic: false,
pattern: part,
};
}
return {
dynamic: true,
pattern: part,
patternRe: utils.pattern.makeRe(part, this._micromatchOptions),
};
});
}
_splitSegmentsIntoSections(segments) {
return utils.array.splitWhen(
segments,
(segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)
);
}
}
exports.default = Matcher;

View File

@ -1,4 +1,4 @@
import Matcher from './matcher';
export default class PartialMatcher extends Matcher {
match(filepath: string): boolean;
match(filepath: string): boolean;
}

View File

@ -1,38 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const matcher_1 = require("./matcher");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const matcher_1 = require('./matcher');
class PartialMatcher extends matcher_1.default {
match(filepath) {
const parts = filepath.split('/');
const levels = parts.length;
const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
for (const pattern of patterns) {
const section = pattern.sections[0];
/**
* In this case, the pattern has a globstar and we must read all directories unconditionally,
* but only if the level has reached the end of the first group.
*
* fixtures/{a,b}/**
* ^ true/false ^ always true
*/
if (!pattern.complete && levels > section.length) {
return true;
}
const match = parts.every((part, index) => {
const segment = pattern.segments[index];
if (segment.dynamic && segment.patternRe.test(part)) {
return true;
}
if (!segment.dynamic && segment.pattern === part) {
return true;
}
return false;
});
if (match) {
return true;
}
match(filepath) {
const parts = filepath.split('/');
const levels = parts.length;
const patterns = this._storage.filter(
(info) => !info.complete || info.segments.length > levels
);
for (const pattern of patterns) {
const section = pattern.sections[0];
/**
* In this case, the pattern has a globstar and we must read all directories unconditionally,
* but only if the level has reached the end of the first group.
*
* fixtures/{a,b}/**
* ^ true/false ^ always true
*/
if (!pattern.complete && levels > section.length) {
return true;
}
const match = parts.every((part, index) => {
const segment = pattern.segments[index];
if (segment.dynamic && segment.patternRe.test(part)) {
return true;
}
if (!segment.dynamic && segment.pattern === part) {
return true;
}
return false;
});
if (match) {
return true;
}
}
return false;
}
}
exports.default = PartialMatcher;

View File

@ -6,14 +6,14 @@ import EntryFilter from './filters/entry';
import ErrorFilter from './filters/error';
import EntryTransformer from './transformers/entry';
export default abstract class Provider<T> {
protected readonly _settings: Settings;
readonly errorFilter: ErrorFilter;
readonly entryFilter: EntryFilter;
readonly deepFilter: DeepFilter;
readonly entryTransformer: EntryTransformer;
constructor(_settings: Settings);
abstract read(_task: Task): T;
protected _getRootDirectory(task: Task): string;
protected _getReaderOptions(task: Task): ReaderOptions;
protected _getMicromatchOptions(): MicromatchOptions;
protected readonly _settings: Settings;
readonly errorFilter: ErrorFilter;
readonly entryFilter: EntryFilter;
readonly deepFilter: DeepFilter;
readonly entryTransformer: EntryTransformer;
constructor(_settings: Settings);
abstract read(_task: Task): T;
protected _getRootDirectory(task: Task): string;
protected _getReaderOptions(task: Task): ReaderOptions;
protected _getMicromatchOptions(): MicromatchOptions;
}

View File

@ -1,48 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const deep_1 = require("./filters/deep");
const entry_1 = require("./filters/entry");
const error_1 = require("./filters/error");
const entry_2 = require("./transformers/entry");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const path = require('path');
const deep_1 = require('./filters/deep');
const entry_1 = require('./filters/entry');
const error_1 = require('./filters/error');
const entry_2 = require('./transformers/entry');
class Provider {
constructor(_settings) {
this._settings = _settings;
this.errorFilter = new error_1.default(this._settings);
this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
this.entryTransformer = new entry_2.default(this._settings);
}
_getRootDirectory(task) {
return path.resolve(this._settings.cwd, task.base);
}
_getReaderOptions(task) {
const basePath = task.base === '.' ? '' : task.base;
return {
basePath,
pathSegmentSeparator: '/',
concurrency: this._settings.concurrency,
deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
errorFilter: this.errorFilter.getFilter(),
followSymbolicLinks: this._settings.followSymbolicLinks,
fs: this._settings.fs,
stats: this._settings.stats,
throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
transform: this.entryTransformer.getTransformer()
};
}
_getMicromatchOptions() {
return {
dot: this._settings.dot,
matchBase: this._settings.baseNameMatch,
nobrace: !this._settings.braceExpansion,
nocase: !this._settings.caseSensitiveMatch,
noext: !this._settings.extglob,
noglobstar: !this._settings.globstar,
posix: true,
strictSlashes: false
};
}
constructor(_settings) {
this._settings = _settings;
this.errorFilter = new error_1.default(this._settings);
this.entryFilter = new entry_1.default(
this._settings,
this._getMicromatchOptions()
);
this.deepFilter = new deep_1.default(
this._settings,
this._getMicromatchOptions()
);
this.entryTransformer = new entry_2.default(this._settings);
}
_getRootDirectory(task) {
return path.resolve(this._settings.cwd, task.base);
}
_getReaderOptions(task) {
const basePath = task.base === '.' ? '' : task.base;
return {
basePath,
pathSegmentSeparator: '/',
concurrency: this._settings.concurrency,
deepFilter: this.deepFilter.getFilter(
basePath,
task.positive,
task.negative
),
entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
errorFilter: this.errorFilter.getFilter(),
followSymbolicLinks: this._settings.followSymbolicLinks,
fs: this._settings.fs,
stats: this._settings.stats,
throwErrorOnBrokenSymbolicLink:
this._settings.throwErrorOnBrokenSymbolicLink,
transform: this.entryTransformer.getTransformer(),
};
}
_getMicromatchOptions() {
return {
dot: this._settings.dot,
matchBase: this._settings.baseNameMatch,
nobrace: !this._settings.braceExpansion,
nocase: !this._settings.caseSensitiveMatch,
noext: !this._settings.extglob,
noglobstar: !this._settings.globstar,
posix: true,
strictSlashes: false,
};
}
}
exports.default = Provider;

View File

@ -5,7 +5,7 @@ import ReaderStream from '../readers/stream';
import { ReaderOptions } from '../types';
import Provider from './provider';
export default class ProviderStream extends Provider<Readable> {
protected _reader: ReaderStream;
read(task: Task): Readable;
api(root: string, task: Task, options: ReaderOptions): Readable;
protected _reader: ReaderStream;
read(task: Task): Readable;
api(root: string, task: Task, options: ReaderOptions): Readable;
}

View File

@ -1,31 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const stream_1 = require("stream");
const stream_2 = require("../readers/stream");
const provider_1 = require("./provider");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const stream_1 = require('stream');
const stream_2 = require('../readers/stream');
const provider_1 = require('./provider');
class ProviderStream extends provider_1.default {
constructor() {
super(...arguments);
this._reader = new stream_2.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const source = this.api(root, task, options);
const destination = new stream_1.Readable({ objectMode: true, read: () => { } });
source
.once('error', (error) => destination.emit('error', error))
.on('data', (entry) => destination.emit('data', options.transform(entry)))
.once('end', () => destination.emit('end'));
destination
.once('close', () => source.destroy());
return destination;
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
constructor() {
super(...arguments);
this._reader = new stream_2.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const source = this.api(root, task, options);
const destination = new stream_1.Readable({
objectMode: true,
read: () => {},
});
source
.once('error', (error) => destination.emit('error', error))
.on('data', (entry) => destination.emit('data', options.transform(entry)))
.once('end', () => destination.emit('end'));
destination.once('close', () => source.destroy());
return destination;
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
}
}
exports.default = ProviderStream;

View File

@ -3,7 +3,7 @@ import ReaderSync from '../readers/sync';
import { Entry, EntryItem, ReaderOptions } from '../types';
import Provider from './provider';
export default class ProviderSync extends Provider<EntryItem[]> {
protected _reader: ReaderSync;
read(task: Task): EntryItem[];
api(root: string, task: Task, options: ReaderOptions): Entry[];
protected _reader: ReaderSync;
read(task: Task): EntryItem[];
api(root: string, task: Task, options: ReaderOptions): Entry[];
}

View File

@ -1,23 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const sync_1 = require("../readers/sync");
const provider_1 = require("./provider");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const sync_1 = require('../readers/sync');
const provider_1 = require('./provider');
class ProviderSync extends provider_1.default {
constructor() {
super(...arguments);
this._reader = new sync_1.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const entries = this.api(root, task, options);
return entries.map(options.transform);
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
constructor() {
super(...arguments);
this._reader = new sync_1.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options = this._getReaderOptions(task);
const entries = this.api(root, task, options);
return entries.map(options.transform);
}
api(root, task, options) {
if (task.dynamic) {
return this._reader.dynamic(root, options);
}
return this._reader.static(task.patterns, options);
}
}
exports.default = ProviderSync;

View File

@ -1,8 +1,8 @@
import Settings from '../../settings';
import { EntryTransformerFunction } from '../../types';
export default class EntryTransformer {
private readonly _settings;
constructor(_settings: Settings);
getTransformer(): EntryTransformerFunction;
private _transform;
private readonly _settings;
constructor(_settings: Settings);
getTransformer(): EntryTransformerFunction;
private _transform;
}

View File

@ -1,26 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils = require("../../utils");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const utils = require('../../utils');
class EntryTransformer {
constructor(_settings) {
this._settings = _settings;
constructor(_settings) {
this._settings = _settings;
}
getTransformer() {
return (entry) => this._transform(entry);
}
_transform(entry) {
let filepath = entry.path;
if (this._settings.absolute) {
filepath = utils.path.makeAbsolute(this._settings.cwd, filepath);
filepath = utils.path.unixify(filepath);
}
getTransformer() {
return (entry) => this._transform(entry);
if (this._settings.markDirectories && entry.dirent.isDirectory()) {
filepath += '/';
}
_transform(entry) {
let filepath = entry.path;
if (this._settings.absolute) {
filepath = utils.path.makeAbsolute(this._settings.cwd, filepath);
filepath = utils.path.unixify(filepath);
}
if (this._settings.markDirectories && entry.dirent.isDirectory()) {
filepath += '/';
}
if (!this._settings.objectMode) {
return filepath;
}
return Object.assign(Object.assign({}, entry), { path: filepath });
if (!this._settings.objectMode) {
return filepath;
}
return Object.assign(Object.assign({}, entry), { path: filepath });
}
}
exports.default = EntryTransformer;

View File

@ -3,8 +3,8 @@ import { Entry, ReaderOptions, Pattern } from '../types';
import Reader from './reader';
import ReaderStream from './stream';
export default class ReaderAsync extends Reader<Promise<Entry[]>> {
protected _walkAsync: typeof fsWalk.walk;
protected _readerStream: ReaderStream;
dynamic(root: string, options: ReaderOptions): Promise<Entry[]>;
static(patterns: Pattern[], options: ReaderOptions): Promise<Entry[]>;
protected _walkAsync: typeof fsWalk.walk;
protected _readerStream: ReaderStream;
dynamic(root: string, options: ReaderOptions): Promise<Entry[]>;
static(patterns: Pattern[], options: ReaderOptions): Promise<Entry[]>;
}

View File

@ -1,35 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fsWalk = require("@nodelib/fs.walk");
const reader_1 = require("./reader");
const stream_1 = require("./stream");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const fsWalk = require('@nodelib/fs.walk');
const reader_1 = require('./reader');
const stream_1 = require('./stream');
class ReaderAsync extends reader_1.default {
constructor() {
super(...arguments);
this._walkAsync = fsWalk.walk;
this._readerStream = new stream_1.default(this._settings);
}
dynamic(root, options) {
return new Promise((resolve, reject) => {
this._walkAsync(root, options, (error, entries) => {
if (error === null) {
resolve(entries);
}
else {
reject(error);
}
});
});
}
async static(patterns, options) {
const entries = [];
const stream = this._readerStream.static(patterns, options);
// After #235, replace it with an asynchronous iterator.
return new Promise((resolve, reject) => {
stream.once('error', reject);
stream.on('data', (entry) => entries.push(entry));
stream.once('end', () => resolve(entries));
});
}
constructor() {
super(...arguments);
this._walkAsync = fsWalk.walk;
this._readerStream = new stream_1.default(this._settings);
}
dynamic(root, options) {
return new Promise((resolve, reject) => {
this._walkAsync(root, options, (error, entries) => {
if (error === null) {
resolve(entries);
} else {
reject(error);
}
});
});
}
async static(patterns, options) {
const entries = [];
const stream = this._readerStream.static(patterns, options);
// After #235, replace it with an asynchronous iterator.
return new Promise((resolve, reject) => {
stream.once('error', reject);
stream.on('data', (entry) => entries.push(entry));
stream.once('end', () => resolve(entries));
});
}
}
exports.default = ReaderAsync;

View File

@ -4,12 +4,12 @@ import * as fsStat from '@nodelib/fs.stat';
import Settings from '../settings';
import { Entry, ErrnoException, Pattern, ReaderOptions } from '../types';
export default abstract class Reader<T> {
protected readonly _settings: Settings;
protected readonly _fsStatSettings: fsStat.Settings;
constructor(_settings: Settings);
abstract dynamic(root: string, options: ReaderOptions): T;
abstract static(patterns: Pattern[], options: ReaderOptions): T;
protected _getFullEntryPath(filepath: string): string;
protected _makeEntry(stats: fs.Stats, pattern: Pattern): Entry;
protected _isFatalError(error: ErrnoException): boolean;
protected readonly _settings: Settings;
protected readonly _fsStatSettings: fsStat.Settings;
constructor(_settings: Settings);
abstract dynamic(root: string, options: ReaderOptions): T;
abstract static(patterns: Pattern[], options: ReaderOptions): T;
protected _getFullEntryPath(filepath: string): string;
protected _makeEntry(stats: fs.Stats, pattern: Pattern): Entry;
protected _isFatalError(error: ErrnoException): boolean;
}

View File

@ -1,33 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const fsStat = require("@nodelib/fs.stat");
const utils = require("../utils");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const path = require('path');
const fsStat = require('@nodelib/fs.stat');
const utils = require('../utils');
class Reader {
constructor(_settings) {
this._settings = _settings;
this._fsStatSettings = new fsStat.Settings({
followSymbolicLink: this._settings.followSymbolicLinks,
fs: this._settings.fs,
throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
});
}
_getFullEntryPath(filepath) {
return path.resolve(this._settings.cwd, filepath);
}
_makeEntry(stats, pattern) {
const entry = {
name: pattern,
path: pattern,
dirent: utils.fs.createDirentFromStats(pattern, stats)
};
if (this._settings.stats) {
entry.stats = stats;
}
return entry;
}
_isFatalError(error) {
return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
constructor(_settings) {
this._settings = _settings;
this._fsStatSettings = new fsStat.Settings({
followSymbolicLink: this._settings.followSymbolicLinks,
fs: this._settings.fs,
throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks,
});
}
_getFullEntryPath(filepath) {
return path.resolve(this._settings.cwd, filepath);
}
_makeEntry(stats, pattern) {
const entry = {
name: pattern,
path: pattern,
dirent: utils.fs.createDirentFromStats(pattern, stats),
};
if (this._settings.stats) {
entry.stats = stats;
}
return entry;
}
_isFatalError(error) {
return (
!utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors
);
}
}
exports.default = Reader;

View File

@ -5,10 +5,10 @@ import * as fsWalk from '@nodelib/fs.walk';
import { Pattern, ReaderOptions } from '../types';
import Reader from './reader';
export default class ReaderStream extends Reader<Readable> {
protected _walkStream: typeof fsWalk.walkStream;
protected _stat: typeof fsStat.stat;
dynamic(root: string, options: ReaderOptions): Readable;
static(patterns: Pattern[], options: ReaderOptions): Readable;
private _getEntry;
private _getStat;
protected _walkStream: typeof fsWalk.walkStream;
protected _stat: typeof fsStat.stat;
dynamic(root: string, options: ReaderOptions): Readable;
static(patterns: Pattern[], options: ReaderOptions): Readable;
private _getEntry;
private _getStat;
}

View File

@ -1,55 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const stream_1 = require("stream");
const fsStat = require("@nodelib/fs.stat");
const fsWalk = require("@nodelib/fs.walk");
const reader_1 = require("./reader");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const stream_1 = require('stream');
const fsStat = require('@nodelib/fs.stat');
const fsWalk = require('@nodelib/fs.walk');
const reader_1 = require('./reader');
class ReaderStream extends reader_1.default {
constructor() {
super(...arguments);
this._walkStream = fsWalk.walkStream;
this._stat = fsStat.stat;
constructor() {
super(...arguments);
this._walkStream = fsWalk.walkStream;
this._stat = fsStat.stat;
}
dynamic(root, options) {
return this._walkStream(root, options);
}
static(patterns, options) {
const filepaths = patterns.map(this._getFullEntryPath, this);
const stream = new stream_1.PassThrough({ objectMode: true });
stream._write = (index, _enc, done) => {
return this._getEntry(filepaths[index], patterns[index], options)
.then((entry) => {
if (entry !== null && options.entryFilter(entry)) {
stream.push(entry);
}
if (index === filepaths.length - 1) {
stream.end();
}
done();
})
.catch(done);
};
for (let i = 0; i < filepaths.length; i++) {
stream.write(i);
}
dynamic(root, options) {
return this._walkStream(root, options);
}
static(patterns, options) {
const filepaths = patterns.map(this._getFullEntryPath, this);
const stream = new stream_1.PassThrough({ objectMode: true });
stream._write = (index, _enc, done) => {
return this._getEntry(filepaths[index], patterns[index], options)
.then((entry) => {
if (entry !== null && options.entryFilter(entry)) {
stream.push(entry);
}
if (index === filepaths.length - 1) {
stream.end();
}
done();
})
.catch(done);
};
for (let i = 0; i < filepaths.length; i++) {
stream.write(i);
return stream;
}
_getEntry(filepath, pattern, options) {
return this._getStat(filepath)
.then((stats) => this._makeEntry(stats, pattern))
.catch((error) => {
if (options.errorFilter(error)) {
return null;
}
return stream;
}
_getEntry(filepath, pattern, options) {
return this._getStat(filepath)
.then((stats) => this._makeEntry(stats, pattern))
.catch((error) => {
if (options.errorFilter(error)) {
return null;
}
throw error;
});
}
_getStat(filepath) {
return new Promise((resolve, reject) => {
this._stat(filepath, this._fsStatSettings, (error, stats) => {
return error === null ? resolve(stats) : reject(error);
});
});
}
throw error;
});
}
_getStat(filepath) {
return new Promise((resolve, reject) => {
this._stat(filepath, this._fsStatSettings, (error, stats) => {
return error === null ? resolve(stats) : reject(error);
});
});
}
}
exports.default = ReaderStream;

View File

@ -3,10 +3,10 @@ import * as fsWalk from '@nodelib/fs.walk';
import { Entry, Pattern, ReaderOptions } from '../types';
import Reader from './reader';
export default class ReaderSync extends Reader<Entry[]> {
protected _walkSync: typeof fsWalk.walkSync;
protected _statSync: typeof fsStat.statSync;
dynamic(root: string, options: ReaderOptions): Entry[];
static(patterns: Pattern[], options: ReaderOptions): Entry[];
private _getEntry;
private _getStat;
protected _walkSync: typeof fsWalk.walkSync;
protected _statSync: typeof fsStat.statSync;
dynamic(root: string, options: ReaderOptions): Entry[];
static(patterns: Pattern[], options: ReaderOptions): Entry[];
private _getEntry;
private _getStat;
}

View File

@ -1,43 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fsStat = require("@nodelib/fs.stat");
const fsWalk = require("@nodelib/fs.walk");
const reader_1 = require("./reader");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const fsStat = require('@nodelib/fs.stat');
const fsWalk = require('@nodelib/fs.walk');
const reader_1 = require('./reader');
class ReaderSync extends reader_1.default {
constructor() {
super(...arguments);
this._walkSync = fsWalk.walkSync;
this._statSync = fsStat.statSync;
constructor() {
super(...arguments);
this._walkSync = fsWalk.walkSync;
this._statSync = fsStat.statSync;
}
dynamic(root, options) {
return this._walkSync(root, options);
}
static(patterns, options) {
const entries = [];
for (const pattern of patterns) {
const filepath = this._getFullEntryPath(pattern);
const entry = this._getEntry(filepath, pattern, options);
if (entry === null || !options.entryFilter(entry)) {
continue;
}
entries.push(entry);
}
dynamic(root, options) {
return this._walkSync(root, options);
}
static(patterns, options) {
const entries = [];
for (const pattern of patterns) {
const filepath = this._getFullEntryPath(pattern);
const entry = this._getEntry(filepath, pattern, options);
if (entry === null || !options.entryFilter(entry)) {
continue;
}
entries.push(entry);
}
return entries;
}
_getEntry(filepath, pattern, options) {
try {
const stats = this._getStat(filepath);
return this._makeEntry(stats, pattern);
}
catch (error) {
if (options.errorFilter(error)) {
return null;
}
throw error;
}
}
_getStat(filepath) {
return this._statSync(filepath, this._fsStatSettings);
return entries;
}
_getEntry(filepath, pattern, options) {
try {
const stats = this._getStat(filepath);
return this._makeEntry(stats, pattern);
} catch (error) {
if (options.errorFilter(error)) {
return null;
}
throw error;
}
}
_getStat(filepath) {
return this._statSync(filepath, this._fsStatSettings);
}
}
exports.default = ReaderSync;

View File

@ -1,164 +1,164 @@
import { FileSystemAdapter, Pattern } from './types';
export declare const DEFAULT_FILE_SYSTEM_ADAPTER: FileSystemAdapter;
export type Options = {
/**
* Return the absolute path for entries.
*
* @default false
*/
absolute?: boolean;
/**
* If set to `true`, then patterns without slashes will be matched against
* the basename of the path if it contains slashes.
*
* @default false
*/
baseNameMatch?: boolean;
/**
* Enables Bash-like brace expansion.
*
* @default true
*/
braceExpansion?: boolean;
/**
* Enables a case-sensitive mode for matching files.
*
* @default true
*/
caseSensitiveMatch?: boolean;
/**
* Specifies the maximum number of concurrent requests from a reader to read
* directories.
*
* @default os.cpus().length
*/
concurrency?: number;
/**
* The current working directory in which to search.
*
* @default process.cwd()
*/
cwd?: string;
/**
* Specifies the maximum depth of a read directory relative to the start
* directory.
*
* @default Infinity
*/
deep?: number;
/**
* Allow patterns to match entries that begin with a period (`.`).
*
* @default false
*/
dot?: boolean;
/**
* Enables Bash-like `extglob` functionality.
*
* @default true
*/
extglob?: boolean;
/**
* Indicates whether to traverse descendants of symbolic link directories.
*
* @default true
*/
followSymbolicLinks?: boolean;
/**
* Custom implementation of methods for working with the file system.
*
* @default fs.*
*/
fs?: Partial<FileSystemAdapter>;
/**
* Enables recursively repeats a pattern containing `**`.
* If `false`, `**` behaves exactly like `*`.
*
* @default true
*/
globstar?: boolean;
/**
* An array of glob patterns to exclude matches.
* This is an alternative way to use negative patterns.
*
* @default []
*/
ignore?: Pattern[];
/**
* Mark the directory path with the final slash.
*
* @default false
*/
markDirectories?: boolean;
/**
* Returns objects (instead of strings) describing entries.
*
* @default false
*/
objectMode?: boolean;
/**
* Return only directories.
*
* @default false
*/
onlyDirectories?: boolean;
/**
* Return only files.
*
* @default true
*/
onlyFiles?: boolean;
/**
* Enables an object mode (`objectMode`) with an additional `stats` field.
*
* @default false
*/
stats?: boolean;
/**
* By default this package suppress only `ENOENT` errors.
* Set to `true` to suppress any error.
*
* @default false
*/
suppressErrors?: boolean;
/**
* Throw an error when symbolic link is broken if `true` or safely
* return `lstat` call if `false`.
*
* @default false
*/
throwErrorOnBrokenSymbolicLink?: boolean;
/**
* Ensures that the returned entries are unique.
*
* @default true
*/
unique?: boolean;
/**
* Return the absolute path for entries.
*
* @default false
*/
absolute?: boolean;
/**
* If set to `true`, then patterns without slashes will be matched against
* the basename of the path if it contains slashes.
*
* @default false
*/
baseNameMatch?: boolean;
/**
* Enables Bash-like brace expansion.
*
* @default true
*/
braceExpansion?: boolean;
/**
* Enables a case-sensitive mode for matching files.
*
* @default true
*/
caseSensitiveMatch?: boolean;
/**
* Specifies the maximum number of concurrent requests from a reader to read
* directories.
*
* @default os.cpus().length
*/
concurrency?: number;
/**
* The current working directory in which to search.
*
* @default process.cwd()
*/
cwd?: string;
/**
* Specifies the maximum depth of a read directory relative to the start
* directory.
*
* @default Infinity
*/
deep?: number;
/**
* Allow patterns to match entries that begin with a period (`.`).
*
* @default false
*/
dot?: boolean;
/**
* Enables Bash-like `extglob` functionality.
*
* @default true
*/
extglob?: boolean;
/**
* Indicates whether to traverse descendants of symbolic link directories.
*
* @default true
*/
followSymbolicLinks?: boolean;
/**
* Custom implementation of methods for working with the file system.
*
* @default fs.*
*/
fs?: Partial<FileSystemAdapter>;
/**
* Enables recursively repeats a pattern containing `**`.
* If `false`, `**` behaves exactly like `*`.
*
* @default true
*/
globstar?: boolean;
/**
* An array of glob patterns to exclude matches.
* This is an alternative way to use negative patterns.
*
* @default []
*/
ignore?: Pattern[];
/**
* Mark the directory path with the final slash.
*
* @default false
*/
markDirectories?: boolean;
/**
* Returns objects (instead of strings) describing entries.
*
* @default false
*/
objectMode?: boolean;
/**
* Return only directories.
*
* @default false
*/
onlyDirectories?: boolean;
/**
* Return only files.
*
* @default true
*/
onlyFiles?: boolean;
/**
* Enables an object mode (`objectMode`) with an additional `stats` field.
*
* @default false
*/
stats?: boolean;
/**
* By default this package suppress only `ENOENT` errors.
* Set to `true` to suppress any error.
*
* @default false
*/
suppressErrors?: boolean;
/**
* Throw an error when symbolic link is broken if `true` or safely
* return `lstat` call if `false`.
*
* @default false
*/
throwErrorOnBrokenSymbolicLink?: boolean;
/**
* Ensures that the returned entries are unique.
*
* @default true
*/
unique?: boolean;
};
export default class Settings {
private readonly _options;
readonly absolute: boolean;
readonly baseNameMatch: boolean;
readonly braceExpansion: boolean;
readonly caseSensitiveMatch: boolean;
readonly concurrency: number;
readonly cwd: string;
readonly deep: number;
readonly dot: boolean;
readonly extglob: boolean;
readonly followSymbolicLinks: boolean;
readonly fs: FileSystemAdapter;
readonly globstar: boolean;
readonly ignore: Pattern[];
readonly markDirectories: boolean;
readonly objectMode: boolean;
readonly onlyDirectories: boolean;
readonly onlyFiles: boolean;
readonly stats: boolean;
readonly suppressErrors: boolean;
readonly throwErrorOnBrokenSymbolicLink: boolean;
readonly unique: boolean;
constructor(_options?: Options);
private _getValue;
private _getFileSystemMethods;
private readonly _options;
readonly absolute: boolean;
readonly baseNameMatch: boolean;
readonly braceExpansion: boolean;
readonly caseSensitiveMatch: boolean;
readonly concurrency: number;
readonly cwd: string;
readonly deep: number;
readonly dot: boolean;
readonly extglob: boolean;
readonly followSymbolicLinks: boolean;
readonly fs: FileSystemAdapter;
readonly globstar: boolean;
readonly ignore: Pattern[];
readonly markDirectories: boolean;
readonly objectMode: boolean;
readonly onlyDirectories: boolean;
readonly onlyFiles: boolean;
readonly stats: boolean;
readonly suppressErrors: boolean;
readonly throwErrorOnBrokenSymbolicLink: boolean;
readonly unique: boolean;
constructor(_options?: Options);
private _getValue;
private _getFileSystemMethods;
}

View File

@ -1,59 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
const fs = require("fs");
const os = require("os");
const fs = require('fs');
const os = require('os');
/**
* The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
* https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
*/
const CPU_COUNT = Math.max(os.cpus().length, 1);
exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
lstat: fs.lstat,
lstatSync: fs.lstatSync,
stat: fs.stat,
statSync: fs.statSync,
readdir: fs.readdir,
readdirSync: fs.readdirSync
lstat: fs.lstat,
lstatSync: fs.lstatSync,
stat: fs.stat,
statSync: fs.statSync,
readdir: fs.readdir,
readdirSync: fs.readdirSync,
};
class Settings {
constructor(_options = {}) {
this._options = _options;
this.absolute = this._getValue(this._options.absolute, false);
this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
this.braceExpansion = this._getValue(this._options.braceExpansion, true);
this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
this.cwd = this._getValue(this._options.cwd, process.cwd());
this.deep = this._getValue(this._options.deep, Infinity);
this.dot = this._getValue(this._options.dot, false);
this.extglob = this._getValue(this._options.extglob, true);
this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
this.fs = this._getFileSystemMethods(this._options.fs);
this.globstar = this._getValue(this._options.globstar, true);
this.ignore = this._getValue(this._options.ignore, []);
this.markDirectories = this._getValue(this._options.markDirectories, false);
this.objectMode = this._getValue(this._options.objectMode, false);
this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
this.onlyFiles = this._getValue(this._options.onlyFiles, true);
this.stats = this._getValue(this._options.stats, false);
this.suppressErrors = this._getValue(this._options.suppressErrors, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
this.unique = this._getValue(this._options.unique, true);
if (this.onlyDirectories) {
this.onlyFiles = false;
}
if (this.stats) {
this.objectMode = true;
}
// Remove the cast to the array in the next major (#404).
this.ignore = [].concat(this.ignore);
constructor(_options = {}) {
this._options = _options;
this.absolute = this._getValue(this._options.absolute, false);
this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
this.braceExpansion = this._getValue(this._options.braceExpansion, true);
this.caseSensitiveMatch = this._getValue(
this._options.caseSensitiveMatch,
true
);
this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
this.cwd = this._getValue(this._options.cwd, process.cwd());
this.deep = this._getValue(this._options.deep, Infinity);
this.dot = this._getValue(this._options.dot, false);
this.extglob = this._getValue(this._options.extglob, true);
this.followSymbolicLinks = this._getValue(
this._options.followSymbolicLinks,
true
);
this.fs = this._getFileSystemMethods(this._options.fs);
this.globstar = this._getValue(this._options.globstar, true);
this.ignore = this._getValue(this._options.ignore, []);
this.markDirectories = this._getValue(this._options.markDirectories, false);
this.objectMode = this._getValue(this._options.objectMode, false);
this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
this.onlyFiles = this._getValue(this._options.onlyFiles, true);
this.stats = this._getValue(this._options.stats, false);
this.suppressErrors = this._getValue(this._options.suppressErrors, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(
this._options.throwErrorOnBrokenSymbolicLink,
false
);
this.unique = this._getValue(this._options.unique, true);
if (this.onlyDirectories) {
this.onlyFiles = false;
}
_getValue(option, value) {
return option === undefined ? value : option;
}
_getFileSystemMethods(methods = {}) {
return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
if (this.stats) {
this.objectMode = true;
}
// Remove the cast to the array in the next major (#404).
this.ignore = [].concat(this.ignore);
}
_getValue(option, value) {
return option === undefined ? value : option;
}
_getFileSystemMethods(methods = {}) {
return Object.assign(
Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER),
methods
);
}
}
exports.default = Settings;

View File

@ -7,25 +7,25 @@ export type Pattern = string;
export type PatternRe = RegExp;
export type PatternsGroup = Record<string, Pattern[]>;
export type ReaderOptions = fsWalk.Options & {
transform(entry: Entry): EntryItem;
deepFilter: DeepFilterFunction;
entryFilter: EntryFilterFunction;
errorFilter: ErrorFilterFunction;
fs: FileSystemAdapter;
stats: boolean;
transform(entry: Entry): EntryItem;
deepFilter: DeepFilterFunction;
entryFilter: EntryFilterFunction;
errorFilter: ErrorFilterFunction;
fs: FileSystemAdapter;
stats: boolean;
};
export type ErrorFilterFunction = fsWalk.ErrorFilterFunction;
export type EntryFilterFunction = fsWalk.EntryFilterFunction;
export type DeepFilterFunction = fsWalk.DeepFilterFunction;
export type EntryTransformerFunction = (entry: Entry) => EntryItem;
export type MicromatchOptions = {
dot?: boolean;
matchBase?: boolean;
nobrace?: boolean;
nocase?: boolean;
noext?: boolean;
noglobstar?: boolean;
posix?: boolean;
strictSlashes?: boolean;
dot?: boolean;
matchBase?: boolean;
nobrace?: boolean;
nocase?: boolean;
noext?: boolean;
noglobstar?: boolean;
posix?: boolean;
strictSlashes?: boolean;
};
export type FileSystemAdapter = fsWalk.FileSystemAdapter;

View File

@ -1,2 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });

View File

@ -1,2 +1,5 @@
export declare function flatten<T>(items: T[][]): T[];
export declare function splitWhen<T>(items: T[], predicate: (item: T) => boolean): T[][];
export declare function splitWhen<T>(
items: T[],
predicate: (item: T) => boolean
): T[][];

View File

@ -1,22 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.splitWhen = exports.flatten = void 0;
function flatten(items) {
return items.reduce((collection, item) => [].concat(collection, item), []);
return items.reduce((collection, item) => [].concat(collection, item), []);
}
exports.flatten = flatten;
function splitWhen(items, predicate) {
const result = [[]];
let groupIndex = 0;
for (const item of items) {
if (predicate(item)) {
groupIndex++;
result[groupIndex] = [];
}
else {
result[groupIndex].push(item);
}
const result = [[]];
let groupIndex = 0;
for (const item of items) {
if (predicate(item)) {
groupIndex++;
result[groupIndex] = [];
} else {
result[groupIndex].push(item);
}
return result;
}
return result;
}
exports.splitWhen = splitWhen;

View File

@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.isEnoentCodeError = void 0;
function isEnoentCodeError(error) {
return error.code === 'ENOENT';
return error.code === 'ENOENT';
}
exports.isEnoentCodeError = isEnoentCodeError;

View File

@ -1,4 +1,7 @@
/// <reference types="node" />
import * as fs from 'fs';
import { Dirent } from '@nodelib/fs.walk';
export declare function createDirentFromStats(name: string, stats: fs.Stats): Dirent;
export declare function createDirentFromStats(
name: string,
stats: fs.Stats
): Dirent;

View File

@ -1,19 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.createDirentFromStats = void 0;
class DirentFromStats {
constructor(name, stats) {
this.name = name;
this.isBlockDevice = stats.isBlockDevice.bind(stats);
this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
this.isDirectory = stats.isDirectory.bind(stats);
this.isFIFO = stats.isFIFO.bind(stats);
this.isFile = stats.isFile.bind(stats);
this.isSocket = stats.isSocket.bind(stats);
this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
}
constructor(name, stats) {
this.name = name;
this.isBlockDevice = stats.isBlockDevice.bind(stats);
this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
this.isDirectory = stats.isDirectory.bind(stats);
this.isFIFO = stats.isFIFO.bind(stats);
this.isFile = stats.isFile.bind(stats);
this.isSocket = stats.isSocket.bind(stats);
this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
}
}
function createDirentFromStats(name, stats) {
return new DirentFromStats(name, stats);
return new DirentFromStats(name, stats);
}
exports.createDirentFromStats = createDirentFromStats;

View File

@ -1,17 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
const array = require("./array");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.string =
exports.stream =
exports.pattern =
exports.path =
exports.fs =
exports.errno =
exports.array =
void 0;
const array = require('./array');
exports.array = array;
const errno = require("./errno");
const errno = require('./errno');
exports.errno = errno;
const fs = require("./fs");
const fs = require('./fs');
exports.fs = fs;
const path = require("./path");
const path = require('./path');
exports.path = path;
const pattern = require("./pattern");
const pattern = require('./pattern');
exports.pattern = pattern;
const stream = require("./stream");
const stream = require('./stream');
exports.stream = stream;
const string = require("./string");
const string = require('./string');
exports.string = string;

View File

@ -1,8 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0;
const os = require("os");
const path = require("path");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.convertPosixPathToPattern =
exports.convertWindowsPathToPattern =
exports.convertPathToPattern =
exports.escapePosixPath =
exports.escapeWindowsPath =
exports.escape =
exports.removeLeadingDotSegment =
exports.makeAbsolute =
exports.unixify =
void 0;
const os = require('os');
const path = require('path');
const IS_WINDOWS_PLATFORM = os.platform() === 'win32';
const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
/**
@ -10,7 +19,8 @@ const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
* Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters.
* Windows: (){}[], !+@ before (, ! at the beginning.
*/
const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
const POSIX_UNESCAPED_GLOB_SYMBOLS_RE =
/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g;
/**
* The device path (\\.\ or \\?\).
@ -27,42 +37,43 @@ const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g;
* Designed to work only with simple paths: `dir\\file`.
*/
function unixify(filepath) {
return filepath.replace(/\\/g, '/');
return filepath.replace(/\\/g, '/');
}
exports.unixify = unixify;
function makeAbsolute(cwd, filepath) {
return path.resolve(cwd, filepath);
return path.resolve(cwd, filepath);
}
exports.makeAbsolute = makeAbsolute;
function removeLeadingDotSegment(entry) {
// We do not use `startsWith` because this is 10x slower than current implementation for some cases.
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
if (entry.charAt(0) === '.') {
const secondCharactery = entry.charAt(1);
if (secondCharactery === '/' || secondCharactery === '\\') {
return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
}
// We do not use `startsWith` because this is 10x slower than current implementation for some cases.
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
if (entry.charAt(0) === '.') {
const secondCharactery = entry.charAt(1);
if (secondCharactery === '/' || secondCharactery === '\\') {
return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
}
return entry;
}
return entry;
}
exports.removeLeadingDotSegment = removeLeadingDotSegment;
exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
function escapeWindowsPath(pattern) {
return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
}
exports.escapeWindowsPath = escapeWindowsPath;
function escapePosixPath(pattern) {
return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
}
exports.escapePosixPath = escapePosixPath;
exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
exports.convertPathToPattern =
IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
function convertWindowsPathToPattern(filepath) {
return escapeWindowsPath(filepath)
.replace(DOS_DEVICE_PATH_RE, '//$1')
.replace(WINDOWS_BACKSLASHES_RE, '/');
return escapeWindowsPath(filepath)
.replace(DOS_DEVICE_PATH_RE, '//$1')
.replace(WINDOWS_BACKSLASHES_RE, '/');
}
exports.convertWindowsPathToPattern = convertWindowsPathToPattern;
function convertPosixPathToPattern(filepath) {
return escapePosixPath(filepath);
return escapePosixPath(filepath);
}
exports.convertPosixPathToPattern = convertPosixPathToPattern;

View File

@ -1,11 +1,17 @@
import { MicromatchOptions, Pattern, PatternRe } from '../types';
type PatternTypeOptions = {
braceExpansion?: boolean;
caseSensitiveMatch?: boolean;
extglob?: boolean;
braceExpansion?: boolean;
caseSensitiveMatch?: boolean;
extglob?: boolean;
};
export declare function isStaticPattern(pattern: Pattern, options?: PatternTypeOptions): boolean;
export declare function isDynamicPattern(pattern: Pattern, options?: PatternTypeOptions): boolean;
export declare function isStaticPattern(
pattern: Pattern,
options?: PatternTypeOptions
): boolean;
export declare function isDynamicPattern(
pattern: Pattern,
options?: PatternTypeOptions
): boolean;
export declare function convertToPositivePattern(pattern: Pattern): Pattern;
export declare function convertToNegativePattern(pattern: Pattern): Pattern;
export declare function isNegativePattern(pattern: Pattern): boolean;
@ -19,7 +25,9 @@ export declare function getPositivePatterns(patterns: Pattern[]): Pattern[];
* // ['./*', '*', 'a/*']
* getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
export declare function getPatternsInsideCurrentDirectory(patterns: Pattern[]): Pattern[];
export declare function getPatternsInsideCurrentDirectory(
patterns: Pattern[]
): Pattern[];
/**
* Returns patterns to be expanded relative to (outside) the current directory.
*
@ -27,23 +35,45 @@ export declare function getPatternsInsideCurrentDirectory(patterns: Pattern[]):
* // ['../*', './../*']
* getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
export declare function getPatternsOutsideCurrentDirectory(patterns: Pattern[]): Pattern[];
export declare function isPatternRelatedToParentDirectory(pattern: Pattern): boolean;
export declare function getPatternsOutsideCurrentDirectory(
patterns: Pattern[]
): Pattern[];
export declare function isPatternRelatedToParentDirectory(
pattern: Pattern
): boolean;
export declare function getBaseDirectory(pattern: Pattern): string;
export declare function hasGlobStar(pattern: Pattern): boolean;
export declare function endsWithSlashGlobStar(pattern: Pattern): boolean;
export declare function isAffectDepthOfReadingPattern(pattern: Pattern): boolean;
export declare function expandPatternsWithBraceExpansion(patterns: Pattern[]): Pattern[];
export declare function isAffectDepthOfReadingPattern(
pattern: Pattern
): boolean;
export declare function expandPatternsWithBraceExpansion(
patterns: Pattern[]
): Pattern[];
export declare function expandBraceExpansion(pattern: Pattern): Pattern[];
export declare function getPatternParts(pattern: Pattern, options: MicromatchOptions): Pattern[];
export declare function makeRe(pattern: Pattern, options: MicromatchOptions): PatternRe;
export declare function convertPatternsToRe(patterns: Pattern[], options: MicromatchOptions): PatternRe[];
export declare function matchAny(entry: string, patternsRe: PatternRe[]): boolean;
export declare function getPatternParts(
pattern: Pattern,
options: MicromatchOptions
): Pattern[];
export declare function makeRe(
pattern: Pattern,
options: MicromatchOptions
): PatternRe;
export declare function convertPatternsToRe(
patterns: Pattern[],
options: MicromatchOptions
): PatternRe[];
export declare function matchAny(
entry: string,
patternsRe: PatternRe[]
): boolean;
/**
* This package only works with forward slashes as a path separator.
* Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
*/
export declare function removeDuplicateSlashes(pattern: string): string;
export declare function partitionAbsoluteAndRelative(patterns: Pattern[]): Pattern[][];
export declare function partitionAbsoluteAndRelative(
patterns: Pattern[]
): Pattern[][];
export declare function isAbsolute(pattern: string): boolean;
export {};

View File

@ -1,9 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
const path = require("path");
const globParent = require("glob-parent");
const micromatch = require("micromatch");
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.isAbsolute =
exports.partitionAbsoluteAndRelative =
exports.removeDuplicateSlashes =
exports.matchAny =
exports.convertPatternsToRe =
exports.makeRe =
exports.getPatternParts =
exports.expandBraceExpansion =
exports.expandPatternsWithBraceExpansion =
exports.isAffectDepthOfReadingPattern =
exports.endsWithSlashGlobStar =
exports.hasGlobStar =
exports.getBaseDirectory =
exports.isPatternRelatedToParentDirectory =
exports.getPatternsOutsideCurrentDirectory =
exports.getPatternsInsideCurrentDirectory =
exports.getPositivePatterns =
exports.getNegativePatterns =
exports.isPositivePattern =
exports.isNegativePattern =
exports.convertToNegativePattern =
exports.convertToPositivePattern =
exports.isDynamicPattern =
exports.isStaticPattern =
void 0;
const path = require('path');
const globParent = require('glob-parent');
const micromatch = require('micromatch');
const GLOBSTAR = '**';
const ESCAPE_SYMBOL = '\\';
const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
@ -17,71 +41,75 @@ const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
*/
const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g;
function isStaticPattern(pattern, options = {}) {
return !isDynamicPattern(pattern, options);
return !isDynamicPattern(pattern, options);
}
exports.isStaticPattern = isStaticPattern;
function isDynamicPattern(pattern, options = {}) {
/**
* A special case with an empty string is necessary for matching patterns that start with a forward slash.
* An empty string cannot be a dynamic pattern.
* For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
*/
if (pattern === '') {
return false;
}
/**
* When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
* filepath directly (without read directory).
*/
if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
return true;
}
if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
return true;
}
/**
* A special case with an empty string is necessary for matching patterns that start with a forward slash.
* An empty string cannot be a dynamic pattern.
* For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
*/
if (pattern === '') {
return false;
}
/**
* When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
* filepath directly (without read directory).
*/
if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
return true;
}
if (
COMMON_GLOB_SYMBOLS_RE.test(pattern) ||
REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) ||
REGEX_GROUP_SYMBOLS_RE.test(pattern)
) {
return true;
}
if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
return true;
}
return false;
}
exports.isDynamicPattern = isDynamicPattern;
function hasBraceExpansion(pattern) {
const openingBraceIndex = pattern.indexOf('{');
if (openingBraceIndex === -1) {
return false;
}
const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
if (closingBraceIndex === -1) {
return false;
}
const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
const openingBraceIndex = pattern.indexOf('{');
if (openingBraceIndex === -1) {
return false;
}
const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
if (closingBraceIndex === -1) {
return false;
}
const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
}
function convertToPositivePattern(pattern) {
return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
}
exports.convertToPositivePattern = convertToPositivePattern;
function convertToNegativePattern(pattern) {
return '!' + pattern;
return '!' + pattern;
}
exports.convertToNegativePattern = convertToNegativePattern;
function isNegativePattern(pattern) {
return pattern.startsWith('!') && pattern[1] !== '(';
return pattern.startsWith('!') && pattern[1] !== '(';
}
exports.isNegativePattern = isNegativePattern;
function isPositivePattern(pattern) {
return !isNegativePattern(pattern);
return !isNegativePattern(pattern);
}
exports.isPositivePattern = isPositivePattern;
function getNegativePatterns(patterns) {
return patterns.filter(isNegativePattern);
return patterns.filter(isNegativePattern);
}
exports.getNegativePatterns = getNegativePatterns;
function getPositivePatterns(patterns) {
return patterns.filter(isPositivePattern);
return patterns.filter(isPositivePattern);
}
exports.getPositivePatterns = getPositivePatterns;
/**
@ -92,7 +120,9 @@ exports.getPositivePatterns = getPositivePatterns;
* getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
function getPatternsInsideCurrentDirectory(patterns) {
return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
return patterns.filter(
(pattern) => !isPatternRelatedToParentDirectory(pattern)
);
}
exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
/**
@ -103,79 +133,86 @@ exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
* getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
*/
function getPatternsOutsideCurrentDirectory(patterns) {
return patterns.filter(isPatternRelatedToParentDirectory);
return patterns.filter(isPatternRelatedToParentDirectory);
}
exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
function isPatternRelatedToParentDirectory(pattern) {
return pattern.startsWith('..') || pattern.startsWith('./..');
return pattern.startsWith('..') || pattern.startsWith('./..');
}
exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
function getBaseDirectory(pattern) {
return globParent(pattern, { flipBackslashes: false });
return globParent(pattern, { flipBackslashes: false });
}
exports.getBaseDirectory = getBaseDirectory;
function hasGlobStar(pattern) {
return pattern.includes(GLOBSTAR);
return pattern.includes(GLOBSTAR);
}
exports.hasGlobStar = hasGlobStar;
function endsWithSlashGlobStar(pattern) {
return pattern.endsWith('/' + GLOBSTAR);
return pattern.endsWith('/' + GLOBSTAR);
}
exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
function isAffectDepthOfReadingPattern(pattern) {
const basename = path.basename(pattern);
return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
const basename = path.basename(pattern);
return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
}
exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
function expandPatternsWithBraceExpansion(patterns) {
return patterns.reduce((collection, pattern) => {
return collection.concat(expandBraceExpansion(pattern));
}, []);
return patterns.reduce((collection, pattern) => {
return collection.concat(expandBraceExpansion(pattern));
}, []);
}
exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
function expandBraceExpansion(pattern) {
const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true });
/**
* Sort the patterns by length so that the same depth patterns are processed side by side.
* `a/{b,}/{c,}/*` `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']`
*/
patterns.sort((a, b) => a.length - b.length);
/**
* Micromatch can return an empty string in the case of patterns like `{a,}`.
*/
return patterns.filter((pattern) => pattern !== '');
const patterns = micromatch.braces(pattern, {
expand: true,
nodupes: true,
keepEscaping: true,
});
/**
* Sort the patterns by length so that the same depth patterns are processed side by side.
* `a/{b,}/{c,}/*` `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']`
*/
patterns.sort((a, b) => a.length - b.length);
/**
* Micromatch can return an empty string in the case of patterns like `{a,}`.
*/
return patterns.filter((pattern) => pattern !== '');
}
exports.expandBraceExpansion = expandBraceExpansion;
function getPatternParts(pattern, options) {
let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
/**
* The scan method returns an empty array in some cases.
* See micromatch/picomatch#58 for more details.
*/
if (parts.length === 0) {
parts = [pattern];
}
/**
* The scan method does not return an empty part for the pattern with a forward slash.
* This is another part of micromatch/picomatch#58.
*/
if (parts[0].startsWith('/')) {
parts[0] = parts[0].slice(1);
parts.unshift('');
}
return parts;
let { parts } = micromatch.scan(
pattern,
Object.assign(Object.assign({}, options), { parts: true })
);
/**
* The scan method returns an empty array in some cases.
* See micromatch/picomatch#58 for more details.
*/
if (parts.length === 0) {
parts = [pattern];
}
/**
* The scan method does not return an empty part for the pattern with a forward slash.
* This is another part of micromatch/picomatch#58.
*/
if (parts[0].startsWith('/')) {
parts[0] = parts[0].slice(1);
parts.unshift('');
}
return parts;
}
exports.getPatternParts = getPatternParts;
function makeRe(pattern, options) {
return micromatch.makeRe(pattern, options);
return micromatch.makeRe(pattern, options);
}
exports.makeRe = makeRe;
function convertPatternsToRe(patterns, options) {
return patterns.map((pattern) => makeRe(pattern, options));
return patterns.map((pattern) => makeRe(pattern, options));
}
exports.convertPatternsToRe = convertPatternsToRe;
function matchAny(entry, patternsRe) {
return patternsRe.some((patternRe) => patternRe.test(entry));
return patternsRe.some((patternRe) => patternRe.test(entry));
}
exports.matchAny = matchAny;
/**
@ -183,24 +220,23 @@ exports.matchAny = matchAny;
* Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
*/
function removeDuplicateSlashes(pattern) {
return pattern.replace(DOUBLE_SLASH_RE, '/');
return pattern.replace(DOUBLE_SLASH_RE, '/');
}
exports.removeDuplicateSlashes = removeDuplicateSlashes;
function partitionAbsoluteAndRelative(patterns) {
const absolute = [];
const relative = [];
for (const pattern of patterns) {
if (isAbsolute(pattern)) {
absolute.push(pattern);
}
else {
relative.push(pattern);
}
const absolute = [];
const relative = [];
for (const pattern of patterns) {
if (isAbsolute(pattern)) {
absolute.push(pattern);
} else {
relative.push(pattern);
}
return [absolute, relative];
}
return [absolute, relative];
}
exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative;
function isAbsolute(pattern) {
return path.isAbsolute(pattern);
return path.isAbsolute(pattern);
}
exports.isAbsolute = isAbsolute;

View File

@ -1,17 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.merge = void 0;
const merge2 = require("merge2");
const merge2 = require('merge2');
function merge(streams) {
const mergedStream = merge2(streams);
streams.forEach((stream) => {
stream.once('error', (error) => mergedStream.emit('error', error));
});
mergedStream.once('close', () => propagateCloseEventToSources(streams));
mergedStream.once('end', () => propagateCloseEventToSources(streams));
return mergedStream;
const mergedStream = merge2(streams);
streams.forEach((stream) => {
stream.once('error', (error) => mergedStream.emit('error', error));
});
mergedStream.once('close', () => propagateCloseEventToSources(streams));
mergedStream.once('end', () => propagateCloseEventToSources(streams));
return mergedStream;
}
exports.merge = merge;
function propagateCloseEventToSources(streams) {
streams.forEach((stream) => stream.emit('close'));
streams.forEach((stream) => stream.emit('close'));
}

View File

@ -1,11 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
exports.isEmpty = exports.isString = void 0;
function isString(input) {
return typeof input === 'string';
return typeof input === 'string';
}
exports.isString = isString;
function isEmpty(input) {
return input === '';
return input === '';
}
exports.isEmpty = isEmpty;