Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ jobs:
- name: Check format
run: npm run format-check

- name: Check format
run: npm run format-check
- name: Check types
run: npm run types-check

- name: Coveralls
uses: coverallsapp/github-action@8d6379e14d29928660c4ba802d8e85393440b329 # v2.3.8
Expand Down
62 changes: 62 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* Creates a ReadableStream that emits file path objects that match a series of globs.
*
* @param {string | string[]} globs The globs to match against.
* @param {Options} [opt] Configuration for the glob-stream instance.
* @returns {ReadableStream<PathObject>} A stream that emits file path objects that have matched.
*/
export default function globStream(
globs: string | string[],
opt?: Options,
): ReadableStream<PathObject>;
/**
* Object of path information for a file matched by glob.
*/
export type PathObject = {
/**
* The current working directory of the matcher.
*/
cwd: string;
/**
* The non-magic portion of the glob that matched.
*/
base: string;
/**
* The absolute file path to the file.
*/
path: string;
};
/**
* A function used to provide a value of uniqueness.
*/
export type UniqueByFunc = (p: PathObject) => unknown;
/**
* Configuration for the glob-stream instance.
*/
export type Options = {
/**
* A property or function to determine uniqueness of a {@link PathObject} - defaults to `"path"`.
*/
uniqueBy?: "base" | "path" | UniqueByFunc | "cwd" | undefined;
/**
* The current working directory - defaults to `process.cwd()`.
*/
cwd?: string | undefined;
/**
* If `true`, the `cwd` value will be used as the `base` on {@link PathObject}.
*/
cwdbase?: boolean | undefined;
/**
* A hardcoded `base` to use on each {@link PathObject}.
*/
base?: string | undefined;
/**
* Paths or globs for the glob instance to exclude.
*/
ignore?: string | string[] | undefined;
/**
* Paths or globs for the glob instance to exclude.
*/
exclude?: string | string[] | undefined;
};
//# sourceMappingURL=index.d.ts.map
1 change: 1 addition & 0 deletions index.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

152 changes: 111 additions & 41 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,39 @@
import fs from "node:fs/promises";
import path from "node:path";
import process from "node:process";
import { deprecate } from "node:util";
import { ReadableStream } from "node:stream/web";

import globParent from "glob-parent";

/**
* @typedef {object} PathObject Object of path information for a file matched by glob.
* @property {string} cwd The current working directory of the matcher.
* @property {string} base The non-magic portion of the glob that matched.
* @property {string} path The absolute file path to the file.
*/

/**
* @typedef {(p: PathObject) => unknown} UniqueByFunc A function used to provide a value of uniqueness.
*/

/**
* @typedef {object} Options Configuration for the glob-stream instance.
* @property {"cwd" | "base" | "path" | UniqueByFunc} [uniqueBy] A property or function to determine uniqueness of a {@link PathObject} - defaults to `"path"`.
* @property {string} [cwd] The current working directory - defaults to `process.cwd()`.
* @property {boolean} [cwdbase] If `true`, the `cwd` value will be used as the `base` on {@link PathObject}.
* @property {string} [base] A hardcoded `base` to use on each {@link PathObject}.
* @property {string | string[]} [ignore] Paths or globs for the glob instance to exclude.
* @property {string | string[]} [exclude] Paths or globs for the glob instance to exclude.
*/

/**
* Validates that all items in an array are strings and at least
* one isn't a negative glob (doesn't start with a `!`).
*
* @param {unknown[]} globs The glob array to validate.
* @returns {asserts globs is string[]}
*/
function validateGlobs(globs) {
let hasPositiveGlob = false;

Expand All @@ -23,14 +52,31 @@ function validateGlobs(globs) {
}
}

/**
* Determines if a glob starts with `!`.
*
* @param {string} glob The glob string to check.
* @returns `true` if the glob string starts with ! or `false` otherwise.
*/
function isNegatedGlob(glob) {
return glob.startsWith("!");
}

/**
* Determines if a glob does not start with a `!`.
*
* @param {string} glob The glob string to check.
* @returns `true` if the glob does not start with `!` or `false` otherwise.
*/
function isPositiveGlob(glob) {
return !isNegatedGlob(glob);
}

/**
* Validates the `uniqueBy` option is of the allowed types.
*
* @param {Options} opts The options to validate.
*/
function validateUniqueBy({ uniqueBy } = {}) {
if (typeof uniqueBy === "function") {
return;
Expand All @@ -47,14 +93,33 @@ function validateUniqueBy({ uniqueBy } = {}) {
throw new Error("The `uniqueBy` option must be a string or function");
}

function isDefined(item) {
return item != null;
/**
* Determines if a value is not `null` or `undefined`.
*
* @param {unknown} value The value to check.
* @returns {boolean} `false` if the value is `null`/`undefined` or `true` otherwise.
*/
function isDefined(value) {
return value != null;
}
const showIgnoreDeprecation = deprecate(
() => {},
"The `ignore` option is deprecated - use `exclude` instead",
);

/**
* Determines if all options are of valid types.
*
* @param {Options} opts The options to validate.
* @returns {asserts opts is {
* uniqueBy: "cwd" | "base" | "path" | UniqueByFunc;
* cwd: string;
* cwdbase: boolean;
* base?: string;
* ignore: string[];
* exclude: string[];
* }}
*/
function validateOptions(opts) {
if (typeof opts.cwd !== "string") {
throw new Error("The `cwd` option must be a string");
Expand Down Expand Up @@ -83,23 +148,32 @@ function validateOptions(opts) {
}
}

/**
* Creates a uniqueness matching function based on a comparator.
*
* @param {"cwd" | "base" | "path" | UniqueByFunc} comparator
* @returns {(p: PathObject) => boolean}
*/
function uniqueBy(comparator) {
const seen = new Set();

if (typeof comparator === "string") {
if (comparator === "cwd") {
return isUniqueByCwd;
return (obj) => isUnique(obj.cwd);
}
if (comparator === "base") {
return isUniqueByBase;
}
if (comparator === "path") {
return isUniqueByPath;
return (obj) => isUnique(obj.base);
}
// Has to be "path" given previous assertions
return (obj) => isUnique(obj.path);
} else {
return isUniqueByFunc;
return (obj) => isUnique(comparator(obj));
}

/**
* @param {string | unknown} value The value to check uniqueness of.
* @returns {boolean} `true` if the value has been seen before or `false` otherwise.
*/
function isUnique(value) {
if (seen.has(value)) {
return false;
Expand All @@ -108,45 +182,32 @@ function uniqueBy(comparator) {
return true;
}
}

function isUniqueByCwd(obj) {
return isUnique(obj.cwd);
}
function isUniqueByBase(obj) {
return isUnique(obj.base);
}
function isUniqueByPath(obj) {
return isUnique(obj.path);
}

function isUniqueByFunc(obj) {
return isUnique(comparator(obj));
}
}

/**
* Creates a ReadableStream that emits file path objects that match a series of globs.
*
* @param {string | string[]} globs The globs to match against.
* @param {Options} [opt] Configuration for the glob-stream instance.
* @returns {ReadableStream<PathObject>} A stream that emits file path objects that have matched.
*/
export default function globStream(globs, opt) {
if (!Array.isArray(globs)) {
globs = [globs];
}

validateGlobs(globs);

const ourOpt = Object.assign(
{},
{
cwd: process.cwd(),
cwdbase: false,
uniqueBy: "path",
exclude: [],
// TODO: deprecate `ignore` option
ignore: [],
},
opt,
{
withFileTypes: true,
followSymlinks: true,
},
);
const ourOpt = {
cwd: process.cwd(),
cwdbase: false,
/** @type {"path"} */
uniqueBy: "path",
exclude: [],
ignore: [],
// Spread user-provided options
...opt,
};
// Normalize `ignore` to array
ourOpt.ignore =
typeof ourOpt.ignore === "string" ? [ourOpt.ignore] : ourOpt.ignore;
Expand Down Expand Up @@ -176,18 +237,27 @@ export default function globStream(globs, opt) {

const isUnique = uniqueBy(ourOpt.uniqueBy);

/**
* @param {string[]} globs
* @param {{ cwd: string, exclude: string[] }} opts
*/
async function* globber(globs, opts) {
const globOpts = {
cwd: opts.cwd,
exclude: opts.exclude,
withFileTypes: true,
followSymlinks: true,
};
for (const glob of globs) {
const globber = fs.glob(glob, opts);
const globIter = globber[Symbol.asyncIterator]();
const globber = fs.glob(glob, globOpts);

// Build the glob parent exactly once for each glob
let parent = globParent(glob);
if (!path.isAbsolute(parent)) {
parent = path.join(opts.cwd, parent);
}

for await (const dirent of globIter) {
for await (const dirent of globber) {
const filepath = path.join(dirent.parentPath, dirent.name);

// Decide on the glob's base path
Expand Down
34 changes: 34 additions & 0 deletions node.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
declare module "node:fs/promises" {
interface GlobOpts {
cwd: string;
exclude: string[];
withFileTypes: boolean;
followSymlinks: boolean;
}
interface Dirent {
parentPath: string;
name: string;
}
function glob(g: string, opts: GlobOpts): AsyncIterable<Dirent>;
}

declare module "node:path" {
function resolve(p1: string): string;
function isAbsolute(p1: string): boolean;
function join(p1: string, p2: string): string;
function normalize(p1: string): string;
}

declare module "node:process" {
function cwd(): string;
}

declare module "node:util" {
function deprecate(fn: () => void, msg: string): () => void;
}

declare module "node:stream/web" {
const ReadableStream: globalThis.ReadableStream & {
from<T>(iter: AsyncIterable<T>): globalThis.ReadableStream<T>;
};
}
17 changes: 16 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading