This repository has been archived by the owner on Apr 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
readme.ts
235 lines (214 loc) · 8.38 KB
/
readme.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// tslint:disable no-implicit-dependencies
import {Command, flags} from '@oclif/command'
import * as Config from '@oclif/config'
import Help from '@oclif/plugin-help'
import * as fs from 'fs-extra'
import * as _ from 'lodash'
import * as path from 'path'
import {URL} from 'url'
import {castArray, compact, sortBy, template, uniqBy} from '../util'
const normalize = require('normalize-package-data')
const columns = parseInt(process.env.COLUMNS!, 10) || 120
function slugify(input: string): string {
return _.kebabCase(input.trim().replace(/:/g, '')).replace(/[^a-zA-Z0-9\- ]/g, '')
}
export default class Readme extends 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: flags.string({description: 'output directory for multi docs', default: 'docs', required: true}),
multi: flags.boolean({description: 'create a different markdown page for each topic'})
}
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('@oclif/plugin-legacy', {paths: [process.cwd()]})
let plugin = new Config.Plugin({root: p, type: 'core'})
await plugin.load()
config.plugins.push(plugin)
} catch {}
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 = uniqBy(commands, c => c.id)
commands = sortBy(commands, c => c.id)
readme = this.replaceTag(readme, 'usage', 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.trimRight()
readme += '\n'
await fs.outputFile('README.md', readme)
}
replaceTag(readme: string, tag: string, body: string): string {
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 -->`)
}
toc(__: Config.IConfig, readme: string): string {
return readme.split('\n').filter(l => l.startsWith('# '))
.map(l => l.trim().slice(2))
.map(l => `* [${l}](#${slugify(l)})`)
.join('\n')
}
usage(config: Config.IConfig): string {
return [
`\`\`\`sh-session
$ npm install -g ${config.name}
$ ${config.bin} COMMAND
running command...
$ ${config.bin} (-v|--version|version)
${config.name}/${process.env.OCLIF_NEXT_VERSION || config.version} ${process.platform}-${process.arch} node-v${process.versions.node}
$ ${config.bin} --help [COMMAND]
USAGE
$ ${config.bin} COMMAND
...
\`\`\`\n`,
].join('\n').trim()
}
multiCommands(config: Config.IConfig, commands: Config.Command[], dir: string): string {
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 = sortBy(topics, t => t.name)
topics = uniqBy(topics, t => t.name)
for (let 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 [
'# Command Topics\n',
...topics.map(t => {
return compact([
`* [\`${config.bin} ${t.name}\`](${dir}/${t.name.replace(/:/g, '/')}.md)`,
template({config})(t.description || '').trim().split('\n')[0]
]).join(' - ')
}),
].join('\n').trim() + '\n'
}
createTopicFile(file: string, config: Config.IConfig, topic: Config.Topic, commands: Config.Command[]) {
const bin = `\`${config.bin} ${topic.name}\``
let doc = [
bin,
'='.repeat(bin.length),
'',
template({config})(topic.description || '').trim(),
'',
this.commands(config, commands),
].join('\n').trim() + '\n'
fs.outputFileSync(file, doc)
}
commands(config: Config.IConfig, commands: Config.Command[]): string {
return [
...commands.map(c => {
let usage = this.commandUsage(c)
return `* [\`${config.bin} ${usage}\`](#${slugify(`${config.bin}-${usage}`)})`
}),
'',
...commands.map(c => this.renderCommand(config, c)).map(s => s.trim() + '\n'),
].join('\n').trim()
}
renderCommand(config: Config.IConfig, c: Config.Command): string {
this.debug('rendering command', c.id)
let title = template({config})(c.description || '').trim().split('\n')[0]
const help = new Help(config, {stripAnsi: true, maxWidth: columns})
const header = () => `## \`${config.bin} ${this.commandUsage(c)}\``
return compact([
header(),
title,
'```\n' + help.command(c).trim() + '\n```',
this.commandCode(config, c),
]).join('\n\n')
}
commandCode(config: Config.IConfig, c: Config.Command): string | undefined {
let pluginName = c.pluginName
if (!pluginName) return
let plugin = config.plugins.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
let 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}](${_.template(template)({repo, version, commandPath, config, c})})_`
}
private repo(plugin: Config.IPlugin): string | undefined {
const pjson = {...plugin.pjson}
normalize(pjson)
let repo = pjson.repository && pjson.repository.url
if (!repo) return
let url = new URL(repo)
if (!['github.com', 'gitlab.com'].includes(url.hostname)) return
return `https://${url.hostname}${url.pathname.replace(/\.git$/, '')}`
}
/**
* fetches the path to a command
*/
private commandPath(plugin: Config.IPlugin, c: Config.Command): string | undefined {
let commandsDir = plugin.pjson.oclif.commands
if (!commandsDir) return
let p = path.join(plugin.root, 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 = p + '.js'
} else if (plugin.pjson.devDependencies.typescript) {
// check if non-compiled scripts are available
let 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 = 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')
}
return p
}
private commandUsage(command: Config.Command): string {
const arg = (arg: Config.Command.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 compact([
command.id,
command.args.filter(a => !a.hidden).map(a => arg(a)).join(' '),
]).join(' ')
}
let usages = castArray(command.usage)
return usages.length === 0 ? defaultUsage() : usages[0]
}
}