wireit
Version:
Upgrade your npm scripts to make them smarter and more efficient
218 lines • 8.81 kB
JavaScript
/**
* @license
* Copyright 2022 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 os from 'os';
import { Analyzer } from './analyzer.js';
import { getOptions, packageDir } from './cli-options.js';
import { Executor } from './executor.js';
import { SimpleLogger } from './logging/simple-logger.js';
import { Console } from './logging/logger.js';
import { unreachable } from './util/unreachable.js';
import { WorkerPool } from './util/worker-pool.js';
/** Below this, a sweep finishes before the user wonders why they're waiting. */
const SWEEP_NOTICE_MS = 1000;
/**
* Delete the entries this run evicted, plus anything an earlier run left.
*
* The notice and the cache's messages go to the console rather than the
* logger because the default logger drops cache advisories, which it treats as
* chatty. The GitHub cache prints its must-see warnings the same way.
*/
const sweepTrash = async (cache, signal) => {
if (cache === undefined) {
return;
}
const sweep = cache.sweepTrash({ signal });
const notice = setTimeout(() => {
console.warn('🗑️ Deleting evicted cache entries. ' +
'Ctrl-C is safe; anything left is deleted on the next run.');
}, SWEEP_NOTICE_MS);
let messages;
try {
messages = await sweep;
}
finally {
clearTimeout(notice);
}
for (const message of messages) {
console.warn(message);
}
};
const run = async (options) => {
const env_1 = { stack: [], error: void 0, hasError: false };
try {
const logger = __addDisposableResource(env_1, options.logger, false);
const workerPool = new WorkerPool(options.numWorkers);
const sweepAbort = new AbortController();
let cache;
switch (options.cache) {
case 'local': {
// Import dynamically so that we import fewer unnecessary modules.
const { LocalCache } = await import('./caching/local-cache.js');
cache = new LocalCache(options.cacheMaxEntries, {
shareWorktrees: options.cacheWorktrees,
});
break;
}
case 'github': {
const { GitHubActionsCache } = await import('./caching/github-actions-cache.js');
const cacheResult = await GitHubActionsCache.create(logger);
if (cacheResult.ok) {
cache = cacheResult.value;
}
else {
cache = undefined;
console.warn('⚠️ Error initializing GitHub cache. Caching is disabled for this run');
logger.log({
script: options.script,
...cacheResult.error,
});
}
break;
}
case 'none': {
cache = undefined;
break;
}
default: {
throw new Error(`Unhandled cache: ${unreachable(options.cache)}`);
}
}
if (options.watch) {
const { Watcher } = await import('./watcher.js');
const watcher = new Watcher(options.script, options.extraArgs, logger, workerPool, cache, options.failureMode, options.agent, options.watch);
process.on('SIGINT', () => {
watcher.abort();
sweepAbort.abort();
});
process.on('SIGTERM', () => {
watcher.abort();
sweepAbort.abort();
});
await watcher.watch();
await sweepTrash(cache, sweepAbort.signal);
return { ok: true, value: undefined };
}
else {
const analyzer = new Analyzer(options.agent, logger);
const { config } = await analyzer.analyze(options.script, options.extraArgs);
if (!config.ok) {
return config;
}
const executor = new Executor(config.value, logger, workerPool, cache, options.failureMode, undefined, false);
let sweeping = false;
let sweepStoppedBy;
const onSignal = (signal) => {
executor.abort();
sweepAbort.abort();
if (sweeping) {
sweepStoppedBy ??= signal;
}
};
process.on('SIGINT', onSignal);
process.on('SIGTERM', onSignal);
const { persistentServices, errors } = await executor.execute();
if (persistentServices.size > 0) {
for (const service of persistentServices.values()) {
const result = await service.terminated;
if (!result.ok) {
errors.push(result.error);
}
}
}
logger.printMetrics();
sweeping = true;
await sweepTrash(cache, sweepAbort.signal);
if (sweepStoppedBy !== undefined) {
// The scripts succeeded, but the user asked Wireit to stop. Exit as an
// interrupted process does, so that a shell stops a chain such as
// "npm run build && npm run deploy". Shells report a process ended by
// signal N with status 128 + N: 130 for SIGINT (2), and 143 for SIGTERM
// (15).
process.exitCode = 128 + os.constants.signals[sweepStoppedBy];
}
return errors.length === 0
? { ok: true, value: undefined }
: { ok: false, error: errors };
}
}
catch (e_1) {
env_1.error = e_1;
env_1.hasError = true;
}
finally {
__disposeResources(env_1);
}
};
const optionsResult = await getOptions();
if (!optionsResult.ok) {
// if we can't figure out our options, we can't figure out what logger
// we should use here, so just use the default logger.
const console = new Console(process.stderr, process.stderr);
const logger = new SimpleLogger(packageDir ?? process.cwd(), console);
logger.log(optionsResult.error);
process.exit(1);
}
const options = optionsResult.value;
const result = await run(options);
if (!result.ok) {
for (const failure of result.error) {
options.logger.log(failure);
}
process.exitCode = 1;
}
//# sourceMappingURL=cli.js.map