UNPKG

@plugjs/plug

Version:
93 lines 3.59 kB
import { inspect } from 'node:util'; import { assert } from "./asserts.js"; import { mkdir, writeFile } from "./fs.js"; import { assertRelativeChildPath, getAbsoluteParent, getCurrentWorkingDirectory, resolveAbsolutePath, } from "./paths.js"; /** * The {@link Files} class represents a collection of relative path names * identifying some _files_ rooted in a given _directory_. */ export class Files { _directory; _files; /** * Create a new {@link Files} instance rooted in the specified `directory` * relative to the specified {@link Run}'s directory. */ constructor(directory) { this._directory = directory || getCurrentWorkingDirectory(); this._files = []; // Nicety for "console.log" / "util.inspect"... Object.defineProperty(this, inspect.custom, { value: () => ({ directory: this._directory, files: [...this._files], }) }); } /** Return the _directory_ where this {@link Files} is rooted */ get directory() { return this._directory; } /** Return the number of files tracked by this instance. */ get length() { return this._files.length; } /** Return an iterator over all _relative_ files of this instance */ *[Symbol.iterator]() { for (const file of this._files) yield file; } /** Return an iterator over all _absolute_ files of this instance */ *absolutePaths() { for (const file of this) yield resolveAbsolutePath(this._directory, file); } /** Return an iterator over all _relative_ to _absolute_ mappings */ *pathMappings() { for (const file of this) yield [file, resolveAbsolutePath(this._directory, file)]; } static builder(arg) { if (!arg) arg = getCurrentWorkingDirectory(); const directory = typeof arg === 'string' ? arg : arg.directory; const set = typeof arg === 'string' ? new Set() : new Set(arg._files); const instance = new Files(directory); let built = false; return { directory: instance.directory, add(...files) { assert(!built, 'FileBuilder "build()" already called'); for (const file of files) { const relative = assertRelativeChildPath(instance.directory, file); set.add(relative); } return this; }, merge(...args) { assert(!built, 'FileBuilder "build()" already called'); for (const files of args) { for (const file of files.absolutePaths()) { this.add(file); } } return this; }, async write(file, content) { const relative = assertRelativeChildPath(instance.directory, file); const absolute = resolveAbsolutePath(instance.directory, relative); const directory = getAbsoluteParent(absolute); await mkdir(directory, { recursive: true }); await writeFile(absolute, content); this.add(absolute); return absolute; }, build() { assert(!built, 'FileBuilder "build()" already called'); built = true; instance._files.push(...set); instance._files.sort(); return instance; }, }; } } //# sourceMappingURL=files.js.map