Skip to content

Commit 0b18b81

Browse files
committed
feat(core): add doc-kit bootstrap command
1 parent 05bda7c commit 0b18b81

11 files changed

Lines changed: 552 additions & 42 deletions

File tree

‎.changeset/bootstrap-command.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@nodejs/doc-kit': minor
3+
---
4+
5+
Add `doc-kit bootstrap [generators...]`: sets a project up end to end — a
6+
`doc-kit.config.mjs` whose naming and versioning are imported straight from
7+
`package.json`, a documentation directory (detected, or created with a
8+
starter page), a `.gitignore` entry for the output, and the generator
9+
packages installed. `doc-kit bootstrap` followed by `doc-kit serve` is all a
10+
new project needs. Prompts for its few decisions on a TTY; `--yes` accepts
11+
the defaults.

‎.changeset/node-preset.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
'@node-core/doc-kit': minor
33
---
44

5-
Add the `@node-core/doc-kit/config` preset
5+
Add the `@node-core/doc-kit/config` preset

‎.changeset/plain-defaults.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@
33
'@nodejs/doc-kit-generator-react': minor
44
---
55

6-
Defaults are now project-neutral instead of Node.js-specific
6+
Defaults are now project-neutral instead of Node.js-specific

‎README.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,21 @@ Commands:
6363
help [command] display help for command
6464
```
6565

66+
### `bootstrap`
67+
68+
The fastest way to adopt doc-kit in a project:
69+
70+
```sh
71+
npx doc-kit bootstrap
72+
npx doc-kit serve
73+
```
74+
75+
`bootstrap` writes a `doc-kit.config.mjs` wired to your `package.json`
76+
(naming, versioning, homepage), finds or creates your documentation
77+
directory, ignores the output directory, and installs the packages for the
78+
generators you pick. `serve` then gives you a live-reloading preview while
79+
you write.
80+
6681
### `generate`
6782

6883
You must provide an input and at least one target through command-line options
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2+
import { join } from 'node:path';
3+
import { stdin, stdout } from 'node:process';
4+
import { createInterface } from 'node:readline/promises';
5+
6+
import { Command, Option } from 'commander';
7+
8+
import { publicGenerators } from '../../src/generators/index.mjs';
9+
import logger from '../../src/logger/index.mjs';
10+
import {
11+
addIgnoredOutput,
12+
buildConfigSource,
13+
detectDocsDirectory,
14+
findExistingConfig,
15+
hasMarkdown,
16+
STARTER_DOC,
17+
} from '../../src/utils/bootstrap.mjs';
18+
import { installGeneratorPackages } from '../../src/utils/install.mjs';
19+
import { errorWrap } from '../utils.mjs';
20+
21+
const bootstrapLogger = logger.child('bootstrap');
22+
23+
/**
24+
* Asks a question with a default answer.
25+
*
26+
* @param {import('node:readline/promises').Interface} rl
27+
* @param {string} question
28+
* @param {string} fallback
29+
* @returns {Promise<string>}
30+
*/
31+
const ask = async (rl, question, fallback) =>
32+
(await rl.question(`${question} (${fallback}) `)).trim() || fallback;
33+
34+
/**
35+
* Asks a yes/no question, defaulting to yes.
36+
*
37+
* @param {import('node:readline/promises').Interface} rl
38+
* @param {string} question
39+
* @returns {Promise<boolean>}
40+
*/
41+
const confirm = async (rl, question) =>
42+
!/^n/i.test((await rl.question(`${question} (Y/n) `)).trim());
43+
44+
export default new Command('bootstrap')
45+
.description(
46+
'Set up a project for doc-kit: a configuration file wired to your ' +
47+
'package.json, a documentation directory, and the generator packages'
48+
)
49+
.argument(
50+
'[generators...]',
51+
`Built-in generator names (${Object.keys(publicGenerators).join(', ')})`
52+
)
53+
.addOption(new Option('-y, --yes', 'Accept all defaults without prompting'))
54+
.addOption(new Option('--dir <path>', 'The documentation directory'))
55+
.addOption(
56+
new Option('-o, --output <directory>', 'The output directory').default(
57+
'out'
58+
)
59+
)
60+
.addOption(new Option('--force', 'Overwrite an existing configuration file'))
61+
.action(
62+
errorWrap(async (generators, opts) => {
63+
const cwd = process.cwd();
64+
65+
const manifestPath = join(cwd, 'package.json');
66+
67+
if (!existsSync(manifestPath)) {
68+
throw new Error(
69+
'No package.json found. Initialize the project first (`npm init`), ' +
70+
'then run `doc-kit bootstrap` again.'
71+
);
72+
}
73+
74+
const existing = findExistingConfig(cwd);
75+
76+
if (existing && !opts.force) {
77+
throw new Error(
78+
`Found ${existing} — this project is already set up. ` +
79+
'Pass `--force` to overwrite it.'
80+
);
81+
}
82+
83+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
84+
85+
const rl =
86+
!opts.yes && stdin.isTTY && stdout.isTTY
87+
? createInterface({ input: stdin, output: stdout })
88+
: undefined;
89+
90+
try {
91+
// 1. Which generators?
92+
let targets = generators;
93+
94+
if (!targets.length) {
95+
targets = rl
96+
? (await ask(rl, 'Generators to set up (comma-separated)', 'html'))
97+
.split(',')
98+
.map(target => target.trim())
99+
.filter(Boolean)
100+
: ['html'];
101+
}
102+
103+
for (const target of targets) {
104+
if (!(target in publicGenerators)) {
105+
throw new Error(
106+
`"${target}" is not a built-in generator ` +
107+
`(expected one of: ${Object.keys(publicGenerators).join(', ')}).`
108+
);
109+
}
110+
}
111+
112+
// 2. Where do the docs live?
113+
let docsDir = opts.dir ?? detectDocsDirectory(cwd);
114+
115+
if (rl && !opts.dir) {
116+
docsDir = await ask(
117+
rl,
118+
'Where does your documentation live?',
119+
docsDir
120+
);
121+
}
122+
123+
mkdirSync(join(cwd, docsDir), { recursive: true });
124+
125+
if (!hasMarkdown(join(cwd, docsDir))) {
126+
writeFileSync(join(cwd, docsDir, 'hello.md'), STARTER_DOC);
127+
bootstrapLogger.info(`Created ${docsDir}/hello.md (a starter page)`);
128+
}
129+
130+
// 3. The configuration file
131+
writeFileSync(
132+
join(cwd, 'doc-kit.config.mjs'),
133+
buildConfigSource({
134+
targets,
135+
docsDir,
136+
output: opts.output,
137+
hasHomepage: Boolean(manifest.homepage),
138+
})
139+
);
140+
bootstrapLogger.info(
141+
'Created doc-kit.config.mjs (naming and versioning follow your package.json)'
142+
);
143+
144+
// 4. Ignore the output directory
145+
const gitignorePath = join(cwd, '.gitignore');
146+
const gitignore = addIgnoredOutput(
147+
existsSync(gitignorePath)
148+
? readFileSync(gitignorePath, 'utf-8')
149+
: undefined,
150+
opts.output
151+
);
152+
153+
if (gitignore !== undefined) {
154+
writeFileSync(gitignorePath, gitignore);
155+
bootstrapLogger.info(`Added ${opts.output}/ to .gitignore`);
156+
}
157+
158+
// 5. Install the generator packages
159+
const install = rl
160+
? await confirm(rl, 'Install the generator packages now?')
161+
: true;
162+
163+
if (install) {
164+
try {
165+
installGeneratorPackages(targets);
166+
} catch (error) {
167+
bootstrapLogger.warn(
168+
`Package installation failed (${error.message}). ` +
169+
`Run \`doc-kit install\` once your registry access is sorted.`
170+
);
171+
}
172+
}
173+
} finally {
174+
rl?.close();
175+
}
176+
177+
bootstrapLogger.info('All set! Next steps:');
178+
bootstrapLogger.info(
179+
' npx doc-kit serve write docs with a live preview'
180+
);
181+
bootstrapLogger.info(' npx doc-kit generate build the docs');
182+
bootstrapLogger.info(
183+
'Configuration guide: https://github.com/nodejs/doc-kit/blob/main/docs/configuration.md'
184+
);
185+
})
186+
);
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import bootstrap from './bootstrap.mjs';
12
import generate from './generate.mjs';
23
import install from './install.mjs';
34
import serve from './serve.mjs';
45

5-
export default [generate, install, serve];
6+
export default [bootstrap, generate, install, serve];
Lines changed: 7 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,10 @@
1-
import { spawnSync } from 'node:child_process';
2-
31
import { Command, Option } from 'commander';
42

53
import { publicGenerators } from '../../src/generators/index.mjs';
64
import logger from '../../src/logger/index.mjs';
75
import { enforceArray } from '../../src/utils/array.mjs';
86
import { loadConfigFile } from '../../src/utils/configuration/index.mjs';
9-
import {
10-
buildInstallArguments,
11-
detectPackageManager,
12-
isDevInstall,
13-
resolveGeneratorPackages,
14-
} from '../../src/utils/install.mjs';
7+
import { installGeneratorPackages } from '../../src/utils/install.mjs';
158
import { errorWrap } from '../utils.mjs';
169

1710
const installLogger = logger.child('install');
@@ -50,38 +43,13 @@ export default new Command('install')
5043

5144
// Configuration targets may be import specifiers of third-party
5245
// generators; explicit arguments must be built-in names
53-
const packages = resolveGeneratorPackages(names, fromConfig);
54-
55-
if (!packages.length) {
56-
installLogger.info(
57-
'All requested generators are already part of this package — ' +
58-
'nothing to install.'
59-
);
60-
return;
61-
}
46+
const packages = installGeneratorPackages(names, fromConfig);
6247

63-
const packageManager = detectPackageManager(process.cwd());
64-
const args = buildInstallArguments(
65-
packageManager,
66-
packages,
67-
isDevInstall(process.cwd())
48+
installLogger.info(
49+
packages.length
50+
? `Installed ${packages.join(', ')}`
51+
: 'All requested generators are already part of this package — ' +
52+
'nothing to install.'
6853
);
69-
70-
installLogger.info(`Running \`${packageManager} ${args.join(' ')}\``);
71-
72-
const { status, error } = spawnSync(packageManager, args, {
73-
stdio: 'inherit',
74-
shell: process.platform === 'win32',
75-
});
76-
77-
if (error) {
78-
throw error;
79-
}
80-
81-
if (status !== 0) {
82-
throw new Error(`\`${packageManager}\` exited with status ${status}`);
83-
}
84-
85-
installLogger.info(`Installed ${packages.join(', ')}`);
8654
})
8755
);

0 commit comments

Comments
 (0)