UNPKG

@commercelayer/cli-dev

Version:
267 lines (262 loc) 11.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const core_1 = require("@oclif/core"); const fs = tslib_1.__importStar(require("fs-extra")); const path = tslib_1.__importStar(require("node:path")); const node_url_1 = require("node:url"); const template_1 = tslib_1.__importDefault(require("lodash/template")); const util_1 = require("../util"); const help_compatibility_1 = require("../help-compatibility"); const normalize = require('normalize-package-data'); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const columns = Number.parseInt(process.env.COLUMNS, 10) || 120; // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const slugify = new (require('github-slugger'))(); const formatDescription = (d) => { let desc = d ? `${d.charAt(0).toUpperCase()}${d.substring(1)}` : ''; if ((desc !== '') && !desc.endsWith('.')) desc += '.'; return desc; }; class Readme extends core_1.Command { static 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: ## Usage <!-- usage --> ## Commands <!-- commands --> Customize the code URL prefix by setting oclif.repositoryPrefix in package.json. `; static flags = { dir: core_1.Flags.string({ description: 'output directory for multi docs', default: 'docs', required: true }), multi: core_1.Flags.boolean({ description: 'create a different markdown page for each topic' }), plugin: core_1.Flags.boolean({ description: 'create a plugin readme doc' }), bin: core_1.Flags.string({ description: 'optional main cli command', dependsOn: ['plugin'] }) }; HelpClass; async run() { const { flags } = await this.parse(Readme); const cwd = process.cwd(); const readmePath = path.resolve(cwd, 'README.md'); const config = await core_1.Config.load({ root: cwd, devPlugins: false, userPlugins: false }); if (flags.bin) config.bin = flags.bin; try { const p = require.resolve('@oclif/plugin-legacy', { paths: [cwd] }); const plugin = new core_1.Plugin({ root: p, type: 'core' }); await plugin.load(); config.plugins.set(plugin.name, plugin); } catch { } await (config).runHook('init', { id: 'readme', argv: this.argv }); this.HelpClass = await (0, core_1.loadHelpClass)(config); let readme = await fs.readFile(readmePath, 'utf8'); let commands = config.commands; commands = commands.filter(c => !c.hidden); commands = commands.filter(c => c.pluginType === 'core'); commands = commands.filter(c => !c.aliases.includes(c.id)); this.debug('commands:', commands.map(c => c.id).length); commands = (0, util_1.uniqBy)(commands, c => c.id); commands = (0, util_1.sortBy)(commands, c => c.id); readme = this.replaceTag(readme, 'usage', flags.plugin ? this.usagePlugin(config) : this.usage(config)); readme = this.replaceTag(readme, 'commands', flags.multi ? this.multiCommands(config, commands, flags.dir) : this.commands(config, commands)); readme = this.replaceTag(readme, 'toc', this.toc(config, readme)); readme = readme.trimEnd(); readme += '\n'; await fs.outputFile(readmePath, 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 -->`) const fixedBody = (body.trim().length === 0) ? body : `\n${body}\n`; return readme.replace(`<!-- ${tag} -->`, `<!-- ${tag} -->\n${fixedBody}<!-- ${tag}stop -->`); } toc(__, readme) { // return readme.split('\n').filter(l => l.startsWith('# ')) return readme.split('\n').filter(l => l.startsWith('## ') && !l.includes('Table of contents') && !l.includes('What is Commerce Layer')) .map(l => l.slice(2).trim()) .map(l => `* [${l}](#${slugify.slug(l)})`) .join('\n'); } usage(config) { /* const versionFlags = ['--version', ...(config.pjson.oclif.additionalVersionFlags ?? []).sort()] const versionFlagsString = `(${versionFlags.join('|')})` */ return [ `\`\`\`sh-session ${config.bin} COMMAND ${config.bin} (-v | version | --version) to check the version of the CLI you have installed. ${config.bin} [COMMAND] (--help | -h) for detailed information about CLI commands. \`\`\`\n`, ].join('\n').trim(); } usagePlugin(config) { return [ `\`\`\`sh-session ${config.bin} COMMAND ${config.bin} [COMMAND] (--help | -h) for detailed information about plugin commands. \`\`\`\n`, ].join('\n').trim(); } multiCommands(config, commands, dir) { 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 = (0, util_1.sortBy)(topics, t => t.name); topics = (0, util_1.uniqBy)(topics, t => t.name); for (const topic of topics) { this.createTopicFile(path.join('.', dir, topic.name.replace(/:/g, '/') + '.md'), config, topic, commands.filter(c => c.id === topic.name || c.id.startsWith(topic.name + ':'))); } return [ '\n', // '# Command Topics\n', ...topics.map(t => { return (0, util_1.compact)([ `* [\`${config.bin} ${t.name}\`](${dir}/${t.name.replace(/:/g, '/')}.md)`, (0, util_1.template)({ config })(formatDescription(t.description)).trim().split('\n')[0], ]).join(' - '); }), ].join('\n').trim() + '\n'; } createTopicFile(file, config, topic, commands) { const bin = `\`${config.bin} ${topic.name}\``; const t = topic; const doc = [ '# ' + bin, '', (0, util_1.template)({ config })(formatDescription(t.description)).trim(), '', this.commands(config, commands), ].join('\n').trim() + '\n'; fs.outputFileSync(file, doc); } commands(config, commands) { return [ ...commands.map(c => { const usage = this.commandUsage(config, c); return `* [\`${config.bin} ${usage}\`](#${slugify.slug(`${config.bin}-${usage}`)})`; }), '', ...commands.map(c => this.renderCommand(config, c)).map(s => s.trim() + '\n'), ].join('\n').trim(); } renderCommand(config, c) { this.debug('rendering command', c.id); const title = (0, util_1.template)({ config, command: c })(formatDescription(c.summary || c.description)).trim().split('\n')[0]; const help = new this.HelpClass(config, { stripAnsi: true, maxWidth: columns }); const wrapper = new help_compatibility_1.HelpCompatibilityWrapper(help); // const header = () => `## \`${config.bin} ${this.commandUsage(config, c)}\`` const header = () => `### \`${config.bin} ${this.commandUsage(config, c)}\``; try { const commandFormatted = wrapper.formatCommand(c).trim(); // .replace(/\$ /g, '') return (0, util_1.compact)([ header(), title, '```sh-session\n' + commandFormatted + '\n```', this.commandCode(config, c), ]).join('\n\n'); } catch (error) { this.error(error.message); } } commandCode(config, c) { const pluginName = c.pluginName; if (!pluginName) return; const plugin = config.getPluginsList().find(p => p.name === c.pluginName); if (!plugin) return; const repo = this.repo(plugin); if (!repo) return; let label = plugin.name; let version = plugin.version; const commandPath = this.commandPath(plugin, c); if (!commandPath) return; if (config.name === plugin.name) { label = commandPath; version = process.env.OCLIF_NEXT_VERSION || version; } const template = plugin.pjson.oclif.repositoryPrefix || '<%- repo %>/blob/v<%- version %>/<%- commandPath %>'; return `_See code: [${label}](${(0, template_1.default)(template)({ repo, version, commandPath, config, c })})_`; } repo(plugin) { const pjson = { ...plugin.pjson }; normalize(pjson); const repo = pjson.repository?.url; if (!repo) return; const url = new node_url_1.URL(repo); if (!['github.com', 'gitlab.com'].includes(url.hostname) && !pjson.oclif.repositoryPrefix) return; return `https://${url.hostname}${url.pathname.replace(/\.git$/, '')}`; } // eslint-disable-next-line valid-jsdoc /** * fetches the path to a command */ commandPath(plugin, c) { const commandsDir = plugin.pjson.oclif.commands; if (!commandsDir) return; let p = path.join(plugin.root, String(commandsDir), ...c.id.split(':')); const libRegex = new RegExp('^lib' + (path.sep === '\\' ? '\\\\' : path.sep)); if (fs.pathExistsSync(path.join(p, 'index.js'))) { p = path.join(p, 'index.js'); } else if (fs.pathExistsSync(p + '.js')) { p += '.js'; } else if (plugin.pjson.devDependencies?.typescript) { // check if non-compiled scripts are available const base = p.replace(plugin.root + path.sep, ''); p = path.join(plugin.root, base.replace(libRegex, 'src' + path.sep)); if (fs.pathExistsSync(path.join(p, 'index.ts'))) { p = path.join(p, 'index.ts'); } else if (fs.pathExistsSync(p + '.ts')) { p += '.ts'; } else return; } else return; p = p.replace(plugin.root + path.sep, ''); if (plugin.pjson.devDependencies?.typescript) { p = p.replace(libRegex, 'src' + path.sep); p = p.replace(/\.js$/, '.ts'); } p = p.replace(/\\/g, '/'); // Replace windows '\' by '/' return p; } commandUsage(config, command) { const arg = (arg) => { const name = arg.name.toUpperCase(); if (arg.required) return `${name}`; return `[${name}]`; }; const id = config.topicSeparator ? command.id.replace(/:/g, config.topicSeparator) : command.id; const defaultUsage = () => { // const flags = Object.entries(command.flags) // .filter(([, v]) => !v.hidden) return (0, util_1.compact)([ id, Object.values(command.args).filter(a => !a.hidden).map(a => arg(a)).join(' '), ]).join(' '); }; const usages = (0, util_1.castArray)(command.usage); return (0, util_1.template)({ config, command })(usages.length === 0 ? defaultUsage() : usages[0]); } } exports.default = Readme;