@oclif/plugin-warn-if-update-available
Version:
warns if there is a newer version of CLI released
61 lines (60 loc) • 2.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const promises_1 = require("fs/promises");
const path_1 = require("path");
const hook = async function ({ config }) {
const file = (0, path_1.join)(config.cacheDir, 'version');
// Destructure package.json configuration with defaults
const { timeoutInDays = 60, message = '<%= config.name %> update available from <%= chalk.greenBright(config.version) %> to <%= chalk.greenBright(latest) %>.', registry = 'https://registry.npmjs.org', authorization = '', } = config.pjson.oclif['warn-if-update-available'] || {};
const checkVersion = async () => {
try {
// do not show warning if updating
if (process.argv[2] === 'update')
return;
const distTags = JSON.parse(await (0, promises_1.readFile)(file, 'utf8'));
if (config.version.includes('-')) {
// to-do: handle channels
return;
}
const semverGt = await Promise.resolve().then(() => require('semver/functions/gt'));
if (distTags && distTags.latest && semverGt(distTags.latest.split('-')[0], config.version.split('-')[0])) {
const chalk = require('chalk');
// Default message if the user doesn't provide one
const template = require('lodash.template');
this.warn(template(message)(Object.assign({ chalk,
config }, distTags)));
}
}
catch (error) {
if (error.code !== 'ENOENT')
throw error;
}
};
const refreshNeeded = async () => {
if (this.config.scopedEnvVarTrue('FORCE_VERSION_CACHE_UPDATE'))
return true;
try {
const { mtime } = await (0, promises_1.stat)(file);
const staleAt = new Date(mtime.valueOf() + (1000 * 60 * 60 * 24 * timeoutInDays));
return staleAt < new Date();
}
catch (error) {
const debug = require('debug')('update-check');
debug(error);
return true;
}
};
const spawnRefresh = async () => {
const debug = require('debug')('update-check');
debug('spawning version refresh');
(0, child_process_1.spawn)(process.execPath, [(0, path_1.join)(__dirname, '../../../lib/get-version'), config.name, file, config.version, registry, authorization], {
detached: !config.windows,
stdio: 'ignore',
}).unref();
};
await checkVersion();
if (await refreshNeeded())
await spawnRefresh();
};
exports.default = hook;