-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocs.ts
More file actions
269 lines (236 loc) · 10.2 KB
/
docs.ts
File metadata and controls
269 lines (236 loc) · 10.2 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
* Copyright 2026, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'node:fs/promises';
import { AnyJson, ensureString } from '@salesforce/ts-types';
import chalk from 'chalk';
import { BaseDitamap } from './ditamap/base-ditamap.js';
import { CLIReference as DitaCLIReference } from './ditamap/cli-reference.js';
import { Command as DitaCommand } from './ditamap/command.js';
import { TopicCommands as DitaTopicCommands } from './ditamap/topic-commands.js';
import { TopicDitamap } from './ditamap/topic-ditamap.js';
import { HelpReference as DitaHelpReference } from './ditamap/help-reference.js';
import { BaseIndex } from './markdown/base-index.js';
import { CLIReference as MarkdownCLIReference } from './markdown/cli-reference.js';
import { Command as MarkdownCommand } from './markdown/command.js';
import { TopicCommands as MarkdownTopicCommands } from './markdown/topic-commands.js';
import { TopicIndex } from './markdown/topic-index.js';
import { HelpReference as MarkdownHelpReference } from './markdown/help-reference.js';
import { CliMeta, events, punctuate, SfTopic, SfTopics, CommandClass } from './utils.js';
type TopicsByTopicsByTopLevel = Map<string, Map<string, CommandClass[]>>;
function emitNoTopicMetadataWarning(topic: string): void {
events.emit(
'warning',
`No metadata for topic ${chalk.bold(
topic
)}. That topic owner must add topic metadata in the oclif section in the package.json file within their plugin.`
);
}
export class Docs {
public constructor(
private outputDir: string,
private hidden: boolean,
private topicMeta: SfTopics,
private cliMeta: CliMeta,
private format: 'dita' | 'markdown' = 'dita'
) {}
public async build(commands: CommandClass[]): Promise<void> {
// Create if doesn't exist
await fs.mkdir(this.outputDir, { recursive: true });
await this.populateTemplate(commands);
}
public async populateTopic(topic: string, subtopics: Map<string, CommandClass[]>): Promise<AnyJson[]> {
const topicMeta = this.topicMeta.get(topic);
if (!topicMeta) {
throw new Error(`No topic meta for ${topic} - add this topic to the oclif section of the package.json.`);
}
let description = topicMeta.description;
if (!description && !topicMeta.external) {
// TODO: check why the same property is used again when it is already used above
description = punctuate(topicMeta.description);
if (!description) {
events.emit(
'warning',
`No description for topic ${chalk.bold(
topic
)}. Skipping until topic owner adds topic metadata in the oclif section in the package.json file within their plugin.`
);
return [];
}
}
const subTopicNames = [];
const commandIds = [];
for (const [subtopic, classes] of subtopics.entries()) {
try {
// const subTopicsMeta = topicMeta.subtopics;
// if (!subTopicsMeta?.get(subtopic)) {
// emitNoTopicMetadataWarning(`${topic}:${subtopic}`);
// continue;
// }
subTopicNames.push(subtopic);
// Commands within the sub topic
for (const command of classes) {
const fullTopic = ensureString(command.id).replace(/:\w+$/, '');
const commandsInFullTopic = classes.filter((cmd) => ensureString(cmd.id).startsWith(fullTopic));
const commandMeta = this.resolveCommandMeta(ensureString(command.id), command, commandsInFullTopic.length);
// eslint-disable-next-line no-await-in-loop
await this.populateCommand(topic, subtopic, command, commandMeta);
commandIds.push(command.id);
}
} catch (error) {
const err =
error instanceof Error ? error : typeof error === 'string' ? new Error(error) : new Error('Unknown error');
if (err.name === 'UnexpectedValueTypeError') {
emitNoTopicMetadataWarning(`${topic}:${subtopic}`);
} else {
events.emit('warning', `Can't create topic for ${topic}:${subtopic}: ${err.message}\n`);
}
}
}
// The topic ditamap with all of the subtopic links.
events.emit('subtopics', topic, subTopicNames);
if (this.format === 'markdown') {
await new MarkdownTopicCommands(topic, topicMeta).write();
await new TopicIndex(topic, commandIds).write();
} else {
await new DitaTopicCommands(topic, topicMeta).write();
await new TopicDitamap(topic, commandIds).write();
}
return subTopicNames;
}
/**
* Group all commands by the top level topic and then subtopic. e.g. force, analytics, evergreen, etc
* then org, apex, etc within the force namespace.
*
* @param commands - The entire set of command data.
* @returns The commands grouped by topics/subtopic/commands.
*/
private groupTopicsAndSubtopics(commands: CommandClass[]): TopicsByTopicsByTopLevel {
// const topLevelTopics: Dictionary<Dictionary<CommandClass | CommandClass[]>> = {};
const topLevelTopics = new Map<string, Map<string, CommandClass[]>>();
for (const command of commands) {
if (command.hidden && !this.hidden) {
continue;
}
const commandParts = ensureString(command.id).split(':');
const topLevelTopic = commandParts[0];
const plugin = command.plugin;
if (plugin) {
// Also include the namespace on the commands so we don't need to do the split at other times in the code.
command.topic = topLevelTopic;
const existingTopicsForTopLevel = topLevelTopics.get(topLevelTopic) ?? new Map<string, CommandClass[]>();
if (commandParts.length === 1) {
// This is a top-level topic that is also a command
const existingTarget = existingTopicsForTopLevel.get(commandParts[0]) ?? [];
existingTopicsForTopLevel.set(commandParts[0], [...existingTarget, command]);
} else if (commandParts.length === 2) {
// This is a command directly under the top-level topic
const existingTarget = existingTopicsForTopLevel.get(commandParts[1]) ?? [];
existingTopicsForTopLevel.set(commandParts[1], [...existingTarget, command]);
} else {
const subtopic = commandParts[1];
try {
const topicMeta = this.topicMeta.get(topLevelTopic);
const subTopicsMeta = topicMeta?.subtopics?.get(subtopic);
if (subTopicsMeta?.hidden && !this.hidden) {
continue;
}
} catch (e) {
// It means no meta so it isn't hidden, although it should always fail before here with no meta found
}
command.subtopic = subtopic;
const subtopicCommands = existingTopicsForTopLevel.get(subtopic) ?? [];
existingTopicsForTopLevel.set(subtopic, [...subtopicCommands, command]);
}
topLevelTopics.set(topLevelTopic, existingTopicsForTopLevel);
}
}
return topLevelTopics;
}
private async populateTemplate(commands: CommandClass[]): Promise<void> {
const topicsAndSubtopics = this.groupTopicsAndSubtopics(commands);
if (this.format === 'markdown') {
await new MarkdownCLIReference().write();
await new MarkdownHelpReference().write();
await new BaseIndex(Array.from(topicsAndSubtopics.keys())).write();
} else {
await new DitaCLIReference().write();
await new DitaHelpReference().write();
await new BaseDitamap(Array.from(topicsAndSubtopics.keys())).write();
}
for (const [topic, subtopics] of topicsAndSubtopics.entries()) {
events.emit('topic', { topic });
// eslint-disable-next-line no-await-in-loop
await this.populateTopic(topic, subtopics);
}
}
private resolveCommandMeta(
commandId: string,
command: CommandClass,
commandsInTopic: number
): Record<string, unknown> {
const commandMeta = Object.assign({}, this.cliMeta);
// Remove top level topic, since the topic meta is already for that topic
const commandParts = commandId.split(':');
let part: string | undefined;
try {
let currentMeta: SfTopic | undefined;
for (part of commandParts) {
if (currentMeta) {
const subtopics = currentMeta.subtopics;
currentMeta = subtopics?.get(part);
} else {
currentMeta = this.topicMeta.get(part);
}
// Collect all tiers of the meta, so the command will also pick up the topic state (isPilot, etc) if applicable
Object.assign({}, commandMeta, currentMeta);
}
} catch (error) {
// @ts-expect-error: part may be undefined
if (commandId.endsWith(part)) {
// This means there wasn't meta information going all the way down to the command, which is ok.
return commandMeta;
} else if (commandsInTopic !== 1) {
events.emit('warning', `subtopic "${part}" meta not found for command ${commandId}`);
} else if (!commandMeta.description) {
commandMeta.description = command.description;
commandMeta.longDescription = (
command.longDescription ? command.longDescription : punctuate(command.description)
) as AnyJson;
}
}
return commandMeta;
}
private async populateCommand(
topic: string,
subtopic: string | null,
command: CommandClass,
commandMeta: Record<string, unknown>
): Promise<string> {
// If it is a hidden command - abort
if (command.hidden && !this.hidden) {
return '';
}
if (this.format === 'markdown') {
const commandMarkdown = new MarkdownCommand(topic, subtopic, command, commandMeta);
await commandMarkdown.write();
return commandMarkdown.getFilename();
} else {
const commandDitamap = new DitaCommand(topic, subtopic, command, commandMeta);
await commandDitamap.write();
return commandDitamap.getFilename();
}
}
}