@anycli/dev-cli
Version:
helpers for anycli CLIs
191 lines (189 loc) • 7.96 kB
JavaScript
;
// tslint:disable no-implicit-dependencies
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = require("@anycli/command");
const Config = require("@anycli/config");
const plugin_help_1 = require("@anycli/plugin-help");
const fs = require("fs-extra");
const path = require("path");
const util_1 = require("../util");
const normalize = require('normalize-package-data');
const requireResolve = require('require-resolve');
class Readme extends command_1.Command {
async run() {
const { flags } = this.parse(Readme);
const config = await Config.load({ root: process.cwd(), devPlugins: false, userPlugins: false });
try {
// @ts-ignore
let p = require.resolve('@anycli/plugin-legacy', { paths: [process.cwd()] });
let plugin = new Config.Plugin({ root: p, type: 'core' });
await plugin.load();
config.plugins.push(plugin);
}
catch (_a) { }
await config.runHook('init', { id: 'readme', argv: this.argv });
let readme = await fs.readFile('README.md', 'utf8');
let commands = config.commands;
commands = commands.filter(c => !c.hidden);
commands = commands.filter(c => c.pluginType === 'core');
this.debug('commands:', commands.map(c => c.id).length);
commands = util_1.uniqBy(commands, c => c.id);
commands = util_1.sortBy(commands, c => c.id);
// if (readme.includes('<!-- toc -->')) {
// } else this.warn('<!-- toc --> not found in README')
readme = this.replaceTag(readme, 'install', this.install(config));
readme = this.replaceTag(readme, 'usage', this.usage(config));
readme = this.replaceTag(readme, 'commands', flags.multi ? this.multiCommands(config, commands) : this.commands(config, commands));
readme = readme.trimRight();
readme += '\n';
await fs.outputFile('README.md', readme);
}
replaceTag(readme, tag, body) {
if (readme.includes(`<!-- ${tag} -->`)) {
if (readme.includes(`<!-- ${tag}stop -->`)) {
readme = readme.replace(new RegExp(`<!-- ${tag} -->(.|\n)*<!-- ${tag}stop -->`, 'm'), `<!-- ${tag} -->`);
}
this.log(`replacing <!-- ${tag} --> in README.md`);
}
return readme.replace(`<!-- ${tag} -->`, `<!-- ${tag} -->\n${body}\n<!-- ${tag}stop -->`);
}
install(config) {
return [
`# Installing ${config.name}\n`,
'with yarn:',
'```\n$ yarn global add ' + config.name + '\n```\n',
'or with npm:',
'```\n$ npm install -g ' + config.name + '\n```\n',
].join('\n').trim();
}
usage(config) {
return [
'# Usage\n',
`\`\`\`sh-session
$ ${config.bin} COMMAND
running command...
$ ${config.bin} (-v|--version|version)
${config.name}/${config.version} (${process.platform}-${process.arch}) node-v${process.versions.node}
$ ${config.bin} --help [COMMAND]
USAGE
$ ${config.bin} COMMAND [OPTIONS]
...
\`\`\`\n`,
].join('\n').trim();
}
multiCommands(config, commands) {
let topics = config.topics;
topics = topics.filter(t => !t.hidden && !t.name.includes(':'));
topics = topics.filter(t => commands.find(c => c.id.startsWith(t.name)));
topics = util_1.sortBy(topics, t => t.name);
topics = util_1.uniqBy(topics, t => t.name);
for (let topic of topics) {
this.createTopicFile(path.join('.', 'docs', topic.name.replace(/:/g, '/') + '.md'), config, topic, commands.filter(c => c.id.startsWith(topic.name)));
}
return [
'# Command Topics\n',
...topics.map(t => {
return util_1.compact([
`* [${config.bin} ${t.name}](docs/${t.name.replace(/:/g, '/')}.md)`,
t.description,
]).join(' - ');
}),
].join('\n').trim() + '\n';
}
createTopicFile(file, config, topic, commands) {
let doc = [
`${config.bin} ${topic.name}`,
'='.repeat(`${config.bin} ${topic.name}`.length),
'',
topic.description,
this.commands(config, commands),
].join('\n').trim() + '\n';
fs.outputFileSync(file, doc);
}
commands(config, commands) {
let rootCommands = commands.filter(c => !c.id.includes(':'));
return [
'# Commands\n',
...commands.map(c => {
return `* [${config.bin} ${this.commandUsage(c)}](#${c.id.replace(/:/g, '')})`;
}),
...rootCommands.map(c => this.renderCommand(config, c, commands)).map(s => s.trim() + '\n'),
].join('\n').trim();
}
renderCommand(config, c, commands, level = 2) {
this.debug('rendering command', c.id);
let title = util_1.template({ config })(c.description || '').split('\n')[0];
const help = new plugin_help_1.default(config, { stripAnsi: true, maxWidth: 120 });
const header = () => '#'.repeat(level) + ` ${c.id}`;
const subcommands = () => {
return commands
.filter(sc => sc.id.startsWith(c.id) && sc.id !== c.id)
.map(c => this.renderCommand(config, c, commands, level + 1))
.map(c => c.trim())
.join('\n\n');
};
return util_1.compact([
header(),
title,
'```\n' + help.command(c).trim() + '\n```',
this.commandCode(config, c),
subcommands(),
]).join('\n\n');
}
commandCode(config, c) {
let pluginName = c.pluginName;
if (!pluginName)
return;
let plugin = config.plugins.find(p => p.name === c.pluginName);
if (!plugin)
return;
normalize(plugin.pjson);
let repo = plugin.pjson.repository;
let commandsDir = plugin.pjson.anycli.commands;
if (!repo || !repo.url || !commandsDir)
return;
if (plugin.name === config.name)
pluginName = process.cwd();
let commandPath = `${pluginName}/${commandsDir}/${c.id.replace(/:/g, '/')}`;
let resolved = requireResolve(commandPath, plugin.root);
if (!resolved) {
process.emitWarning(`command not found commandPath: ${commandPath} root: ${plugin.root}`);
}
commandPath = resolved.src.replace(resolved.pkg.root + '/', '');
if (plugin.pjson.devDependencies.typescript) {
commandPath = commandPath.replace(/^lib\//, 'src/');
commandPath = commandPath.replace(/\.js$/, '.ts');
}
repo = repo.url.split('+')[1].replace(/\.git$/, '');
return `_See code: [${plugin.name}](${repo}/blob/v${plugin.version}/${commandPath})_`;
}
commandUsage(command) {
const arg = (arg) => {
let name = arg.name.toUpperCase();
if (arg.required)
return `${name}`;
return `[${name}]`;
};
const defaultUsage = () => {
const flags = Object.entries(command.flags)
.filter(([, v]) => !v.hidden);
return util_1.compact([
command.id,
command.args.filter(a => !a.hidden).map(a => arg(a)).join(' '),
flags.length && '[OPTIONS]',
]).join(' ');
};
let usages = util_1.castArray(command.usage);
return usages.length === 0 ? defaultUsage() : usages[0];
}
}
Readme.description = `adds commands to README.md in current directory
The readme must have any of the following tags inside of it for it to be replaced or else it will do nothing:
<!-- install -->
<!-- usage -->
<!-- commands -->
`;
Readme.flags = {
multi: command_1.flags.boolean({ description: 'create a different markdown page for each topic' })
};
exports.default = Readme;