-
Notifications
You must be signed in to change notification settings - Fork 1
/
zcli-doc.ts
226 lines (194 loc) · 5.24 KB
/
zcli-doc.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
// deno-lint-ignore-file no-explicit-any
import { path } from "./deps.ts";
import { Command } from "./command.ts";
import { CommandFactory } from "./init.ts";
import { dedent } from "./lib/dedent.ts";
import {
ZcliJson,
zcliJson,
ZcliJsonArgument,
ZcliJsonCommand,
ZcliJsonFlag,
} from "./zcli-json.ts";
import { colors } from "./fmt.ts";
export async function zcliDoc<
Context extends {
meta: { version: string; date?: string; commit?: string };
},
>(
commandFactory: CommandFactory<Context, any>,
root: Command<any, any, any>,
config: ZcliDocConfig = {},
) {
const json = await zcliJson(commandFactory, root);
if (!config.output) {
console.log(toMarkdown(json, config));
} else {
const outputDir = path.dirname(config.output);
try {
Deno.statSync(outputDir);
} catch (_err) {
await Deno.mkdir(outputDir, { recursive: true });
}
await Deno.writeTextFile(config.output, toMarkdown(json, config));
}
}
function toMarkdown(
json: ZcliJson,
config: ZcliDocConfig,
) {
return `${config.title ? `# ${config.title}` : ""}
${config.description ? [...dedent(config.description)].join("\n") : ""}
## Available Commands
| Command | Description |
| ------- | ----------- |
${tableOfContents(json.commands[0], [], config)}
${commandToMarkdown(json.commands[0], [], config).trim()}`.trim();
}
function tableOfContents(
command: ZcliJsonCommand,
path: string[],
config: ZcliDocConfig,
): string {
const name = [...path, command.name].join(" ");
return `
| [**\`${name}\`**](#${formatMarkdownHeaderFragment(`$ ${name}`)}) | ${
(colors.stripColor(command.summary || command.description)).replace(
"\n",
" ",
)
} |
${
command.commands.filter(ignoreFilter(config, path)).map((cmd) =>
tableOfContents(cmd, [...path, command.name], config)
)
.join("\n")
}
`.trim();
}
/**
* Remove non-ASCII characters from a string
*
* @param fragment - Text to format
*/
function formatMarkdownHeaderFragment(fragment: string) {
return fragment
.replace(/[^a-zA-Z0-9 ]/g, "")
.replace(/\s/g, "-")
.toLowerCase();
}
function commandToMarkdown(
command: ZcliJsonCommand,
path: string[],
config: ZcliDocConfig,
): string {
const { name, description, summary, arguments: args, flags } = command;
const localFlags = flags.filter((flag) => !flag.global);
const globalFlags = flags.filter((flag) => flag.global);
return `
---
## \`$ ${[...path, name].join(" ")}\`
${colors.stripColor(description || summary)}
${
!args?.items.length ? "" : `
### Arguments
${colors.stripColor(args.description || args.summary || "")}
| Type | Variadic? | Description |
| ---- | --------- | ------------ |
${args.items.map(argumentToMarkdown).join("\n")}
`
}
${
!localFlags.length ? "" : `
### Flags
| Name | Type | Required? | Default | Description |
| -------- | ---- | --------- | --- | --- |
${localFlags.map(flagToMarkdown).join("\n")}
`
}
${
!globalFlags.length ? "" : `
### Global Flags
These flags are available on all commands.
| Name | Type | Required? | Default | Description |
| -------- | ---- | --------- | --- | --- |
${globalFlags.map(flagToMarkdown).join("\n")}
`
}
[**⇗ Back to top**](#available-commands)
${
command.commands.filter(ignoreFilter(config, path)).map((cmd) =>
commandToMarkdown(cmd, path.concat(name), config)
)
.join("")
}
`;
}
function ignoreFilter(
config: ZcliDocConfig,
path: string[] = [],
) {
return (cmd: ZcliJsonCommand) => {
if (typeof config.ignoreCommands === "function") {
return !config.ignoreCommands(cmd, [...path, cmd.name]);
}
const name = [...path, cmd.name].join(" ");
return !config.ignoreCommands?.includes(name);
};
}
function flagToMarkdown(flag: ZcliJsonFlag): string {
const {
description,
summary,
schema,
required,
default: defaultValue,
} = flag;
return `| ${formatFlagName(flag)} | \`${jsonSchemaToString(schema)}\` | ${
required ? "Yes" : "No"
} | ${defaultValue ? `\`${JSON.stringify(defaultValue)}\`` : ""} | ${
colors.stripColor(description || summary || "").replace("\n", " ")
} |`;
}
function argumentToMarkdown(arg: ZcliJsonArgument): string {
return `| \`${jsonSchemaToString(arg.schema)}\` | ${
arg.variadic ? "Yes" : "No"
} | ${colors.stripColor(arg.summary).replace("\n", " ")} |`;
}
function formatFlagName(flag: ZcliJsonFlag): string {
return [flag.name, ...flag.aliases].map((alias) =>
alias.length === 1 ? `-${alias}` : `--${alias}`
).join(", ");
}
/**
* Convert a JSON schema to a human-readable string
*/
function jsonSchemaToString(schema: any): string {
if (schema.type === "array") {
return `${jsonSchemaToString(schema.items)}[]`;
} else if (schema.enum) {
return schema.enum.map((e: any) => JSON.stringify(e)).join(" \\| ");
} else {
return schema.type + (schema.format ? `(${schema.format})` : "");
}
}
export type ZcliDocConfig = {
/**
* The title of the document
*/
title?: string;
/**
* The description of the document
*/
description?: string;
/**
* Output the markdown to a file at the given path
*/
output?: string;
/**
* Ignore these commands
*/
ignoreCommands?:
| string[]
| ((command: ZcliJsonCommand, path: string[]) => boolean);
};