@clerc/plugin-not-found
Version:
Clerc plugin not found (did you mean)
75 lines (71 loc) • 2.46 kB
JavaScript
import { definePlugin, NoSuchCommandError, NoCommandGivenError } from '@clerc/core';
import { semanticArray } from '@clerc/utils';
import didyoumean from 'didyoumean2';
import * as yc from 'yoctocolors';
const locales = {
"en": {
"notFound.possibleCommands": "Possible commands: %s.",
"notFound.commandNotFound": 'Command "%s" not found.',
"notFound.didyoumean": 'Did you mean "%s"?',
"notFound.commandNotRegisteredNote": "NOTE: You haven't register any command yet."
},
"zh-CN": {
"notFound.possibleCommands": "\u53EF\u80FD\u7684\u547D\u4EE4: %s\u3002",
"notFound.commandNotFound": '\u672A\u627E\u5230\u547D\u4EE4 "%s"\u3002',
"notFound.didyoumean": '\u4F60\u662F\u4E0D\u662F\u6307 "%s"\uFF1F',
"notFound.commandNotRegisteredNote": "\u63D0\u793A: \u4F60\u8FD8\u6CA1\u6709\u6CE8\u518C\u4EFB\u4F55\u547D\u4EE4\u3002"
}
};
const notFoundPlugin = () => definePlugin({
setup: (cli) => {
const { t, add } = cli.i18n;
add(locales);
return cli.interceptor({
enforce: "pre",
fn: (ctx, next) => {
const commandKeys = Object.keys(cli._commands);
const hasCommands = commandKeys.length > 0;
try {
next();
} catch (e) {
if (!(e instanceof NoSuchCommandError || e instanceof NoCommandGivenError)) {
throw e;
}
if (ctx.raw._.length === 0 || e instanceof NoCommandGivenError) {
console.error(t("core.noCommandGiven"));
if (hasCommands) {
console.error(
t(
"notFound.possibleCommands",
semanticArray(commandKeys, cli.i18n)
)
);
}
return;
}
const calledCommandName = e.commandName;
const closestCommandName = didyoumean(
calledCommandName,
commandKeys
);
console.error(
t(
"notFound.commandNotFound",
yc.strikethrough(calledCommandName)
)
);
if (hasCommands && closestCommandName) {
console.error(
t("notFound.didyoumean", yc.bold(closestCommandName))
);
} else if (!hasCommands) {
console.error(t("notFound.commandNotRegisteredNote"));
}
process.stderr.write("\n");
process.exit(2);
}
}
});
}
});
export { notFoundPlugin };