-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·287 lines (257 loc) · 8.51 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
#!/usr/bin/env node
const json2md = require('json2md');
const globby = require('globby');
const path = require('path');
const { lstat, writeFile, readFile } = require('fs/promises');
const pkgUp = require('pkg-up');
const regexEscape = require('regex-escape');
const flat = require('flat');
const generatedHeader = 'DO NOT EDIT THIS FILE';
const logging = {
verbose: false,
};
function replaceComment(blockName, string) {
logging.verbose && console.log(`Creating block <!-- ${blockName} -->`);
const reBlock = regexEscape(blockName);
const regExp = new RegExp(`<!--\\s+${reBlock}\\s+(.*?)-->|^`, 'gs');
return (template) => {
let match = template.match(regExp);
if (match) {
logging.verbose && console.log(`Found comment <!-- ${blockName} -->, replacing`);
return template.replace(regExp, `<!-- ${blockName} ${string.trim()} -->\n`);
} else {
return template;
}
};
}
async function buildReadme(argv) {
const {
packages,
outFile,
inFile = outFile,
project = path.dirname(await pkgUp()),
dry,
recursive,
skipGeneratedHeader,
keepTags: _keepTags,
create,
custom,
contextLinkBlocks = [],
} = argv;
const packageJsons = packages
? await globby([path.join(path.resolve(project, packages), '*', 'package.json')])
: [];
const outFilePath = path.resolve(project, outFile);
const inFilePath = path.resolve(project, inFile);
const keepTags = _keepTags || outFilePath === inFilePath;
function replaceBlock(blockName, string) {
logging.verbose && console.log(`Creating block <!-- ${blockName} -->`);
const reBlock = regexEscape(blockName);
const regExp = new RegExp(
`<!--\\s+${reBlock}\\s+-->([\\s\\n]*)(.*?([\\s\\n]*)<!-- ${reBlock} end -->)?`,
'gs',
);
return (template) => {
let match = template.match(regExp);
if (match) {
logging.verbose && console.log(`Found <!-- ${blockName} -->, replacing`);
return template.replace(
regExp,
keepTags
? `<!-- ${blockName} -->$1${string.trim()}$3<!-- ${blockName} end -->`
: `$1${string.trim()}$3`,
);
} else {
return template;
}
};
}
async function loadCustomBlocks(custom, project) {
if (custom) {
let customBlocksModule = require(path.resolve(project, custom));
let customBlocksDefinitions =
typeof customBlocksModule === 'function' ? await customBlocksModule() : customBlocksModule;
return Object.entries(customBlocksDefinitions).map(([name, contents]) => {
return replaceBlock(name, typeof contents === 'string' ? contents : json2md(contents));
});
} else {
return [];
}
}
logging.verbose && console.log('Processing', outFilePath);
const customBlocks = await loadCustomBlocks(custom, project);
const packagesBlock = await Promise.all(
packageJsons.map(async (packageFile) => {
const packageDir = path.dirname(packageFile);
const dirName = path.basename(packageDir);
const packageDetails = require(packageFile);
const packageReadmeFile = path.join(packageDir, packageDetails.readme || 'README.md');
const packageReadmeExists = await lstat(packageReadmeFile)
.then(() => true)
.catch(() => false);
return [
{ h2: dirName },
{
p: [
...(packageReadmeExists
? [
{
link: {
title: packageDetails.name,
source: path.relative(path.dirname(outFilePath), packageReadmeFile),
},
},
]
: [`\`${packageDetails.name}\``]),
],
},
...(packageDetails.description ? [{ p: packageDetails.description }] : []),
];
}),
);
const projectPackageFile = path.join(project, 'package.json');
const projectPackageDetails = require(projectPackageFile);
const titleBlock = [{ h1: projectPackageDetails.name }];
const flatPackage = flat(projectPackageDetails);
const rootPackageJsonBlocks = [
...Object.keys(flatPackage)
.filter((key) => typeof flatPackage[key] === 'string' || typeof flatPackage[key] === 'number')
.map((key) => replaceBlock(key, json2md([{ p: flatPackage[key] }]))),
replaceBlock('title', json2md(titleBlock)),
];
const outFileContents = await readFile(inFilePath)
.catch((e) => {
if (create && e.errno === -2) {
return readFile(path.resolve(__dirname, 'README.example.md'));
} else {
throw e;
}
})
.then((data) => data.toString());
const linkBlocks =
packageJsons.length > 0
? await Promise.all(
packageJsons.map(async (packageFile) => {
const packageDir = path.dirname(packageFile);
const dirName = path.basename(packageDir);
return replaceBlock(
`link ${dirName}`,
json2md([{ link: { title: dirName, source: `#${dirName}` } }]),
);
}),
)
: [];
const thisBlock = [{ p: outFile }];
const generatedComment = `It is generated from ${inFile}, edit that file instead.`;
const linkThisBlock = [{ link: { title: outFile, source: outFile } }];
const mdResult = [
...(skipGeneratedHeader ? [] : [replaceComment(generatedHeader, generatedComment)]),
...rootPackageJsonBlocks,
replaceBlock('packages', json2md(packagesBlock)),
replaceBlock('this', json2md(thisBlock)),
replaceBlock('link this', json2md(linkThisBlock)),
...linkBlocks,
...contextLinkBlocks,
...customBlocks,
].reduce((template, mutator) => mutator(template), outFileContents);
if (dry) {
console.log('--- ', outFilePath);
console.log(mdResult);
} else {
console.log('Writing', path.relative(process.cwd(), outFilePath));
await writeFile(outFilePath, mdResult);
}
if (recursive) {
for (const packageFile of packageJsons) {
const packageDir = path.dirname(packageFile);
const dirName = path.basename(packageDir);
const packageDetails = require(packageFile);
const packageReadmeFile = path.join(packageDir, packageDetails.readme || 'README.md');
try {
await buildReadme({
recursive: false,
packages: false,
outFile: packageReadmeFile,
project: packageDir,
create: false,
contextLinkBlocks: [...contextLinkBlocks, ...linkBlocks],
dry,
});
} catch (e) {
if (e.errno === -2) {
logging.verbose &&
console.log(`Ignoring ${dirName} from recursive building, missing readme file.`);
} else {
throw e;
}
}
}
}
}
async function main() {
const { argv } = require('yargs')
.option('outFile', {
alias: 'o',
required: true,
default: 'README.md',
describe: 'output file path. Can be relative to project root or absolute',
})
.option('inFile', {
alias: 'i',
required: false,
default: 'README.md',
describe:
'input/template file path. Can be relative to project root or absolute. If inFile is used, outFile will not contain template comment tags, unless keepTags option is set.',
})
.option('packages', {
required: false,
default: 'packages/',
describe: 'packages directory location',
})
.option('keepTags', {
required: false,
boolean: true,
default: false,
describe: 'keep template tags even if inFile is used.',
})
.option('project', {
required: false,
describe: 'root project location',
})
.option('dry', {
boolean: true,
describe: 'do not write output file, print results to stdout instead',
})
.option('skipGeneratedHeader', {
boolean: true,
default: false,
required: false,
describe: `Do not add "${generatedHeader}" header to output files when template file is used`,
})
.option('recursive', {
alias: 'r',
default: true,
describe: 'should also update readme files in packages',
})
.option('create', {
default: true,
describe: 'create readme file if one does not exist yet',
})
.option('verbose', {
alias: 'v',
boolean: true,
default: false,
describe: 'display verbose output',
})
.option('custom', {
required: false,
describe: 'load custom block definitions from file (js or json)',
})
.help();
logging.verbose = argv.verbose && !argv.dry;
await buildReadme(argv);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});