UNPKG

wireit

Version:

Upgrade your npm scripts to make them smarter and more efficient

371 lines • 12.4 kB
/** * @license * Copyright 2023 Google LLC * SPDX-License-Identifier: Apache-2.0 */ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { env.stack.push({ async: true }); } return value; }; var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { return function (env) { function fail(e) { env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } var r, s = 0; function next() { while (r = env.stack.pop()) { try { if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); if (r.dispose) { var result = r.dispose.call(r.value); if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); } else s |= 1; } catch (e) { fail(e); } } if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); }; })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }); import * as fs from 'fs/promises'; import * as pathlib from 'path'; import { createReadStream as rawCreateReadStream, createWriteStream as rawCreateWriteStream, } from 'fs'; import { Deferred } from './deferred.js'; import './dispose.js'; import { parsePositiveInteger } from './parse-positive-integer.js'; export { constants } from 'fs'; export class Semaphore { #remaining; #waiting = []; constructor(numSlots) { if (numSlots <= 0) { throw new Error(`numSlots must be positive, got ${numSlots}`); } this.#remaining = numSlots; } async reserve() { while (this.#remaining === 0) { const deferred = new Deferred(); this.#waiting.push(deferred); await deferred.promise; } this.#remaining--; let disposed = false; return { [Symbol.dispose]: () => { if (disposed) { return; } disposed = true; this.#remaining++; if (this.#waiting.length > 0) { this.#waiting.pop()?.resolve(); } }, }; } } /** * This is tricky to get right. There's no simple cross-platform way to * determine what our current limits are. Windows it's 512, on macOS it * defaults to 256, and on Linux it varies a lot. * 200 gives us a bit of headroom for other things that might be using * file descriptors in our process, like node internals. */ const DEFAULT_MAX_OPEN_FILES = 200; export const fileBudget = new Semaphore( // getOptions reports an invalid value as an error before any script runs. parsePositiveInteger(process.env['WIREIT_MAX_OPEN_FILES'] ?? '') ?? DEFAULT_MAX_OPEN_FILES); export async function mkdir(path, options) { const reservation = await fileBudget.reserve(); try { return await fs.mkdir(path, options); } finally { reservation[Symbol.dispose](); } } export async function mkdtemp(path) { const reservation = await fileBudget.reserve(); try { return await fs.mkdtemp(path); } finally { reservation[Symbol.dispose](); } } export async function writeFile(path, contents, encoding) { const reservation = await fileBudget.reserve(); try { return await fs.writeFile(path, contents, encoding); } finally { reservation[Symbol.dispose](); } } export async function readFile(path, encoding) { const reservation = await fileBudget.reserve(); try { return await fs.readFile(path, encoding); } finally { reservation[Symbol.dispose](); } } export async function rm(path, options) { const reservation = await fileBudget.reserve(); try { return await fs.rm(path, options); } finally { reservation[Symbol.dispose](); } } export async function lstat(path) { const reservation = await fileBudget.reserve(); try { return await fs.lstat(path); } finally { reservation[Symbol.dispose](); } } export async function realpath(path) { const reservation = await fileBudget.reserve(); try { return await fs.realpath(path); } finally { reservation[Symbol.dispose](); } } export async function stat(path) { const reservation = await fileBudget.reserve(); try { return await fs.stat(path); } finally { reservation[Symbol.dispose](); } } export async function utimes(path, atime, mtime) { const env_1 = { stack: [], error: void 0, hasError: false }; try { const _reservation = __addDisposableResource(env_1, await fileBudget.reserve(), false); return await fs.utimes(path, atime, mtime); } catch (e_1) { env_1.error = e_1; env_1.hasError = true; } finally { __disposeResources(env_1); } } export async function rename(oldPath, newPath) { const env_2 = { stack: [], error: void 0, hasError: false }; try { const _reservation = __addDisposableResource(env_2, await fileBudget.reserve(), false); return await fs.rename(oldPath, newPath); } catch (e_2) { env_2.error = e_2; env_2.hasError = true; } finally { __disposeResources(env_2); } } export async function access(path) { const reservation = await fileBudget.reserve(); try { return await fs.access(path); } finally { reservation[Symbol.dispose](); } } export async function createReadStream(path, options) { const reservation = await fileBudget.reserve(); const stream = rawCreateReadStream(path, options); stream.on('close', () => reservation[Symbol.dispose]()); return stream; } export async function createWriteStream(path) { const reservation = await fileBudget.reserve(); const stream = rawCreateWriteStream(path); stream.on('close', () => reservation[Symbol.dispose]()); return stream; } export async function copyFile(src, dest, flags) { const reservation = await fileBudget.reserve(); try { return await fs.copyFile(src, dest, flags); } finally { reservation[Symbol.dispose](); } } export async function readlink(path, options) { const reservation = await fileBudget.reserve(); try { return await fs.readlink(path, options); } finally { reservation[Symbol.dispose](); } } export async function symlink(target, path, type) { const reservation = await fileBudget.reserve(); try { return await fs.symlink(target, path, type); } finally { reservation[Symbol.dispose](); } } export async function unlink(target) { const reservation = await fileBudget.reserve(); try { return await fs.unlink(target); } finally { reservation[Symbol.dispose](); } } export async function rmdir(target) { const reservation = await fileBudget.reserve(); try { return await fs.rmdir(target); } finally { reservation[Symbol.dispose](); } } export async function readdir(path, options) { const env_3 = { stack: [], error: void 0, hasError: false }; try { const _reservation = __addDisposableResource(env_3, await fileBudget.reserve(), false); return await fs.readdir(path, options); } catch (e_3) { env_3.error = e_3; env_3.hasError = true; } finally { __disposeResources(env_3); } } /** * Deletes a file or a folder tree, like fs.rm with recursive and force, but * stops when the signal aborts. fs.rm takes no signal, so it can't stop part * way through a large tree. * * Deletes in parallel, up to the open file budget, because deleting one file * at a time was several times slower than fs.rm. The signal is checked after * each slot is reserved, so after an abort only the deletions already running * finish. The promise then rejects with the signal's reason. * * @param options.slots Limits the calls in flight at once, if to fewer than * the open file budget. Pass the same Semaphore to several rmTree calls to * limit them together. Node runs file system calls on a pool of 4 threads by * default, in the order they are made. Every other file system call in the * process waits behind the deletions already in flight, which on a slow disk * can take seconds when there are hundreds. */ export async function rmTree(path, { signal, slots } = {}) { const context = { signal, slots }; let stats; try { stats = await reserveUnlessAborted(context, () => fs.lstat(path)); } catch (error) { if (isMissing(error)) { return; } throw error; } await rmTreeEntry(path, stats.isDirectory(), context); } async function rmTreeEntry(path, isDirectory, context) { try { if (!isDirectory) { await reserveUnlessAborted(context, async () => { try { await fs.unlink(path); } catch (error) { if (isMissing(error)) { throw error; } // On Windows, fs.rm retries an EPERM, such as from a read-only file, // after making the file writable. await fs.rm(path, { force: true }); } }); return; } const children = await reserveUnlessAborted(context, () => fs.readdir(path, { withFileTypes: true })); // allSettled, so that this doesn't return while the siblings of a failed // child are still being deleted. const results = await Promise.allSettled(children.map((child) => rmTreeEntry(pathlib.join(path, child.name), child.isDirectory(), context))); const failure = results.find((result) => result.status === 'rejected'); if (failure !== undefined) { throw failure.reason; } await reserveUnlessAborted(context, () => fs.rmdir(path)); } catch (error) { // Something else, such as another Wireit process, deleted it first. if (!isMissing(error)) { throw error; } } } async function reserveUnlessAborted(context, operation) { const env_4 = { stack: [], error: void 0, hasError: false }; try { const _slot = __addDisposableResource(env_4, await context.slots?.reserve(), false); const _reservation = __addDisposableResource(env_4, await fileBudget.reserve(), false); context.signal?.throwIfAborted(); return await operation(); } catch (e_4) { env_4.error = e_4; env_4.hasError = true; } finally { __disposeResources(env_4); } } const isMissing = (error) => error.code === 'ENOENT'; //# sourceMappingURL=fs.js.map