@mondarth/create-docs 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/check.js +105 -0
- package/dist/cli.js +273 -0
- package/dist/errors.js +4 -0
- package/dist/manifest.js +87 -0
- package/dist/publish.js +96 -0
- package/dist/scaffold.js +148 -0
- package/dist/templates.js +304 -0
- package/dist/version.js +34 -0
- package/package.json +30 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ulenar of Mondarth
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/check.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { KEY_SECRET } from './templates.js';
|
|
3
|
+
/** The GitHub CLI on this machine. */
|
|
4
|
+
export const gh = args => new Promise(resolve => {
|
|
5
|
+
execFile('gh', args, { encoding: 'utf8' }, (error, stdout, stderr) => {
|
|
6
|
+
resolve({ ok: error === null, stdout: stdout.trim(), stderr: stderr.trim() });
|
|
7
|
+
});
|
|
8
|
+
});
|
|
9
|
+
/** What the set's repository still needs, by audience: what create-docs prints when it has written a set. */
|
|
10
|
+
export function setupStep(manifest, branch) {
|
|
11
|
+
return manifest.audience === 'internal'
|
|
12
|
+
? `In the repository's Settings > Pages, set Source to GitHub Actions. Then, in Settings > Environments >` +
|
|
13
|
+
` github-pages > Deployment branches and tags, make sure ${branch} may deploy.`
|
|
14
|
+
: `Add the upload key for ${manifest.product}/${manifest.set} on docs.mondarth.com as the repository secret` +
|
|
15
|
+
` ${KEY_SECRET}: \`gh secret set ${KEY_SECRET}\`, and paste the key.`;
|
|
16
|
+
}
|
|
17
|
+
/** Whether the branch is one a deployment branch policy's name, a branch name or a pattern of `*`s, allows. */
|
|
18
|
+
function allows(pattern, branch) {
|
|
19
|
+
const expression = pattern
|
|
20
|
+
.split('*')
|
|
21
|
+
.map(part => part.replaceAll(/[.+?^${}()|[\]\\]/g, '\\$&'))
|
|
22
|
+
.join('.*');
|
|
23
|
+
return new RegExp(`^${expression}$`).test(branch);
|
|
24
|
+
}
|
|
25
|
+
async function checkPages(run, repo, branch) {
|
|
26
|
+
const pages = await run(['api', `repos/${repo}/pages`, '--jq', '.build_type']);
|
|
27
|
+
if (!pages.ok) {
|
|
28
|
+
return [{ ok: false, message: `GitHub Pages is off: Settings > Pages > Source: GitHub Actions` }];
|
|
29
|
+
}
|
|
30
|
+
if (pages.stdout !== 'workflow') {
|
|
31
|
+
return [
|
|
32
|
+
{
|
|
33
|
+
ok: false,
|
|
34
|
+
message: `GitHub Pages is built from a branch: Settings > Pages > Source must be GitHub Actions`,
|
|
35
|
+
},
|
|
36
|
+
];
|
|
37
|
+
}
|
|
38
|
+
const findings = [{ ok: true, message: 'GitHub Pages is built by GitHub Actions' }];
|
|
39
|
+
// The environment GitHub makes as Pages is turned on, which allows the default branch alone.
|
|
40
|
+
const environment = await run([
|
|
41
|
+
'api',
|
|
42
|
+
`repos/${repo}/environments/github-pages`,
|
|
43
|
+
'--jq',
|
|
44
|
+
'.deployment_branch_policy // {} | [.protected_branches // false, .custom_branch_policies // false] | @tsv',
|
|
45
|
+
]);
|
|
46
|
+
if (!environment.ok) {
|
|
47
|
+
findings.push({ ok: true, message: 'The github-pages environment is made at the first deployment' });
|
|
48
|
+
return findings;
|
|
49
|
+
}
|
|
50
|
+
const [protectedOnly, custom] = environment.stdout.split('\t');
|
|
51
|
+
if (custom === 'true') {
|
|
52
|
+
const policies = await run([
|
|
53
|
+
'api',
|
|
54
|
+
`repos/${repo}/environments/github-pages/deployment-branch-policies`,
|
|
55
|
+
'--jq',
|
|
56
|
+
'.branch_policies[] | select(.type == "branch") | .name',
|
|
57
|
+
]);
|
|
58
|
+
const names = policies.stdout.split('\n').filter(name => name !== '');
|
|
59
|
+
findings.push(names.some(name => allows(name, branch))
|
|
60
|
+
? { ok: true, message: `The github-pages environment allows ${branch}` }
|
|
61
|
+
: {
|
|
62
|
+
ok: false,
|
|
63
|
+
message: `The github-pages environment does not allow ${branch}: add it in Settings > Environments >` +
|
|
64
|
+
` github-pages > Deployment branches and tags`,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
else if (protectedOnly === 'true') {
|
|
68
|
+
findings.push({
|
|
69
|
+
ok: true,
|
|
70
|
+
message: `The github-pages environment allows protected branches: ${branch} must be one`,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
findings.push({ ok: true, message: 'The github-pages environment allows every branch' });
|
|
75
|
+
}
|
|
76
|
+
return findings;
|
|
77
|
+
}
|
|
78
|
+
async function checkKey(run, repo) {
|
|
79
|
+
const secrets = await run(['secret', 'list', '--repo', repo, '--json', 'name', '--jq', '.[].name']);
|
|
80
|
+
if (!secrets.ok) {
|
|
81
|
+
return [
|
|
82
|
+
{ ok: false, message: `Cannot list the repository's secrets: ${secrets.stderr || 'gh secret list failed'}` },
|
|
83
|
+
];
|
|
84
|
+
}
|
|
85
|
+
return secrets.stdout.split('\n').includes(KEY_SECRET)
|
|
86
|
+
? [{ ok: true, message: `The upload key is set (${KEY_SECRET})` }]
|
|
87
|
+
: [{ ok: false, message: `The upload key is not set: ${KEY_SECRET} is not among the repository's secrets` }];
|
|
88
|
+
}
|
|
89
|
+
/** Checks the set's repository is set up to publish it, as its audience requires. */
|
|
90
|
+
export async function check(manifest, branch, run = gh) {
|
|
91
|
+
const auth = await run(['auth', 'status']);
|
|
92
|
+
if (!auth.ok) {
|
|
93
|
+
return [
|
|
94
|
+
{
|
|
95
|
+
ok: false,
|
|
96
|
+
message: 'The GitHub CLI is needed to check, logged in: install it (https://cli.github.com), run `gh auth login`',
|
|
97
|
+
},
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
const repo = await run(['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner']);
|
|
101
|
+
if (!repo.ok || repo.stdout === '') {
|
|
102
|
+
return [{ ok: false, message: 'This is not a GitHub repository the GitHub CLI knows: push it to GitHub first' }];
|
|
103
|
+
}
|
|
104
|
+
return manifest.audience === 'internal' ? checkPages(run, repo.stdout, branch) : checkKey(run, repo.stdout);
|
|
105
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { access, readFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname, join, posix } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline/promises';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { parseArgs, promisify } from 'node:util';
|
|
8
|
+
import { check, gh, setupStep } from './check.js';
|
|
9
|
+
import { CreateDocsError } from './errors.js';
|
|
10
|
+
import { AUDIENCES, SLUG, problemsOf, readManifest, requireManifest, } from './manifest.js';
|
|
11
|
+
import { SITE, publish } from './publish.js';
|
|
12
|
+
import { readLock, scaffold } from './scaffold.js';
|
|
13
|
+
import { KEY_SECRET } from './templates.js';
|
|
14
|
+
import { documentedPackage, tagPrefixOf } from './version.js';
|
|
15
|
+
const HELP = `Adds a documentation set, built with Mondarth's Sphinx theme, to the repository, or brings it up to date.
|
|
16
|
+
Run it from the repository's root.
|
|
17
|
+
|
|
18
|
+
create-docs [options] write the set in --dir, or bring it up to date
|
|
19
|
+
create-docs check [--dir] check the repository is set up to publish the set
|
|
20
|
+
create-docs version [--dir] print the version of the package the set documents
|
|
21
|
+
create-docs publish --dir <dir> --version <version>
|
|
22
|
+
upload a public set's build to docs.mondarth.com (key: ${KEY_SECRET})
|
|
23
|
+
|
|
24
|
+
Options:
|
|
25
|
+
--dir <path> the set's folder (docs)
|
|
26
|
+
--product <name> the product it documents, as in /<product>/<set>/ (emma)
|
|
27
|
+
--set <name> the set (extension)
|
|
28
|
+
--title <title> its title
|
|
29
|
+
--audience <audience> public (docs.mondarth.com) or internal (the repository's GitHub Pages)
|
|
30
|
+
--version-from <path> the package.json whose version it documents
|
|
31
|
+
--source <url> its source, linked from its footer
|
|
32
|
+
--author <name> its author (Mondarth)
|
|
33
|
+
--name <name> its scripts' name: docs:<name>:build (the set's)
|
|
34
|
+
--tag-prefix <prefix> the start of the package's release tags, which publish a public set (<package>-v)
|
|
35
|
+
--branch <branch> the branch whose pushes publish an internal set (main)
|
|
36
|
+
--force replace what was changed by hand in the files it generates
|
|
37
|
+
--yes ask nothing: what is not given takes its default
|
|
38
|
+
--no-check do not check the repository's setup afterwards
|
|
39
|
+
`;
|
|
40
|
+
/** create-docs' own version, from its package.json. */
|
|
41
|
+
async function toolVersion() {
|
|
42
|
+
const path = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
|
|
43
|
+
return JSON.parse(await readFile(path, 'utf8')).version;
|
|
44
|
+
}
|
|
45
|
+
async function exists(path) {
|
|
46
|
+
try {
|
|
47
|
+
await access(path);
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** The set's folder, as given: a path inside the repository, with forward slashes. */
|
|
55
|
+
function checkedDir(dir) {
|
|
56
|
+
const normal = posix.normalize(dir.replaceAll('\\', '/')).replace(/\/+$/, '');
|
|
57
|
+
if (!/^[\w.-]+(?:\/[\w.-]+)*$/.test(normal) || normal.split('/').includes('..') || normal === '.') {
|
|
58
|
+
throw new CreateDocsError(`--dir ${dir}: a folder inside the repository, such as docs or packages/extension/docs`);
|
|
59
|
+
}
|
|
60
|
+
return normal;
|
|
61
|
+
}
|
|
62
|
+
/** The repository's GitHub address, from its origin, to link the set's source; undefined if it has none. */
|
|
63
|
+
async function originUrl(cwd) {
|
|
64
|
+
try {
|
|
65
|
+
const { stdout } = await promisify(execFile)('git', ['remote', 'get-url', 'origin'], { cwd });
|
|
66
|
+
const match = /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(stdout.trim());
|
|
67
|
+
return match === null ? undefined : `https://github.com/${match[1] ?? ''}`;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const OPTIONS = {
|
|
74
|
+
dir: { type: 'string', default: 'docs' },
|
|
75
|
+
product: { type: 'string' },
|
|
76
|
+
set: { type: 'string' },
|
|
77
|
+
title: { type: 'string' },
|
|
78
|
+
audience: { type: 'string' },
|
|
79
|
+
'version-from': { type: 'string' },
|
|
80
|
+
source: { type: 'string' },
|
|
81
|
+
author: { type: 'string' },
|
|
82
|
+
name: { type: 'string' },
|
|
83
|
+
'tag-prefix': { type: 'string' },
|
|
84
|
+
branch: { type: 'string' },
|
|
85
|
+
version: { type: 'string' },
|
|
86
|
+
force: { type: 'boolean', default: false },
|
|
87
|
+
yes: { type: 'boolean', default: false },
|
|
88
|
+
'no-check': { type: 'boolean', default: false },
|
|
89
|
+
help: { type: 'boolean', short: 'h', default: false },
|
|
90
|
+
};
|
|
91
|
+
/** A value from its option, else asked for, else its default; a CreateDocsError if it is required and has none. */
|
|
92
|
+
async function valueOf(io, values, given, question, fallback = '') {
|
|
93
|
+
if (given !== undefined)
|
|
94
|
+
return given;
|
|
95
|
+
if (values.yes || io.ask === undefined) {
|
|
96
|
+
if (fallback === '')
|
|
97
|
+
throw new CreateDocsError(`${question}: give it (see --help)`);
|
|
98
|
+
return fallback;
|
|
99
|
+
}
|
|
100
|
+
const answer = (await io.ask(question, fallback)).trim();
|
|
101
|
+
return answer === '' ? fallback : answer;
|
|
102
|
+
}
|
|
103
|
+
/** The manifest of a set not yet written, from the options, and what is asked for. */
|
|
104
|
+
async function newManifest(io, values, dir) {
|
|
105
|
+
const product = await valueOf(io, values, values.product, 'The product it documents (as in /<product>/<set>/)');
|
|
106
|
+
const set = await valueOf(io, values, values.set, 'The set', dir.split('/').at(-2) ?? '');
|
|
107
|
+
const title = await valueOf(io, values, values.title, 'Its title', `${product} ${set}`);
|
|
108
|
+
const audience = await valueOf(io, values, values.audience, 'Its audience: public or internal', 'public');
|
|
109
|
+
const besidePackage = dir.includes('/') ? posix.join(posix.dirname(dir), 'package.json') : 'package.json';
|
|
110
|
+
const fromFallback = (await exists(join(io.cwd, besidePackage))) ? besidePackage : 'package.json';
|
|
111
|
+
const from = await valueOf(io, values, values['version-from'], 'The package.json whose version it documents', fromFallback);
|
|
112
|
+
const source = values.source ?? (await originUrl(io.cwd));
|
|
113
|
+
const manifest = {
|
|
114
|
+
product,
|
|
115
|
+
set,
|
|
116
|
+
title,
|
|
117
|
+
audience: audience,
|
|
118
|
+
...(values.author === undefined ? {} : { author: values.author }),
|
|
119
|
+
...(source === undefined ? {} : { source }),
|
|
120
|
+
version: { from },
|
|
121
|
+
};
|
|
122
|
+
const problems = problemsOf(manifest);
|
|
123
|
+
if (!AUDIENCES.includes(manifest.audience))
|
|
124
|
+
problems.unshift(`--audience ${audience}: public or internal`);
|
|
125
|
+
if (!SLUG.test(product) || !SLUG.test(set))
|
|
126
|
+
problems.unshift('--product and --set: lower-case words joined by hyphens');
|
|
127
|
+
if (problems.length > 0)
|
|
128
|
+
throw new CreateDocsError(problems.join('; '));
|
|
129
|
+
return manifest;
|
|
130
|
+
}
|
|
131
|
+
const MARKS = {
|
|
132
|
+
created: 'created ',
|
|
133
|
+
updated: 'updated ',
|
|
134
|
+
unchanged: 'unchanged',
|
|
135
|
+
kept: 'kept ',
|
|
136
|
+
edited: 'EDITED ',
|
|
137
|
+
replaced: 'replaced ',
|
|
138
|
+
};
|
|
139
|
+
function printFindings(io, findings) {
|
|
140
|
+
for (const finding of findings)
|
|
141
|
+
io.out(`${finding.ok ? '✓' : '✗'} ${finding.message}\n`);
|
|
142
|
+
}
|
|
143
|
+
/** Writes the set, or brings it up to date, then says what is left to do, and checks the setup. */
|
|
144
|
+
async function create(io, values) {
|
|
145
|
+
const root = io.cwd;
|
|
146
|
+
if (!(await exists(join(root, 'package.json')))) {
|
|
147
|
+
throw new CreateDocsError("Run create-docs from the repository's root, where its package.json is");
|
|
148
|
+
}
|
|
149
|
+
const dir = checkedDir(values.dir);
|
|
150
|
+
const lock = await readLock(root, dir);
|
|
151
|
+
const existing = await readManifest(join(root, dir));
|
|
152
|
+
if (existing !== undefined)
|
|
153
|
+
io.out(`Bringing ${dir} up to date: its manifest, ${dir}/mondarth-docs.json, is kept.\n`);
|
|
154
|
+
const manifest = existing ?? (await newManifest(io, values, dir));
|
|
155
|
+
const documented = await documentedPackage(root, manifest);
|
|
156
|
+
// The scripts' name: the set's, unless another set's scripts have it.
|
|
157
|
+
const packageJson = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
|
|
158
|
+
const taken = (name) => {
|
|
159
|
+
const script = packageJson.scripts?.[`docs:${name}:build`];
|
|
160
|
+
return script !== undefined && !script.includes(`-f ${dir}/compose.yaml`);
|
|
161
|
+
};
|
|
162
|
+
const name = values.name ?? lock?.layout.name ?? (taken(manifest.set) ? `${manifest.product}-${manifest.set}` : manifest.set);
|
|
163
|
+
if (!SLUG.test(name))
|
|
164
|
+
throw new CreateDocsError(`--name ${name}: lower-case words joined by hyphens`);
|
|
165
|
+
const layout = {
|
|
166
|
+
manifest,
|
|
167
|
+
dir,
|
|
168
|
+
name,
|
|
169
|
+
tagPrefix: values['tag-prefix'] ?? lock?.layout.tagPrefix ?? tagPrefixOf(manifest.version.from, documented.name),
|
|
170
|
+
branch: values.branch ?? lock?.layout.branch ?? 'main',
|
|
171
|
+
};
|
|
172
|
+
const reports = await scaffold({ root, layout, force: values.force, toolVersion: await toolVersion() });
|
|
173
|
+
for (const report of reports)
|
|
174
|
+
io.out(`${MARKS[report.outcome]} ${report.path}\n`);
|
|
175
|
+
const edited = reports.filter(report => report.outcome === 'edited');
|
|
176
|
+
for (const report of edited)
|
|
177
|
+
io.out(`\n${report.diff ?? ''}\n`);
|
|
178
|
+
if (edited.length > 0) {
|
|
179
|
+
io.out(`\n${edited.length} changed by hand, and kept: what create-docs writes is above. --force replaces them.\n`);
|
|
180
|
+
}
|
|
181
|
+
io.out(`
|
|
182
|
+
Next:
|
|
183
|
+
pnpm install install create-docs, which the set's scripts and workflow use
|
|
184
|
+
pnpm docs:${name}:dev preview the set on http://localhost:8000
|
|
185
|
+
pnpm docs:${name}:build build it, as its workflow does
|
|
186
|
+
|
|
187
|
+
To publish it, once: ${setupStep(manifest, layout.branch)}
|
|
188
|
+
Then \`pnpm docs:${name}:check\` checks it.
|
|
189
|
+
`);
|
|
190
|
+
if (!values['no-check']) {
|
|
191
|
+
io.out('\nChecking the setup now:\n');
|
|
192
|
+
printFindings(io, await check(manifest, layout.branch, io.gh));
|
|
193
|
+
}
|
|
194
|
+
return edited.length > 0 ? 1 : 0;
|
|
195
|
+
}
|
|
196
|
+
/** Runs create-docs with the arguments, and returns its exit status. */
|
|
197
|
+
export async function main(argv, io) {
|
|
198
|
+
const { values, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
|
|
199
|
+
const [command = 'create', ...rest] = positionals;
|
|
200
|
+
if (values.help) {
|
|
201
|
+
io.out(HELP);
|
|
202
|
+
return 0;
|
|
203
|
+
}
|
|
204
|
+
if (rest.length > 0)
|
|
205
|
+
throw new CreateDocsError(`Unexpected ${rest.join(' ')} (see --help)`);
|
|
206
|
+
const folder = join(io.cwd, checkedDir(values.dir));
|
|
207
|
+
switch (command) {
|
|
208
|
+
case 'create':
|
|
209
|
+
return create(io, values);
|
|
210
|
+
case 'check': {
|
|
211
|
+
const manifest = await requireManifest(folder);
|
|
212
|
+
const lock = await readLock(io.cwd, checkedDir(values.dir));
|
|
213
|
+
const findings = await check(manifest, values.branch ?? lock?.layout.branch ?? 'main', io.gh);
|
|
214
|
+
printFindings(io, findings);
|
|
215
|
+
return findings.every(finding => finding.ok) ? 0 : 1;
|
|
216
|
+
}
|
|
217
|
+
case 'version': {
|
|
218
|
+
io.out(`${(await documentedPackage(io.cwd, await requireManifest(folder))).version}\n`);
|
|
219
|
+
return 0;
|
|
220
|
+
}
|
|
221
|
+
case 'publish': {
|
|
222
|
+
if (values.version === undefined)
|
|
223
|
+
throw new CreateDocsError('publish: give the --version to publish as');
|
|
224
|
+
const manifest = await requireManifest(folder);
|
|
225
|
+
const published = await publish({
|
|
226
|
+
manifest,
|
|
227
|
+
html: join(folder, '_build', 'html'),
|
|
228
|
+
version: values.version,
|
|
229
|
+
key: io.env[KEY_SECRET],
|
|
230
|
+
site: io.env.MONDARTH_DOCS_URL ?? SITE,
|
|
231
|
+
...(io.send === undefined ? {} : { send: io.send }),
|
|
232
|
+
});
|
|
233
|
+
io.out(`Published ${manifest.product}/${manifest.set} ${values.version}, revision ${published.revision}: ${published.url}\n`);
|
|
234
|
+
return 0;
|
|
235
|
+
}
|
|
236
|
+
default:
|
|
237
|
+
throw new CreateDocsError(`Unknown command ${command} (see --help)`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** The process's own: its folder and environment, the terminal to ask in, when there is one, and the GitHub CLI. */
|
|
241
|
+
function processIo() {
|
|
242
|
+
const interactive = process.stdin.isTTY && process.stdout.isTTY;
|
|
243
|
+
return {
|
|
244
|
+
cwd: process.cwd(),
|
|
245
|
+
env: process.env,
|
|
246
|
+
out: text => process.stdout.write(text),
|
|
247
|
+
ask: interactive
|
|
248
|
+
? async (question, fallback) => {
|
|
249
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
250
|
+
try {
|
|
251
|
+
return await prompt.question(fallback === '' ? `${question}: ` : `${question} (${fallback}): `);
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
prompt.close();
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
: undefined,
|
|
258
|
+
gh,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
// Run as the command, not when a test imports it.
|
|
262
|
+
if (process.argv[1] !== undefined &&
|
|
263
|
+
fileURLToPath(import.meta.url) === (await import('node:fs')).realpathSync(process.argv[1])) {
|
|
264
|
+
try {
|
|
265
|
+
process.exitCode = await main(process.argv.slice(2), processIo());
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
if (!(error instanceof CreateDocsError) && !(error instanceof TypeError && 'code' in error))
|
|
269
|
+
throw error;
|
|
270
|
+
process.stderr.write(`create-docs: ${error.message}\n`);
|
|
271
|
+
process.exitCode = 1;
|
|
272
|
+
}
|
|
273
|
+
}
|
package/dist/errors.js
ADDED
package/dist/manifest.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { CreateDocsError } from './errors.js';
|
|
4
|
+
/** The manifest's name, in the set's folder: the theme reads it too (mondarth_sphinx_theme.configure). */
|
|
5
|
+
export const MANIFEST = 'mondarth-docs.json';
|
|
6
|
+
/** Where a set is published: `public` to docs.mondarth.com, `internal` to its repository's GitHub Pages. */
|
|
7
|
+
export const AUDIENCES = ['public', 'internal'];
|
|
8
|
+
/** A product's or a set's name: a segment of the set's address, `/<product>/<set>/<version>/`. */
|
|
9
|
+
export const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
10
|
+
function isRecord(value) {
|
|
11
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
/** What is wrong with a manifest, each field's problem said: none if it is usable. As the theme checks, and `version`. */
|
|
14
|
+
export function problemsOf(value) {
|
|
15
|
+
if (!isRecord(value))
|
|
16
|
+
return ['not a JSON object'];
|
|
17
|
+
const problems = [];
|
|
18
|
+
for (const key of ['product', 'set']) {
|
|
19
|
+
const slug = value[key];
|
|
20
|
+
if (typeof slug !== 'string' || !SLUG.test(slug)) {
|
|
21
|
+
problems.push(`"${key}" must be lower-case letters and digits, words joined by hyphens`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (typeof value.title !== 'string' || value.title.trim() === '')
|
|
25
|
+
problems.push('"title" must be the set\'s title');
|
|
26
|
+
if (!AUDIENCES.includes(value.audience))
|
|
27
|
+
problems.push('"audience" must be "public" or "internal"');
|
|
28
|
+
for (const key of ['author', 'source']) {
|
|
29
|
+
if (key in value && typeof value[key] !== 'string')
|
|
30
|
+
problems.push(`"${key}" must be text`);
|
|
31
|
+
}
|
|
32
|
+
const version = value.version;
|
|
33
|
+
if (!isRecord(version) || typeof version.from !== 'string' || !version.from.endsWith('package.json')) {
|
|
34
|
+
problems.push('"version" must be { "from": "<the package.json whose version the set documents>" }');
|
|
35
|
+
}
|
|
36
|
+
return problems;
|
|
37
|
+
}
|
|
38
|
+
/** The manifest the text holds, or a CreateDocsError naming the file and what is wrong with it. */
|
|
39
|
+
export function parseManifest(text, path) {
|
|
40
|
+
let value;
|
|
41
|
+
try {
|
|
42
|
+
value = JSON.parse(text);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
throw new CreateDocsError(`${path}: not JSON (${error.message})`);
|
|
46
|
+
}
|
|
47
|
+
const problems = problemsOf(value);
|
|
48
|
+
if (problems.length > 0)
|
|
49
|
+
throw new CreateDocsError(`${path}: ${problems.join('; ')}`);
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
/** The manifest in the set's folder, or undefined if it has none yet. */
|
|
53
|
+
export async function readManifest(folder) {
|
|
54
|
+
const path = join(folder, MANIFEST);
|
|
55
|
+
let text;
|
|
56
|
+
try {
|
|
57
|
+
text = await readFile(path, 'utf8');
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error.code === 'ENOENT')
|
|
61
|
+
return undefined;
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
return parseManifest(text, path);
|
|
65
|
+
}
|
|
66
|
+
/** The manifest in the set's folder, which must have one. */
|
|
67
|
+
export async function requireManifest(folder) {
|
|
68
|
+
const manifest = await readManifest(folder);
|
|
69
|
+
if (manifest === undefined) {
|
|
70
|
+
throw new CreateDocsError(`${join(folder, MANIFEST)}: no manifest; run create-docs with --dir ${folder} first`);
|
|
71
|
+
}
|
|
72
|
+
return manifest;
|
|
73
|
+
}
|
|
74
|
+
/** The manifest as written: its fields in a fixed order, two-space indented, ending with a newline. */
|
|
75
|
+
export function manifestText(manifest) {
|
|
76
|
+
const { product, set, title, audience, author, source, version } = manifest;
|
|
77
|
+
const ordered = {
|
|
78
|
+
product,
|
|
79
|
+
set,
|
|
80
|
+
title,
|
|
81
|
+
audience,
|
|
82
|
+
...(author === undefined ? {} : { author }),
|
|
83
|
+
...(source === undefined ? {} : { source }),
|
|
84
|
+
version: { from: version.from },
|
|
85
|
+
};
|
|
86
|
+
return `${JSON.stringify(ordered, null, 2)}\n`;
|
|
87
|
+
}
|
package/dist/publish.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { access } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { CreateDocsError } from './errors.js';
|
|
5
|
+
import { KEY_SECRET } from './templates.js';
|
|
6
|
+
import { checkedVersion } from './version.js';
|
|
7
|
+
/**
|
|
8
|
+
* Uploads a public set's built HTML to docs.mondarth.com, as one of its versions. The upload, as the site takes it:
|
|
9
|
+
*
|
|
10
|
+
* PUT <site>/api/v1/sets/<product>/<set>/versions/<version>
|
|
11
|
+
* Authorization: Bearer <the set's key>
|
|
12
|
+
* Content-Type: application/gzip
|
|
13
|
+
* <the HTML, as a gzipped tar of the build's folder, index.html at its root>
|
|
14
|
+
*
|
|
15
|
+
* Each upload is a revision of its version: the site serves the newest, keeps the earlier ones, and moves the set's
|
|
16
|
+
* `latest` only to a newer version than it had. It answers 201 with what it published, as {@link Published}.
|
|
17
|
+
*/
|
|
18
|
+
/** The site, unless MONDARTH_DOCS_URL names another, as a test's stand-in. */
|
|
19
|
+
export const SITE = 'https://docs.mondarth.com';
|
|
20
|
+
/** The folder as a gzipped tar, its files at the root, by the system's tar. */
|
|
21
|
+
export function packFolder(folder) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
execFile('tar', ['-czf', '-', '-C', folder, '.'], { encoding: 'buffer', maxBuffer: 1024 * 1024 * 1024 }, (error, stdout) => {
|
|
24
|
+
if (error === null)
|
|
25
|
+
resolve(new Uint8Array(stdout));
|
|
26
|
+
else
|
|
27
|
+
reject(new CreateDocsError(`Cannot pack ${folder}: ${error.message}`));
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** What the site said, when it refused the upload: its message, or what the status means. */
|
|
32
|
+
async function refusal(response, manifest) {
|
|
33
|
+
const set = `${manifest.product}/${manifest.set}`;
|
|
34
|
+
let said = '';
|
|
35
|
+
try {
|
|
36
|
+
const body = (await response.json());
|
|
37
|
+
if (typeof body.message === 'string')
|
|
38
|
+
said = `: ${body.message}`;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Not the site's JSON: what the status means is all there is.
|
|
42
|
+
}
|
|
43
|
+
switch (response.status) {
|
|
44
|
+
case 401:
|
|
45
|
+
return `docs.mondarth.com refused the key${said}. Is ${KEY_SECRET} the key for ${set}?`;
|
|
46
|
+
case 403:
|
|
47
|
+
return `The key may not publish ${set}${said}: it is another set's`;
|
|
48
|
+
case 413:
|
|
49
|
+
return `The documentation is larger than docs.mondarth.com takes${said}`;
|
|
50
|
+
default:
|
|
51
|
+
return `docs.mondarth.com refused the upload (${response.status})${said}`;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Uploads the built HTML as the version, and says what the site published. */
|
|
55
|
+
export async function publish(options) {
|
|
56
|
+
const { manifest, html, key, send = fetch, pack = packFolder } = options;
|
|
57
|
+
const version = checkedVersion(options.version);
|
|
58
|
+
const site = (options.site ?? SITE).replace(/\/+$/, '');
|
|
59
|
+
if (manifest.audience !== 'public') {
|
|
60
|
+
throw new CreateDocsError(`${manifest.product}/${manifest.set} is internal: it is published to GitHub Pages`);
|
|
61
|
+
}
|
|
62
|
+
if (key === undefined || key === '') {
|
|
63
|
+
throw new CreateDocsError(`No upload key: add ${manifest.product}/${manifest.set}'s key for docs.mondarth.com as the repository secret` +
|
|
64
|
+
` ${KEY_SECRET}, and pass it to this step as the environment variable ${KEY_SECRET}`);
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
await access(join(html, 'index.html'));
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
throw new CreateDocsError(`${html} has no index.html: build the documentation first`);
|
|
71
|
+
}
|
|
72
|
+
const url = `${site}/api/v1/sets/${manifest.product}/${manifest.set}/versions/${encodeURIComponent(version)}`;
|
|
73
|
+
const body = await pack(html);
|
|
74
|
+
let response;
|
|
75
|
+
try {
|
|
76
|
+
response = await send(url, {
|
|
77
|
+
method: 'PUT',
|
|
78
|
+
headers: { authorization: `Bearer ${key}`, 'content-type': 'application/gzip' },
|
|
79
|
+
body,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
throw new CreateDocsError(`docs.mondarth.com is not available yet, or cannot be reached (${String(error)})`);
|
|
84
|
+
}
|
|
85
|
+
// A site that does not take uploads yet answers as a site without the address.
|
|
86
|
+
if (response.status === 404 || response.status === 405 || response.status === 501) {
|
|
87
|
+
throw new CreateDocsError(`docs.mondarth.com is not available yet: it does not take uploads (${response.status})`);
|
|
88
|
+
}
|
|
89
|
+
if (!response.ok)
|
|
90
|
+
throw new CreateDocsError(await refusal(response, manifest));
|
|
91
|
+
const published = (await response.json());
|
|
92
|
+
if (typeof published.revision !== 'number' || typeof published.url !== 'string') {
|
|
93
|
+
throw new CreateDocsError('docs.mondarth.com took the upload, but did not say what it published');
|
|
94
|
+
}
|
|
95
|
+
return { revision: published.revision, url: published.url };
|
|
96
|
+
}
|
package/dist/scaffold.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { MANIFEST, manifestText } from './manifest.js';
|
|
8
|
+
import { composeYaml, confPy, gitignore, indexMd, scriptsOf, workflowPath, workflowYaml, } from './templates.js';
|
|
9
|
+
/**
|
|
10
|
+
* Writes a set, or brings it up to date. A set owns its manifest, conf.py and first page: written once, never again.
|
|
11
|
+
* What is generated (its compose.yaml and .gitignore, its workflow, its package.json scripts) is written again each
|
|
12
|
+
* run; the lock file records what was written, so that a change made by hand is told from create-docs' own, kept, and
|
|
13
|
+
* shown, unless `force` replaces it.
|
|
14
|
+
*/
|
|
15
|
+
/** The lock file, in the set's folder: what create-docs last wrote there, and how the set is laid out. */
|
|
16
|
+
export const LOCK = '.create-docs-lock.json';
|
|
17
|
+
/** The package create-docs is, as a repository's devDependencies name it. */
|
|
18
|
+
export const PACKAGE = '@mondarth/create-docs';
|
|
19
|
+
const sha256 = (text) => createHash('sha256').update(text).digest('hex');
|
|
20
|
+
async function readText(path) {
|
|
21
|
+
try {
|
|
22
|
+
return await readFile(path, 'utf8');
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error.code === 'ENOENT')
|
|
26
|
+
return undefined;
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function write(path, text) {
|
|
31
|
+
await mkdir(dirname(path), { recursive: true });
|
|
32
|
+
await writeFile(path, text);
|
|
33
|
+
}
|
|
34
|
+
/** The set's lock, if create-docs has written it before. */
|
|
35
|
+
export async function readLock(root, dir) {
|
|
36
|
+
const text = await readText(join(root, dir, LOCK));
|
|
37
|
+
return text === undefined ? undefined : JSON.parse(text);
|
|
38
|
+
}
|
|
39
|
+
/** How what is there differs from what would be written, as git shows it, or a line saying they differ. */
|
|
40
|
+
async function diffOf(path, current, next) {
|
|
41
|
+
const folder = await mkdtemp(join(tmpdir(), 'create-docs-'));
|
|
42
|
+
try {
|
|
43
|
+
await writeFile(join(folder, 'current'), current);
|
|
44
|
+
await writeFile(join(folder, 'next'), next);
|
|
45
|
+
await promisify(execFile)('git', ['diff', '--no-index', '--no-color', 'current', 'next'], { cwd: folder });
|
|
46
|
+
return '';
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
// git diff exits 1 when the files differ, and writes the difference.
|
|
50
|
+
const { stdout } = error;
|
|
51
|
+
return stdout !== undefined && stdout !== ''
|
|
52
|
+
? stdout.replaceAll('a/current', `a/${path}`).replaceAll('b/next', `b/${path}`)
|
|
53
|
+
: `${path} differs from what create-docs writes`;
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
await rm(folder, { recursive: true, force: true });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** What becomes of a generated text: written, unless it was changed by hand since create-docs last wrote it. */
|
|
60
|
+
function outcomeOf(current, next, recorded, force) {
|
|
61
|
+
if (current === undefined)
|
|
62
|
+
return 'created';
|
|
63
|
+
if (current === next)
|
|
64
|
+
return 'unchanged';
|
|
65
|
+
if (recorded !== undefined && sha256(current) === recorded)
|
|
66
|
+
return 'updated';
|
|
67
|
+
return force ? 'replaced' : 'edited';
|
|
68
|
+
}
|
|
69
|
+
const WRITES = new Set(['created', 'updated', 'replaced']);
|
|
70
|
+
/** Writes the set, or brings it up to date, and says what became of each of its files and scripts. */
|
|
71
|
+
export async function scaffold({ root, layout, force, toolVersion }) {
|
|
72
|
+
const { manifest, dir } = layout;
|
|
73
|
+
const lock = await readLock(root, dir);
|
|
74
|
+
const reports = [];
|
|
75
|
+
const next = {
|
|
76
|
+
version: toolVersion,
|
|
77
|
+
layout: { name: layout.name, tagPrefix: layout.tagPrefix, branch: layout.branch },
|
|
78
|
+
files: {},
|
|
79
|
+
scripts: {},
|
|
80
|
+
};
|
|
81
|
+
// The set's own: written once.
|
|
82
|
+
const owned = [
|
|
83
|
+
[join(dir, MANIFEST), manifestText(manifest)],
|
|
84
|
+
[join(dir, 'conf.py'), confPy(manifest)],
|
|
85
|
+
[join(dir, 'index.md'), indexMd(manifest)],
|
|
86
|
+
];
|
|
87
|
+
for (const [path, text] of owned) {
|
|
88
|
+
if ((await readText(join(root, path))) === undefined) {
|
|
89
|
+
await write(join(root, path), text);
|
|
90
|
+
reports.push({ path, outcome: 'created' });
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
reports.push({ path, outcome: 'kept' });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// Generated: written again, unless changed by hand.
|
|
97
|
+
const generated = [
|
|
98
|
+
[join(dir, '.gitignore'), gitignore(layout)],
|
|
99
|
+
[join(dir, 'compose.yaml'), composeYaml(layout)],
|
|
100
|
+
[workflowPath(manifest), workflowYaml(layout)],
|
|
101
|
+
];
|
|
102
|
+
for (const [path, text] of generated) {
|
|
103
|
+
const current = await readText(join(root, path));
|
|
104
|
+
const outcome = outcomeOf(current, text, lock?.files[path], force);
|
|
105
|
+
if (WRITES.has(outcome))
|
|
106
|
+
await write(join(root, path), text);
|
|
107
|
+
// A file changed by hand keeps what was recorded, so that the next run still knows it was.
|
|
108
|
+
const recorded = outcome === 'edited' ? lock?.files[path] : sha256(text);
|
|
109
|
+
if (recorded !== undefined)
|
|
110
|
+
next.files[path] = recorded;
|
|
111
|
+
reports.push(outcome === 'edited' && current !== undefined
|
|
112
|
+
? { path, outcome, diff: await diffOf(path, current, text) }
|
|
113
|
+
: { path, outcome });
|
|
114
|
+
}
|
|
115
|
+
// The scripts, and create-docs itself, in the repository's package.json.
|
|
116
|
+
const packagePath = join(root, 'package.json');
|
|
117
|
+
const packageText = (await readText(packagePath)) ?? '{}\n';
|
|
118
|
+
const indent = /^([ \t]+)"/m.exec(packageText)?.[1] ?? ' ';
|
|
119
|
+
const packageJson = JSON.parse(packageText);
|
|
120
|
+
const scripts = { ...(packageJson.scripts ?? {}) };
|
|
121
|
+
for (const [name, command] of Object.entries(scriptsOf(layout))) {
|
|
122
|
+
const current = scripts[name];
|
|
123
|
+
const recorded = lock?.scripts[name];
|
|
124
|
+
const outcome = outcomeOf(current, command, recorded === undefined ? undefined : sha256(recorded), force);
|
|
125
|
+
if (WRITES.has(outcome))
|
|
126
|
+
scripts[name] = command;
|
|
127
|
+
const kept = outcome === 'edited' ? recorded : command;
|
|
128
|
+
if (kept !== undefined)
|
|
129
|
+
next.scripts[name] = kept;
|
|
130
|
+
const path = `package.json#scripts.${name}`;
|
|
131
|
+
reports.push(outcome === 'edited' && current !== undefined
|
|
132
|
+
? { path, outcome, diff: `- ${current}\n+ ${command}` }
|
|
133
|
+
: { path, outcome });
|
|
134
|
+
}
|
|
135
|
+
packageJson.scripts = scripts;
|
|
136
|
+
const dependencies = (packageJson.dependencies ?? {});
|
|
137
|
+
const devDependencies = { ...(packageJson.devDependencies ?? {}) };
|
|
138
|
+
if (dependencies[PACKAGE] === undefined && devDependencies[PACKAGE] === undefined) {
|
|
139
|
+
devDependencies[PACKAGE] = `^${toolVersion}`;
|
|
140
|
+
packageJson.devDependencies = Object.fromEntries(Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b)));
|
|
141
|
+
reports.push({ path: `package.json#devDependencies.${PACKAGE}`, outcome: 'created' });
|
|
142
|
+
}
|
|
143
|
+
const nextPackageText = `${JSON.stringify(packageJson, null, indent)}\n`;
|
|
144
|
+
if (nextPackageText !== packageText)
|
|
145
|
+
await write(packagePath, nextPackageText);
|
|
146
|
+
await write(join(root, dir, LOCK), `${JSON.stringify(next, null, 2)}\n`);
|
|
147
|
+
return reports;
|
|
148
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What create-docs writes. A set owns its manifest, conf.py and pages, written once; the rest is generated, and
|
|
3
|
+
* brought up to date each time create-docs runs (scaffold.ts).
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* The toolchain image: Sphinx, MyST and the Mondarth theme, at the newest release of its major version, so that a
|
|
7
|
+
* set takes the theme's fixes and features without a change of its own. `DOCS_IMAGE` replaces it, as CI does to build
|
|
8
|
+
* a set with the image it has just built.
|
|
9
|
+
*/
|
|
10
|
+
export const TOOLCHAIN_IMAGE = 'ghcr.io/mondarth/sphinx:0';
|
|
11
|
+
/** The actions the generated workflow uses, pinned as this repository's own workflows pin them (a test holds them so). */
|
|
12
|
+
export const ACTIONS = {
|
|
13
|
+
checkout: 'actions/checkout@v7',
|
|
14
|
+
pnpm: 'pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1',
|
|
15
|
+
node: 'actions/setup-node@v7',
|
|
16
|
+
configurePages: 'actions/configure-pages@v6',
|
|
17
|
+
uploadPages: 'actions/upload-pages-artifact@v5',
|
|
18
|
+
deployPages: 'actions/deploy-pages@v5',
|
|
19
|
+
};
|
|
20
|
+
/** The secret a public set's upload key is kept in. */
|
|
21
|
+
export const KEY_SECRET = 'MONDARTH_DOCS_KEY';
|
|
22
|
+
/** The generated workflow's file, from the repository's root. */
|
|
23
|
+
export function workflowPath(manifest) {
|
|
24
|
+
return `.github/workflows/docs-${manifest.product}-${manifest.set}.yml`;
|
|
25
|
+
}
|
|
26
|
+
/** The line that heads each generated file, saying what wrote it and how to bring it up to date. */
|
|
27
|
+
function header(layout) {
|
|
28
|
+
return [
|
|
29
|
+
`# Written by @mondarth/create-docs for the documentation set ${layout.manifest.product}/${layout.manifest.set}. To`,
|
|
30
|
+
`# bring it up to date, run \`pnpm exec create-docs --dir ${layout.dir}\`: a change made here by hand is kept, and`,
|
|
31
|
+
'# shown, unless it is given --force.',
|
|
32
|
+
].join('\n');
|
|
33
|
+
}
|
|
34
|
+
/** The command that builds the set's HTML into `<dir>/_build/html`, in the toolchain image, warnings failing it. */
|
|
35
|
+
export function buildCommand(dir) {
|
|
36
|
+
return `DOCS_UID=$(id -u) DOCS_GID=$(id -g) docker compose -f ${dir}/compose.yaml run --rm --no-deps -T docs mondarth-docs html`;
|
|
37
|
+
}
|
|
38
|
+
/** The package.json scripts of the set, by name. */
|
|
39
|
+
export function scriptsOf(layout) {
|
|
40
|
+
const { dir, name } = layout;
|
|
41
|
+
return {
|
|
42
|
+
[`docs:${name}:build`]: buildCommand(dir),
|
|
43
|
+
[`docs:${name}:dev`]: `DOCS_UID=$(id -u) DOCS_GID=$(id -g) docker compose -f ${dir}/compose.yaml run --rm --service-ports docs mondarth-docs livehtml`,
|
|
44
|
+
[`docs:${name}:check`]: `create-docs check --dir ${dir}`,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The set's conf.py: the theme's configuration, from the manifest. The set's own, to add to. */
|
|
48
|
+
export function confPy(manifest) {
|
|
49
|
+
return `"""Sphinx configuration for ${manifest.title}: its manifest, mondarth-docs.json, and the Mondarth theme's settings."""
|
|
50
|
+
|
|
51
|
+
from mondarth_sphinx_theme import configure
|
|
52
|
+
|
|
53
|
+
configure(globals())
|
|
54
|
+
|
|
55
|
+
# The set's own settings follow, and override the theme's: an extension, say, \`extensions.append('sphinx.ext.autodoc')\`.
|
|
56
|
+
`;
|
|
57
|
+
}
|
|
58
|
+
/** The set's first page. */
|
|
59
|
+
export function indexMd(manifest) {
|
|
60
|
+
return `# ${manifest.title}
|
|
61
|
+
|
|
62
|
+
Start here. Each page is Markdown (MyST): add one beside this, and list it in the contents below.
|
|
63
|
+
|
|
64
|
+
\`\`\`{toctree}
|
|
65
|
+
:maxdepth: 2
|
|
66
|
+
\`\`\`
|
|
67
|
+
`;
|
|
68
|
+
}
|
|
69
|
+
/** What git leaves out of the set's folder: the build. */
|
|
70
|
+
export function gitignore(layout) {
|
|
71
|
+
return `${header(layout)}\n_build/\n`;
|
|
72
|
+
}
|
|
73
|
+
/** The set's Docker setup: the toolchain image, building as the calling user, the preview on DOCS_PORT. */
|
|
74
|
+
export function composeYaml(layout) {
|
|
75
|
+
const { product, set } = layout.manifest;
|
|
76
|
+
return `${header(layout)}
|
|
77
|
+
#
|
|
78
|
+
# pnpm docs:${layout.name}:build build the HTML into ${layout.dir}/_build/html
|
|
79
|
+
# pnpm docs:${layout.name}:dev live preview on http://localhost:8000 (DOCS_PORT)
|
|
80
|
+
#
|
|
81
|
+
# The toolchain image is the newest of its major version: \`docker compose -f ${layout.dir}/compose.yaml pull\` fetches it.
|
|
82
|
+
name: docs-${product}-${set}
|
|
83
|
+
|
|
84
|
+
services:
|
|
85
|
+
docs:
|
|
86
|
+
image: \${DOCS_IMAGE:-${TOOLCHAIN_IMAGE}}
|
|
87
|
+
# Build as the calling user, so that the output is not owned by root.
|
|
88
|
+
user: '\${DOCS_UID:-1000}:\${DOCS_GID:-1000}'
|
|
89
|
+
volumes:
|
|
90
|
+
- .:/docs
|
|
91
|
+
environment:
|
|
92
|
+
# The version the documentation describes; a release build sets it.
|
|
93
|
+
DOCS_VERSION: \${DOCS_VERSION:-dev}
|
|
94
|
+
ports:
|
|
95
|
+
- '\${DOCS_PORT:-8000}:8000'
|
|
96
|
+
`;
|
|
97
|
+
}
|
|
98
|
+
/** The job that builds the set on a pull request that changes it, so that a broken page fails review. */
|
|
99
|
+
function buildJob(layout) {
|
|
100
|
+
return ` build:
|
|
101
|
+
name: Build ${layout.manifest.title}
|
|
102
|
+
if: github.event_name == 'pull_request'
|
|
103
|
+
runs-on: ubuntu-latest
|
|
104
|
+
steps:
|
|
105
|
+
- uses: ${ACTIONS.checkout}
|
|
106
|
+
- name: Build the documentation
|
|
107
|
+
run: ${buildCommand(layout.dir)}`;
|
|
108
|
+
}
|
|
109
|
+
/** The steps that check out what is published and install create-docs, from the repository's devDependencies. */
|
|
110
|
+
function setupSteps() {
|
|
111
|
+
return ` - uses: ${ACTIONS.checkout}
|
|
112
|
+
with:
|
|
113
|
+
ref: \${{ inputs.ref || github.ref }}
|
|
114
|
+
- uses: ${ACTIONS.pnpm}
|
|
115
|
+
- uses: ${ACTIONS.node}
|
|
116
|
+
with:
|
|
117
|
+
node-version: 24
|
|
118
|
+
cache: pnpm
|
|
119
|
+
- name: Install create-docs
|
|
120
|
+
run: pnpm install --frozen-lockfile`;
|
|
121
|
+
}
|
|
122
|
+
/** The workflow of a public set: built on pull requests, uploaded to docs.mondarth.com at a release or by hand. */
|
|
123
|
+
function publicWorkflow(layout) {
|
|
124
|
+
const { manifest, dir, tagPrefix } = layout;
|
|
125
|
+
const file = workflowPath(manifest);
|
|
126
|
+
return `${header(layout)}
|
|
127
|
+
#
|
|
128
|
+
# ${manifest.title}, published to docs.mondarth.com, at /${manifest.product}/${manifest.set}/<version>/:
|
|
129
|
+
#
|
|
130
|
+
# - at each release of the package it documents (${manifest.version.from}), when the release's tag is pushed
|
|
131
|
+
# (${tagPrefix}<version>), or when the release workflow calls this one (a tag pushed with the default
|
|
132
|
+
# GITHUB_TOKEN starts no workflow);
|
|
133
|
+
# - by hand (Actions > ${'Docs: ' + manifest.title} > Run workflow): any versions, from any branch, tag or commit, as
|
|
134
|
+
# a correction to a version already released, built from its documentation maintenance branch, or the
|
|
135
|
+
# documentation of a release published after it. Each upload is a revision of its version: the newest is served.
|
|
136
|
+
#
|
|
137
|
+
# Pull requests that change the set build it.
|
|
138
|
+
name: 'Docs: ${manifest.title}'
|
|
139
|
+
|
|
140
|
+
on:
|
|
141
|
+
pull_request:
|
|
142
|
+
paths:
|
|
143
|
+
- '${dir}/**'
|
|
144
|
+
- '${file}'
|
|
145
|
+
push:
|
|
146
|
+
tags:
|
|
147
|
+
- '${tagPrefix}*'
|
|
148
|
+
workflow_call:
|
|
149
|
+
inputs:
|
|
150
|
+
versions:
|
|
151
|
+
description: The versions to publish as, separated by spaces (blank, the package's own)
|
|
152
|
+
type: string
|
|
153
|
+
default: ''
|
|
154
|
+
ref:
|
|
155
|
+
description: The branch, tag or commit to build (blank, the one this run is for)
|
|
156
|
+
type: string
|
|
157
|
+
default: ''
|
|
158
|
+
secrets:
|
|
159
|
+
${KEY_SECRET}:
|
|
160
|
+
required: true
|
|
161
|
+
workflow_dispatch:
|
|
162
|
+
inputs:
|
|
163
|
+
versions:
|
|
164
|
+
description: The versions to publish as, separated by spaces (blank, the package's own)
|
|
165
|
+
required: false
|
|
166
|
+
ref:
|
|
167
|
+
description: The branch, tag or commit to build (blank, the one this run is started on)
|
|
168
|
+
required: false
|
|
169
|
+
|
|
170
|
+
permissions:
|
|
171
|
+
contents: read
|
|
172
|
+
|
|
173
|
+
jobs:
|
|
174
|
+
${buildJob(layout)}
|
|
175
|
+
|
|
176
|
+
publish:
|
|
177
|
+
name: Publish ${manifest.title}
|
|
178
|
+
if: github.event_name != 'pull_request'
|
|
179
|
+
runs-on: ubuntu-latest
|
|
180
|
+
steps:
|
|
181
|
+
${setupSteps()}
|
|
182
|
+
# Each version is built on its own, as each page's footer names its version, then uploaded.
|
|
183
|
+
- name: Build and publish each version
|
|
184
|
+
run: |
|
|
185
|
+
versions="\${VERSIONS:-$(pnpm exec create-docs version --dir ${dir})}"
|
|
186
|
+
for version in \${versions}; do
|
|
187
|
+
rm -rf ${dir}/_build
|
|
188
|
+
DOCS_VERSION="\${version}" ${buildCommand(dir)}
|
|
189
|
+
pnpm exec create-docs publish --dir ${dir} --version "\${version}"
|
|
190
|
+
done
|
|
191
|
+
env:
|
|
192
|
+
VERSIONS: \${{ inputs.versions }}
|
|
193
|
+
${KEY_SECRET}: \${{ secrets.${KEY_SECRET} }}
|
|
194
|
+
`;
|
|
195
|
+
}
|
|
196
|
+
/** The workflow of an internal set: built on pull requests, published to GitHub Pages from its branch. */
|
|
197
|
+
function internalWorkflow(layout) {
|
|
198
|
+
const { manifest, dir, branch } = layout;
|
|
199
|
+
const file = workflowPath(manifest);
|
|
200
|
+
return `${header(layout)}
|
|
201
|
+
#
|
|
202
|
+
# ${manifest.title}, published to this repository's GitHub Pages: its current documentation, not versioned.
|
|
203
|
+
# Published when a push to ${branch} changes it, or the package it documents (${manifest.version.from}), or by hand
|
|
204
|
+
# (Actions > ${'Docs: ' + manifest.title} > Run workflow). Pull requests that change the set build it.
|
|
205
|
+
#
|
|
206
|
+
# Settings > Pages > Source must be GitHub Actions, and the github-pages environment must allow ${branch}
|
|
207
|
+
# (\`pnpm docs:${layout.name}:check\` checks both).
|
|
208
|
+
name: 'Docs: ${manifest.title}'
|
|
209
|
+
|
|
210
|
+
on:
|
|
211
|
+
pull_request:
|
|
212
|
+
paths:
|
|
213
|
+
- '${dir}/**'
|
|
214
|
+
- '${file}'
|
|
215
|
+
push:
|
|
216
|
+
branches: [${branch}]
|
|
217
|
+
paths:
|
|
218
|
+
- '${dir}/**'
|
|
219
|
+
- '${manifest.version.from}'
|
|
220
|
+
- '${file}'
|
|
221
|
+
workflow_call:
|
|
222
|
+
inputs:
|
|
223
|
+
ref:
|
|
224
|
+
description: The branch, tag or commit to build (blank, the one this run is for)
|
|
225
|
+
type: string
|
|
226
|
+
default: ''
|
|
227
|
+
workflow_dispatch:
|
|
228
|
+
inputs:
|
|
229
|
+
ref:
|
|
230
|
+
description: The branch, tag or commit to build (blank, the one this run is started on)
|
|
231
|
+
required: false
|
|
232
|
+
|
|
233
|
+
permissions:
|
|
234
|
+
contents: read
|
|
235
|
+
|
|
236
|
+
# One deployment at a time; the newest waits for the one before it, rather than cancelling it.
|
|
237
|
+
concurrency:
|
|
238
|
+
group: docs-${manifest.product}-${manifest.set}-pages
|
|
239
|
+
cancel-in-progress: false
|
|
240
|
+
|
|
241
|
+
jobs:
|
|
242
|
+
${buildJob(layout)}
|
|
243
|
+
|
|
244
|
+
publish:
|
|
245
|
+
name: Publish ${manifest.title}
|
|
246
|
+
if: github.event_name != 'pull_request'
|
|
247
|
+
runs-on: ubuntu-latest
|
|
248
|
+
permissions:
|
|
249
|
+
contents: read
|
|
250
|
+
pages: write
|
|
251
|
+
id-token: write
|
|
252
|
+
# To see the uploaded artifact listed before deploying it (below).
|
|
253
|
+
actions: read
|
|
254
|
+
environment:
|
|
255
|
+
name: github-pages
|
|
256
|
+
url: \${{ steps.deployment.outputs.page_url || steps.retry.outputs.page_url }}
|
|
257
|
+
steps:
|
|
258
|
+
- uses: ${ACTIONS.checkout}
|
|
259
|
+
with:
|
|
260
|
+
ref: \${{ inputs.ref || github.ref }}
|
|
261
|
+
- name: Build the documentation
|
|
262
|
+
run: |
|
|
263
|
+
version="$(node -p "require('./${manifest.version.from}').version")"
|
|
264
|
+
DOCS_VERSION="\${version}" ${buildCommand(dir)}
|
|
265
|
+
- uses: ${ACTIONS.configurePages}
|
|
266
|
+
# A re-run deploys an artifact of its own: GitHub Pages names a deployment after its commit.
|
|
267
|
+
- uses: ${ACTIONS.uploadPages}
|
|
268
|
+
with:
|
|
269
|
+
name: github-pages-\${{ github.run_attempt }}
|
|
270
|
+
path: ${dir}/_build/html
|
|
271
|
+
# GitHub lists a new artifact a moment after its upload, and deploy-pages looks once, so this waits for it.
|
|
272
|
+
- name: Wait for the artifact to be listed
|
|
273
|
+
run: |
|
|
274
|
+
for _ in $(seq 24); do
|
|
275
|
+
gh api "repos/\${GITHUB_REPOSITORY}/actions/runs/\${GITHUB_RUN_ID}/artifacts?name=\${ARTIFACT}" \\
|
|
276
|
+
--jq '.total_count' | grep -qv '^0$' && exit 0
|
|
277
|
+
sleep 5
|
|
278
|
+
done
|
|
279
|
+
echo "::warning::\${ARTIFACT} was not listed within two minutes; deploying all the same"
|
|
280
|
+
env:
|
|
281
|
+
GH_TOKEN: \${{ github.token }}
|
|
282
|
+
ARTIFACT: github-pages-\${{ github.run_attempt }}
|
|
283
|
+
- name: Deploy
|
|
284
|
+
id: deployment
|
|
285
|
+
continue-on-error: true
|
|
286
|
+
uses: ${ACTIONS.deployPages}
|
|
287
|
+
with:
|
|
288
|
+
artifact_name: github-pages-\${{ github.run_attempt }}
|
|
289
|
+
# GitHub Pages' own deployment can fail for a moment ("Deployment failed, try again later"): once more.
|
|
290
|
+
- name: Wait before deploying again
|
|
291
|
+
if: steps.deployment.outcome == 'failure'
|
|
292
|
+
run: sleep 30
|
|
293
|
+
- name: Deploy again
|
|
294
|
+
id: retry
|
|
295
|
+
if: steps.deployment.outcome == 'failure'
|
|
296
|
+
uses: ${ACTIONS.deployPages}
|
|
297
|
+
with:
|
|
298
|
+
artifact_name: github-pages-\${{ github.run_attempt }}
|
|
299
|
+
`;
|
|
300
|
+
}
|
|
301
|
+
/** The set's workflow, as its audience is published. */
|
|
302
|
+
export function workflowYaml(layout) {
|
|
303
|
+
return layout.manifest.audience === 'public' ? publicWorkflow(layout) : internalWorkflow(layout);
|
|
304
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { CreateDocsError } from './errors.js';
|
|
4
|
+
/** A version a set may be published as: SemVer's. */
|
|
5
|
+
export const VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
6
|
+
/** The package the manifest's `version.from` names, from the repository's root. */
|
|
7
|
+
export async function documentedPackage(root, manifest) {
|
|
8
|
+
const path = join(root, manifest.version.from);
|
|
9
|
+
let value;
|
|
10
|
+
try {
|
|
11
|
+
value = JSON.parse(await readFile(path, 'utf8'));
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
throw new CreateDocsError(`${manifest.version.from}: cannot read the version (${error.message})`);
|
|
15
|
+
}
|
|
16
|
+
const { name, version } = (value ?? {});
|
|
17
|
+
if (typeof name !== 'string' || typeof version !== 'string') {
|
|
18
|
+
throw new CreateDocsError(`${manifest.version.from}: needs a "name" and a "version"`);
|
|
19
|
+
}
|
|
20
|
+
return { name, version };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The start of the tags the package's releases are tagged with: `<name>-v` in a monorepo, where semantic-release-monorepo
|
|
24
|
+
* tags a package so, and `v` for the repository's own package.json, as semantic-release tags it.
|
|
25
|
+
*/
|
|
26
|
+
export function tagPrefixOf(from, name) {
|
|
27
|
+
return from === 'package.json' ? 'v' : `${name}-v`;
|
|
28
|
+
}
|
|
29
|
+
/** The version given, checked: a CreateDocsError if it is not SemVer's. */
|
|
30
|
+
export function checkedVersion(version) {
|
|
31
|
+
if (!VERSION.test(version))
|
|
32
|
+
throw new CreateDocsError(`"${version}" is not a version (1.2.3, 1.2.3-beta.1)`);
|
|
33
|
+
return version;
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mondarth/create-docs",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Adds a documentation set, built with Mondarth's Sphinx theme, to a repository: `pnpm create @mondarth/docs`.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Mondarth/docs.git",
|
|
10
|
+
"directory": "packages/create-docs"
|
|
11
|
+
},
|
|
12
|
+
"bin": {
|
|
13
|
+
"create-docs": "./dist/cli.js"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=24"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"vitest": "^5.1.2"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsc -p tsconfig.build.json",
|
|
29
|
+
"test": "vitest run",
|
|
30
|
+
"typecheck": "tsc --noEmit",
|
|
31
|
+
"typecheck:fallback": "tsc6 --noEmit"
|
|
32
|
+
}
|
|
6
33
|
}
|
package/README.md
DELETED