Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/experimental-incremental.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@doc-kit/cli': minor
'@doc-kit/core': minor
'@doc-kit/generator-react': minor
---

Add `doc-kit generate --experimental-incremental`
3 changes: 3 additions & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ parentheses.
**Default:** the number of CPUs, up to 6 (`1` on riscv64).
- `--chunk-size <n>` {number} Items each worker processes per task, at least 1
(`chunkSize`). **Default:** `10`.
- `--experimental-incremental` {boolean} Reuse the previous build's output,
rebuilding only what changed (`experimentalIncremental`). **Default:**
`false`. **Experimental.**

```bash
# Build everything the configuration file describes
Expand Down
7 changes: 7 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,13 @@ These sit at the top level, next to `target` and `global`:
- `discardResults` {boolean} Keep none of the requested generators' results,
so each can be let go as soon as it's produced. `doc-kit generate` and
`doc-kit preview` set it. **Default:** `false`.
- `experimentalIncremental` {boolean} Reuse the previous build's output: the
generators that support it only rebuild what changed, leave the other files
untouched, and remove the files whose sources are gone. The state is stored
in `<output>/.doc-kit/`, which is about as large as the output and
shouldn't be deployed. After an interrupted build, every file is written
again. **Default:** `false`. **Experimental:** the option and the
directory's format may change.

Each worker's heap is limited to 512 MB. If a build runs out of memory, lower
`threads`, or raise the limit by running Node.js with `--max-old-space-size`,
Expand Down
84 changes: 84 additions & 0 deletions docs/creating-generators.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,90 @@ await cp(new URL('./assets', import.meta.url), join(output, 'assets'), {
});
```

### Incremental builds

With [`experimentalIncremental`](./configuration.md#execution-options) on, a
generator can skip the items that haven't changed since the previous build.
`generate` receives a third argument for this, with an `incremental` property.

A generator that produces one result per item, for other generators to read,
uses `reuse`:

```mjs displayName="generate.mjs"
export async function* generate(entries, worker, { incremental }) {
// `stale` holds the entries that changed. Results for the others are
// loaded from the previous build, and all results are yielded in order
yield* incremental.reuse(entries, stale => worker.stream(stale));
}
```

A generator that only writes files uses `partition`:

```mjs displayName="generate.mjs"
import { join } from 'node:path';

import getConfig from '@doc-kit/core/utils/configuration/index.mjs';
import { writeFile } from '@doc-kit/core/utils/file.mjs';

export async function generate(entries, worker, { incremental }) {
const { output } = getConfig('my-format');

// `files` returns the file, or files, an entry is written to
const { stale } = incremental.partition(entries, {
files: entry => `${entry.api}.txt`,
});

for (const entry of stale) {
await writeFile(join(output, `${entry.api}.txt`), render(entry));
}
}
```

In both cases, files and results from the previous build that this build
doesn't use are removed when it finishes.

Each item has a key: a hash of its JSON and of the generator's configuration,
so changing the configuration rebuilds everything. A result of `reuse` is
hashed by the key it was stored under instead of by its content, so whatever
is built from it is rebuilt whenever it is. The generator object can adjust
the key under `incremental`:

- `key` {Function} Returns what to hash for an item instead of the item
itself: one value or an array. Strings and bytes are hashed as they are,
other values as JSON.
- `omit` {string[]} Configuration keys that don't affect the output, such as
paths. `input`, `output`, `ignore` and `pathsToCopy` are always omitted.
- `salt` {Array} Extra values to hash into every key, such as a format
version.

`incremental` has these methods:

- `reuse(items, make[, options])` yields one result per item, in order, as
arrays. `items` is an array, or an async iterable of arrays. `make` receives
the stale items as an async iterable of arrays and yields one result for
each, in order. Results are stored in `<output>/.doc-kit/`, so they must be
[structured-cloneable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
`options.key` overrides the declared `key`. A generator that already writes
each result to its own file can pass `options.file`, which returns that
file for an item, and `options.read`, which reads a result from it, so the
result isn't stored twice.
- `partition(items, options)` splits the items into `{ fresh, stale }`.
`options.files` returns the file or files an item is written to, and
`options.key` overrides the declared `key`.
- `record(label, ...files)` tracks files that don't belong to an item, such as
assets, so they aren't removed.
- `salt(compute)` hashes values computed at run time into every key, such as
the hash of a built bundle. Call it before the first `reuse` or `partition`.
- `digest(...parts)` hashes values into a string that a `key` function can
return later, without holding on to the values.

When the option is off, or the generator has no `output`, every item is stale
and nothing is stored or removed, so a generator doesn't need a separate code
path.

Keys don't cover code. After changing a generator or a plugin, or upgrading
doc-kit, delete `<output>/.doc-kit/` to rebuild everything.

## Worker threads

For heavy work on many independent items, give the generator a
Expand Down
166 changes: 166 additions & 0 deletions e2e/incremental-build.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import { execFile } from 'node:child_process';
import {
appendFile,
mkdir,
mkdtemp,
readdir,
readFile,
rm,
stat,
writeFile,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, relative } from 'node:path';
import { promisify } from 'node:util';

import { expect, test } from '@playwright/test';

const CLI = join(import.meta.dirname, '../packages/cli/bin/cli.mjs');

const DOCUMENTS = {
fs: '# File system\n\nReads and writes files.\n',
path: '# Path\n\nWorks with file paths.\n',
zlib: '# Zlib\n\nCompresses and decompresses.\n',
};

// Each test runs the real CLI, worker threads included, against the output
// the previous test left
test.describe.configure({ mode: 'serial' });

test.describe('Incremental builds', () => {
let root;
let input;
let output;

/**
* Runs an incremental build of the site, with `all.html`, and its JSON.
*/
const build = () =>
promisify(execFile)(process.execPath, [
CLI,
'generate',
...['-t', 'html', '-t', 'html-all', '-t', 'json'],
...['-i', join(input, '*.md')],
...['-o', output],
'--experimental-incremental',
]);

/**
* The modification time of every page and JSON document, by path. Client
* assets are excluded, as they are written on every build.
*/
const builtFiles = async () => {
const entries = await readdir(output, {
recursive: true,
withFileTypes: true,
});

const files = entries
.filter(entry => entry.isFile())
.map(entry => relative(output, join(entry.parentPath, entry.name)))
.filter(file => /^[^./][^/]*\.(html|json)$/.test(file));

return Object.fromEntries(
await Promise.all(
files
.toSorted()
.map(async file => [file, (await stat(join(output, file))).mtimeMs])
)
);
};

/**
* The files whose modification time differs between two builds.
*/
const changedBetween = (before, after) =>
Object.keys(after).filter(file => after[file] !== before[file]);

test.beforeAll(async () => {
root = await mkdtemp(join(tmpdir(), 'doc-kit-incremental-e2e-'));
input = join(root, 'docs');
output = join(root, 'out');

await mkdir(input);

for (const [name, content] of Object.entries(DOCUMENTS)) {
await writeFile(join(input, `${name}.md`), content);
}

await build();
});

test.afterAll(() => rm(root, { recursive: true, force: true }));

test('leaves every file alone when nothing changed', async () => {
const before = await builtFiles();

expect(Object.keys(before)).toEqual([
'404.html',
'all.html',
'fs.html',
'fs.json',
'path.html',
'path.json',
'zlib.html',
'zlib.json',
]);

await build();

expect(await builtFiles()).toEqual(before);
});

test('rewrites only the files an edited document is part of', async () => {
const before = await builtFiles();

await appendFile(join(input, 'fs.md'), '\nWatches them, too.\n');
await build();

const after = await builtFiles();

expect(changedBetween(before, after)).toEqual([
'all.html',
'fs.html',
'fs.json',
]);
expect(await readFile(join(output, 'fs.html'), 'utf-8')).toContain(
'Watches them, too.'
);
});

test('removes the files of a deleted document, and nothing the pages need', async () => {
await writeFile(join(output, 'mine.txt'), 'not doc-kit’s');

await rm(join(input, 'zlib.md'));
await build();

const after = await builtFiles();

expect(Object.keys(after)).toEqual([
'404.html',
'all.html',
'fs.html',
'fs.json',
'path.html',
'path.json',
]);
await expect(stat(join(output, 'mine.txt'))).resolves.toBeDefined();

// Every asset a page loads still exists
for (const page of Object.keys(after).filter(file =>
file.endsWith('.html')
)) {
const html = await readFile(join(output, page), 'utf-8');
const assets = html.matchAll(/(?:src|href)="([^"]*assets\/[^"]+)"/g);

for (const [, asset] of assets) {
const path = join(output, dirname(page), asset);

await expect(
stat(path),
`${page} loads ${asset}`
).resolves.toBeDefined();
}
}
});
});
5 changes: 5 additions & 0 deletions packages/cli/bin/commands/generate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const { runGenerators } = createGenerator();
* @property {string} index
* @property {boolean} minify
* @property {string} typeMap
* @property {boolean} experimentalIncremental
*/

/**
Expand Down Expand Up @@ -53,6 +54,10 @@ export const generateOptions = [
new Option('--index <url>', 'index.md URL or path'),
new Option('--minify', 'Minify?'),
new Option('--type-map <url>', 'Type map URL or path'),
new Option(
'--experimental-incremental',
'Rebuild only what changed since the previous build (experimental)'
),
];

const generate = new Command('generate').description('Generate API docs');
Expand Down
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
},
"imports": {
"#generators/*": "./src/generators/*",
"#incremental/*": "./src/incremental/*",
"#logger/*": "./src/logger/*",
"#parsers/*": [
"./src/parsers/*",
Expand Down
Loading
Loading