-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathindex.js
431 lines (377 loc) · 13.9 KB
/
index.js
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
const fs = require('fs');
const Promise = require('bluebird');
const recursive = Promise.promisify(require('recursive-readdir'));
const rimraf = Promise.promisify(require('rimraf'));
const copydir = require('copy-dir');
const path = require('path');
const _ = require('lodash');
const rp = require('request-promise');
const CFError = require('cf-errors');
const TEMP_DIR = path.resolve(__dirname, '../temp');
const TEMPLATE_DIR = path.resolve(__dirname);
const FILES_TO_IGNORE = ['index.js', 'docs.spec.js'];
const baseDir = path.resolve(TEMP_DIR, './content');
const ALLOW_BETA_COMMANDS = process.env.ALLOW_BETA_COMMANDS;
const categoriesOrder = {
completion: 30,
authentication: 31,
'operate on resources': 32,
pipelines: 40,
'pipelines v2 (beta)': 42,
projects: 45,
builds: 50,
contexts: 70,
images: 80,
triggers: 90,
environments: 100,
compositions: 110,
'helm repos': 111,
'predefined pipelines': 120,
'cli config': 121,
teams: 130,
more: 150,
};
const hasSubCommands = async (command) => {
const files = await recursive(path.resolve(__dirname, '../lib/interface/cli/commands'));
let hasSubCommand = false;
for (let j = 0; j < files.length && !hasSubCommand; j++) {
const file = files[j];
if (!file.endsWith('.cmd.js')) {
continue;
}
const currCommand = require(file);
if (_.isEqual(currCommand.parentCommand, command) && !command.isRoot()) {
hasSubCommand = true;
}
}
return hasSubCommand;
};
const getNestedCategories = async (command) => {
let nestedCategory = '';
const categoryArr = [];
let docs = command.prepareDocs();
categoryArr.push(docs.category);
let currCommand = command.parentCommand;
while (currCommand && await hasSubCommands(currCommand)) {
docs = currCommand.prepareDocs();
categoryArr.push(docs.category);
currCommand = currCommand.parentCommand;
}
nestedCategory = categoryArr.pop();
for (let i = categoryArr.length - 1; i >= 0; i--) {
nestedCategory = nestedCategory + '/' + categoryArr[i];
}
if (!nestedCategory) {
nestedCategory = command.prepareDocs().category;
}
return nestedCategory;
};
const deleteTempFolder = async () => {
await rimraf(TEMP_DIR);
};
const copyTemplateToTmp = async () => {
const filePathsToIgnore = _.map(FILES_TO_IGNORE, (file) => {
return path.resolve(TEMPLATE_DIR, file);
});
copydir.sync(TEMPLATE_DIR, TEMP_DIR, (stat, filepath) => {
if (stat === 'file' && filePathsToIgnore.includes(filepath)) {
return false;
} else {
return true;
}
});
};
/**
* creates a specific command content and file
* in case the file already exists in the base docs folder it will extend it
* possible extensions are: HEADER, DESCRIPTION, COMMANDS, ARGUMENTS, OPTIONS
*/
const getWeight = async (command) => {
const docs = command.prepareDocs();
let weight = 0;
if (docs.weight) {
return docs.weight;
}
else {
let parent = command.getParentCommand();
while (parent && !parent.prepareDocs().weight) {
parent = parent.getParentCommand();
}
if (parent) {
weight = parent.prepareDocs().weight;
}
return weight;
}
};
const createCommandFile = async (nestedCategory, command) => {
const docs = command.prepareDocs();
const dir = path.resolve(baseDir, `${(nestedCategory || 'undefined').toLowerCase()}`);
const commandFilePath = path.resolve(dir, `./${docs.title}.md`);
let finalFileString = '';
let skeletonFileExists = false;
if (fs.existsSync(commandFilePath)) {
finalFileString = fs.readFileSync(commandFilePath, 'utf8');
skeletonFileExists = true;
}
// HEADER STRING
let headerString;
const weight = await getWeight(command);
if (docs.subCategory) {
headerString = `+++\ntitle = "${docs.subCategory}"\nweight = ${weight || 100}\n+++\n\n`;
} else {
headerString = `+++\ntitle = "${docs.title}"\nweight = ${weight || 100}\n+++\n\n`;
}
if (skeletonFileExists) {
finalFileString = finalFileString.replace('{{HEADER}}', headerString);
} else {
finalFileString += headerString;
}
// DESCRIPTION STRING
let descriptionString = '### Description\n\n';
descriptionString += `${docs.description}\n\n`;
descriptionString += `${docs.usage}\n`;
if (skeletonFileExists) {
finalFileString = finalFileString.replace('{{DESCRIPTION}}', descriptionString);
} else {
finalFileString += descriptionString;
}
// COMMAND string
const mainCommand = docs.command.shift();
let commandsString = `### Command\n\`${mainCommand}\``;
if (docs.command.length) {
commandsString += `\n\n#### Aliases\n`;
_.forEach(docs.command, (command) => {
commandsString += `\n\n\`${command}\``;
});
}
commandsString += '\n\n';
if (skeletonFileExists) {
finalFileString = finalFileString.replace('{{COMMANDS}}', commandsString);
} else {
finalFileString += commandsString;
}
// ARGUMENTS string
docs.command.shift();
if (docs.positionals.length) {
const argumentsString = `### Arguments\n\nOption | Alias | Default | Description\n--------- | --------- | ----------- | -----------\n${docs.positionals}`;
if (skeletonFileExists) {
finalFileString = finalFileString.replace('{{ARGUMENTS}}', argumentsString);
} else {
finalFileString += argumentsString;
}
}
// OPTIONS string
if (docs.options) {
let optionsString = '';
_.forEach(docs.options, (options, group) => {
optionsString = `### ${group}\n\nOption | Alias | Type | Default | Description\n--------- | --------- | --------- |----------- | -----------\n${options}` + optionsString;
});
if (skeletonFileExists) {
finalFileString = finalFileString.replace('{{OPTIONS}}', optionsString);
} else {
finalFileString += optionsString;
}
}
// EXAMPLES string
if (docs.examples.length) {
const examplesString = `### Examples\n\n${docs.examples}`;
if (skeletonFileExists) {
finalFileString = finalFileString.replace('{{EXAMPLES}}', examplesString);
} else {
finalFileString += examplesString;
}
}
fs.writeFileSync(commandFilePath, finalFileString);
};
const createCategoryFile = async (content, category) => {
const indexFile = path.resolve(baseDir, `./${(category || 'undefined').toLowerCase()}/_index.md`);
const finalContent = content.replace('{{COMMANDS}}', '');
fs.writeFileSync(indexFile, finalContent);
};
/**
* updates the category main file with a specific command
* possible extensions are: HEADER, COMMANDS
*/
const updateCategoryFileArray = async (nestedCategory, command, existingContent) => {
const docs = command.prepareDocs();
const { category } = docs;
const finalCategoryArr = existingContent || {};
// HEADER string
const parent = command.parentCommand;
let title = category;
if (parent) {
const parentdocs = parent.prepareDocs();
if (parentdocs.subCategory) {
title = parentdocs.subCategory;
}
}
const indexFile = path.resolve(baseDir, `./${(nestedCategory || 'undefined').toLowerCase()}/_index.md`);
finalCategoryArr.indexPath = indexFile;
if (!_.isEqual(title.toLowerCase(), 'more') && !_.isEqual(title.toLowerCase(), 'operate on resources')) {
const headerString = `+++\ntitle = "${title}"\nweight = ${categoriesOrder[title.toLowerCase()] || 100}\n+++\n\n`;
finalCategoryArr.header = headerString;
}
else {
finalCategoryArr.header = '';
}
let commandString = '';
const formattedTitle = docs.title.replace(/\s+/g, '-')
.toLowerCase();
commandString += `### [${docs.title}](${formattedTitle})\n`;
commandString += `\`${docs.command[0]}\`\n\n`;
commandString += `${docs.description}\n\n`;
commandString += `${docs.usage}\n\n`;
const newCmd = {};
finalCategoryArr.category = category;
newCmd.weight = await getWeight(command);
newCmd.content = commandString;
if (!finalCategoryArr.commands) {
finalCategoryArr.commands = [];
}
finalCategoryArr.commands.push(newCmd);
return finalCategoryArr;
};
/**
* updates the category main file with a specific command
* possible extensions are: HEADER, COMMANDS
*/
const updateCategoryFileContent = async (finalContent) => {
let finalCategoryFileString = '';
const indexFile = finalContent.indexPath;
if (fs.existsSync(indexFile)) {
finalCategoryFileString = fs.readFileSync(indexFile, 'utf8');
}
finalCategoryFileString += finalContent.header;
const commandArr = finalContent.commands;
commandArr.sort((a, b) => {
return a.weight - b.weight;
});
_.forEach(commandArr, (command) => {
finalCategoryFileString += command.content;
});
return finalCategoryFileString;
};
const upsertCategoryFolder = async (nestedCategory) => {
const dir = path.resolve(baseDir, `${(nestedCategory || 'undefined').toLowerCase()}`);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
};
const createAutomatedDocs = async () => {
const files = await recursive(path.resolve(__dirname, '../lib/interface/cli/commands'));
const categories = {};
const nestedCategories = {};
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.endsWith('.cmd.js')) {
continue;
}
console.log(file);
const command = require(file);
// dont document beta commands currently
if (command.isBetaCommand() && !ALLOW_BETA_COMMANDS) {
continue;
}
// document only in case category field exists and there are no sub commands under it
const docs = command.prepareDocs();
const { category } = docs;
if (!category || await hasSubCommands(command)) {
continue;
}
nestedCategories[category] = await getNestedCategories(command);
const nestedCategory = nestedCategories[category];
categories[category] = await updateCategoryFileArray(nestedCategory, command, categories[category]);
await upsertCategoryFolder(nestedCategory);
await createCommandFile(nestedCategory, command);
}
let categoriesFinalContent = {};
for (let command in categories) {
let f = categories[command];
categoriesFinalContent[f.category] = await updateCategoryFileContent(f);
}
_.forEach(categoriesFinalContent, async (content, category) => {
await createCategoryFile(content, nestedCategories[category]);
});
};
const createDownloadPage = async () => {
const RequestOptions = {
url: 'https://api.github.com/repos/codefresh-io/cli/releases/latest',
headers: {
'User-Agent': 'codefresh-cli-build',
},
json: true,
};
try {
// response example https://docs.github.com/en/rest/releases/releases#get-the-latest-release
const { assets = [] } = await rp(RequestOptions);
const getDownloadUrlFromAssets = (nameRegex) => assets.find((a) => a.name.match(nameRegex))?.browser_download_url;
const downloadLinks = [
{
label: 'Alpine-x64',
downloadUrl: getDownloadUrlFromAssets(/alpine-x64/),
},
{
label: 'Linux-x64',
downloadUrl: getDownloadUrlFromAssets(/linux-x64/),
},
{
label: 'Macos-x64',
downloadUrl: getDownloadUrlFromAssets(/macos-x64/),
},
{
label: 'Windows-x64',
downloadUrl: getDownloadUrlFromAssets(/win-x64/),
},
{
label: 'Alpine-arm64',
downloadUrl: getDownloadUrlFromAssets(/alpine-arm64/),
},
{
label: 'Linux-arm64',
downloadUrl: getDownloadUrlFromAssets(/linux-arm64/),
},
];
const commandFilePath = path.resolve(baseDir, './installation/download.md');
const finalContent =
'+++\n' +
'title = "Download"\n' +
'description = "asd"\n' +
'date = "2017-04-24T18:36:24+02:00"\n' +
'weight = 40\n' +
'+++\n' +
'\n' +
'Navigate to <a href="https://github.com/codefresh-io/cli/releases" target="_blank">Official Releases</a>\n' +
'and download the binary that matches your operating system.<br>\n' +
'We currently support the following OS: <br>\n' +
'<ul>\n' +
downloadLinks.map(({ label, downloadUrl = 'https://github.com/codefresh-io/cli/releases' }) =>
` <li><a href='${downloadUrl}' target="_blank">${label}</a></li>`).join('\n') +
'</ul> \n' +
'\n' +
'After downloading the binary, untar or unzip it and your are good to go.<br>\n' +
'You can also add the binary to your system PATH environment variable so you can use it easily.\n' +
'\n' +
'If your operating system is missing please feel free to open us an issue in our <a href="https://github.com/codefresh-io/cli/issues" target="_blank">Github repository</a>.\n';
fs.writeFileSync(commandFilePath, finalContent);
} catch (err) {
throw new CFError(err);
}
};
const generateDocs = async () => {
await deleteTempFolder();
await copyTemplateToTmp();
await createAutomatedDocs();
await createDownloadPage();
};
const main = async () => {
try {
await generateDocs();
} catch (err) {
console.error(err.stack);
}
};
if (require.main === module) {
main();
} else {
module.exports = generateDocs;
}