diff --git a/Cargo.lock b/Cargo.lock
index d93203c..5dff58d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -564,7 +564,7 @@ dependencies = [
[[package]]
name = "comline-codegen"
version = "0.1.0"
-source = "git+https://github.com/ComlineProject/generation?rev=ac4425c32f88f98a2a3bfb971a209c173c6559a8#ac4425c32f88f98a2a3bfb971a209c173c6559a8"
+source = "git+https://github.com/ComlineProject/generation?rev=6889d3db79ab20f7091d309071ea0b41e2ed5317#6889d3db79ab20f7091d309071ea0b41e2ed5317"
dependencies = [
"comline-core",
"eyre",
@@ -578,7 +578,7 @@ dependencies = [
[[package]]
name = "comline-codegen-rust"
version = "0.1.0"
-source = "git+https://github.com/ComlineProject/comline-rust?rev=8d0d659d100d41d64d203a7890a6b15471cde802#8d0d659d100d41d64d203a7890a6b15471cde802"
+source = "git+https://github.com/ComlineProject/comline-rust?rev=0e39319a80be086f6dbee1a3a017eab0662925b6#0e39319a80be086f6dbee1a3a017eab0662925b6"
dependencies = [
"comline-codegen",
"comline-core",
@@ -588,7 +588,7 @@ dependencies = [
[[package]]
name = "comline-codegen-typescript"
version = "0.1.0"
-source = "git+https://github.com/ComlineProject/comline-typescript?rev=37cd70f96260325f37a39be6a15cb858d2e069dc#37cd70f96260325f37a39be6a15cb858d2e069dc"
+source = "git+https://github.com/ComlineProject/comline-typescript?rev=ad8756847518e6af281c46d1d0e441fdb46e9dde#ad8756847518e6af281c46d1d0e441fdb46e9dde"
dependencies = [
"comline-codegen",
"comline-core",
@@ -632,7 +632,7 @@ source = "git+https://github.com/ComlineProject/core?rev=525939352b79538ce5e9b41
[[package]]
name = "comline-doc-html"
version = "0.1.0"
-source = "git+https://github.com/ComlineProject/generation?rev=ac4425c32f88f98a2a3bfb971a209c173c6559a8#ac4425c32f88f98a2a3bfb971a209c173c6559a8"
+source = "git+https://github.com/ComlineProject/generation?rev=6889d3db79ab20f7091d309071ea0b41e2ed5317#6889d3db79ab20f7091d309071ea0b41e2ed5317"
dependencies = [
"comline-codegen",
"eyre",
@@ -643,7 +643,7 @@ dependencies = [
[[package]]
name = "comline-doc-markdown"
version = "0.1.0"
-source = "git+https://github.com/ComlineProject/generation?rev=ac4425c32f88f98a2a3bfb971a209c173c6559a8#ac4425c32f88f98a2a3bfb971a209c173c6559a8"
+source = "git+https://github.com/ComlineProject/generation?rev=6889d3db79ab20f7091d309071ea0b41e2ed5317#6889d3db79ab20f7091d309071ea0b41e2ed5317"
dependencies = [
"comline-codegen",
"eyre",
diff --git a/Cargo.toml b/Cargo.toml
index 1bc7615..02a4145 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -38,14 +38,14 @@ comline-core = { git = "https://github.com/ComlineProject/core", rev = "52593935
# `comline-codegen`'s types, so the rev below must be byte-identical to the
# one *they* pin - Cargo only unifies a git dependency across identical rev
# strings, and two copies of `GenRequest` are two incompatible types.
-comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "ac4425c32f88f98a2a3bfb971a209c173c6559a8" }
+comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "6889d3db79ab20f7091d309071ea0b41e2ed5317" }
# The official Markdown and HTML documentation renderers (`comline doc`),
# linked in like the official generators. Same generation rev as
# `comline-codegen`.
-comline-doc-markdown = { git = "https://github.com/ComlineProject/generation", rev = "ac4425c32f88f98a2a3bfb971a209c173c6559a8" }
-comline-doc-html = { git = "https://github.com/ComlineProject/generation", rev = "ac4425c32f88f98a2a3bfb971a209c173c6559a8" }
-comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "8d0d659d100d41d64d203a7890a6b15471cde802", optional = true }
-comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "37cd70f96260325f37a39be6a15cb858d2e069dc", optional = true }
+comline-doc-markdown = { git = "https://github.com/ComlineProject/generation", rev = "6889d3db79ab20f7091d309071ea0b41e2ed5317" }
+comline-doc-html = { git = "https://github.com/ComlineProject/generation", rev = "6889d3db79ab20f7091d309071ea0b41e2ed5317" }
+comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "0e39319a80be086f6dbee1a3a017eab0662925b6", optional = true }
+comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "ad8756847518e6af281c46d1d0e441fdb46e9dde", optional = true }
# `comline conformance`: the conformance runner (corpus loading, judging,
# profile proofs) and its case format, a public spec. Pinned by git rev.
comline-runtime-conformance = { git = "https://github.com/ComlineProject/runtime", rev = "4378c91b74ee1ef1debc800a3daf75c874198e70" }
diff --git a/docs/cli.md b/docs/cli.md
index 81f06d5..080be10 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -449,62 +449,100 @@ argument matches no stored version (the error lists the versions that exist).
### `comline doc`
```
-comline doc [--out
] [--version ] [--changelog-from ] [--format markdown|html|json]
+comline doc [--out ] [--version ] [--changelog-from ] [--format [,...]]
```
-Write the package's documentation. Nothing is written to `.comline/`.
+Write the package's documentation for every version: each release, each dev
+build and the unreleased working state (when it differs from the last build).
+Nothing is written to `.comline/`.
+
+Each format lands in `//`, with one folder per version:
+`0.2.0/`, `0.3.0-dev.2/`, and `unreleased/` for the working tree. Each
+version carries the changelog from the version before it, computed by core's
+`comline diff` rules.
- **Pages** (`markdown`, the default, rendered by the official renderer linked
- into `comline`): `index.md` (the package, its `//!` header, its modules), one
- page per module (`types::user` is `types/user.md`) with its `//!` header and
- every unit with its `///` docs, fields, arguments and each protocol's wire
- summary, `changelog.md` with `--changelog-from`, and `nav.yml`, a `nav` for
- mkdocs or zensical.
-- **`html`** writes a self-contained static site, rendered by the official HTML
- renderer, also linked in: `index.html`, one page per module
- (`types/user.html`), `changelog.html` with `--changelog-from`, `style.css`
- and `search.js`. It has the same content as the Markdown pages, plus a
- sidebar of modules and units, a search box over the units (the index is
- inlined in `search.js`), and light and dark themes that follow the OS
- setting. Nothing loads from the network and every link is relative, so
- `index.html` opens straight from disk or from any static host.
-- **`json`** writes the documentation model itself, `model.json`, in the shape
- of core's `schemas/doc-model.json`.
+ into `comline`): per version, `index.md` (the package, its `//!` header, its
+ modules), one page per module (`types::user` is `types/user.md`) with its
+ `//!` header and every unit with its `///` docs, fields, arguments and each
+ protocol's wire summary, `changelog.md`, and `nav.yml`, a `nav` for mkdocs
+ or zensical. `/markdown/index.md` lists the versions. Switching
+ versions on a published site is left to site tooling, such as
+ [mike](https://github.com/jimporter/mike) for mkdocs.
+- **`html`** writes a self-contained static site per version, rendered by the
+ official HTML renderer, also linked in: `index.html`, one page per module
+ (`types/user.html`), `changelog.html`, `style.css` and `search.js`. It has
+ the same content as the Markdown pages, plus a sidebar of modules and units,
+ a search box over the units, a version picker in the header, and light and
+ dark themes that follow the OS setting. The picker opens the same page and
+ unit in the chosen version, or that version's index with a note when it has
+ no such page. At `/html/`, `index.html` points at the latest version
+ (the newest release, else the newest dev build), and `compare.html`
+ compares versions: two show what changed between them, grouped by unit and
+ labelled major, minor or patch; more show a grid of every unit and member
+ per version. The labels come from the changelogs core computed between each
+ version and the one before it; the page never judges a change itself.
+ Nothing loads from the network and every link is relative, so the site opens
+ straight from disk or from any static host.
+- **`json`** writes each version's documentation model, `model.json`, in the
+ shape of core's `schemas/doc-model.json`, and `/json/index.json`
+ listing the versions.
| Flag | Default | Meaning |
|---|---|---|
| `--out ` | `[doc] out`, else `docs/api` | where to write, relative to the project |
-| `--version ` | the working tree | document a built version (a version string, a commit hash, or `HEAD`) from its frozen IR, `//!` headers included |
-| `--changelog-from ` | `[doc] changelog_from` | add what changed from built version `` to the documented one |
-| `--format ` | `[doc] format`, else `markdown` | `markdown`, `html`, `json`, or another id the `[doc] renderer` offers |
-
-A built version keeps no source, so with `--version` its protocols have no wire
-summary. A version built before headers were stored has none.
+| `--version ` | every version | document only this built version (a version string, a commit hash, or `HEAD`), into `///` |
+| `--changelog-from ` | `[doc] changelog_from` | with `--version`: add what changed from built version `` |
+| `--format ` | `[doc] formats`, else `markdown` | `markdown`, `html`, `json`, or another id the `[doc] renderer` offers; repeat it or separate with commas |
+
+**Caching.** A built version never changes, so its folder is kept between
+runs. `//.comline-doc.json` records the key each folder was
+rendered with: its commit, the commit of the version before it, the renderer
+and its version, the model version and the links. A built-in renderer's
+version carries a content hash of its sources and assets (`0.1.0+`),
+so a `comline` with a changed renderer re-renders every folder; an external
+renderer is keyed by its file's hash. A run re-renders only the
+folders whose key changed, which is the unreleased state and new versions,
+and removes the folders of versions no longer listed.
+
+A built version keeps no source, so its protocols have no wire summary, and a
+version built before headers were stored has no `//!` headers. Its pages say
+so in a note.
`comline.toml`'s `[doc]` table:
```toml
[doc]
out = "docs/api"
-format = "markdown"
+formats = ["html", "markdown", "json"]
+versions = { last = 5 } # or "all" (the default), { since = "0.3.0" }, { releases_only = true }
renderer = "renderers/my-renderer.wasm" # optional: an external renderer
timeout = 60 # seconds per call to `renderer`
links = { std = "https://comlineproject.github.io/docs/std/" }
-changelog_from = "0.1.0"
+changelog_from = "0.1.0" # with --version only
```
+- `versions` trims the list. `last = N` keeps the newest N (the unreleased
+ state counts as one), `since` keeps that version and newer, and
+ `releases_only` keeps releases alone (no dev builds and no unreleased
+ state). They combine, applied in that reverse order: `releases_only`, then
+ `since`, then `last`.
- `renderer` is run exactly like an external `generator`: a `.wasm` under
wasmtime with no filesystem, environment or network, a native executable with
an empty environment, the same limits and path checks. It must list the
- format in its `Describe` answer's `renderers`.
+ format in its `Describe` answer's `renderers`. One that doesn't render a
+ site index (`sites` in its `Describe` answer) still renders every version's
+ folder.
- `links` maps a dependency (or `std`) to the base URL of its documentation. A
type from it links to `//#`; a dependency not listed is
plain text.
+`comline new` adds `docs/api/html/` to `.gitignore`.
+
```bash
comline doc
-comline doc --out site/api --changelog-from 0.1.0
-comline doc --version 0.2.0
+comline doc --format html,markdown
+comline doc --version 0.2.0 --changelog-from 0.1.0
comline doc --format html --out site
comline doc --format json
```
diff --git a/src/cli.rs b/src/cli.rs
index e09b2e1..320e697 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -102,28 +102,40 @@ Examples:
/// Write the package's documentation: Markdown pages, or the model as JSON
#[command(long_about = "\
-Write the package's documentation: an index page, one page per module (its \
-`//!` header, every unit with its `///` docs, fields, arguments and each \
-protocol's wire summary), a changelog page with `--changelog-from`, and an \
-mkdocs/zensical `nav.yml`. Read-only: nothing is written to `.comline/`.
-
-The working tree is documented unless `--version` names a built version (a \
-version string, a commit hash or `HEAD`), which is documented from its frozen \
-IR, `//!` headers included. A built version keeps no source, so its protocols \
-have no wire summary.
-
-`--format html` writes a self-contained static site instead: `index.html`, \
-one page per module, `changelog.html`, a stylesheet and a search script, all \
-linked relatively, so `index.html` opens straight from disk. `--format json` \
-writes the documentation model itself (`model.json`), for other tools. `comline.toml`'s `[doc]` table sets the defaults: `out` \
-(`docs/api`), `format` (`markdown`), `renderer` (an external renderer, run \
-like an external generator), `links` (dependency docs URLs) and \
+Write the package's documentation for every version: each release, each dev \
+build and the unreleased working state (when it differs from the last build), \
+each into `///` (`unreleased/` for the working tree) with \
+the changelog from the version before it. Per version: an index page, one page \
+per module (its `//!` header, every unit with its `///` docs, fields, arguments \
+and each protocol's wire summary) and a changelog page. Read-only: nothing is \
+written to `.comline/`.
+
+`markdown` (the default) writes pages and an mkdocs/zensical `nav.yml` per \
+version, plus an `index.md` listing the versions. `html` writes a \
+self-contained static site per version, with a version picker in its header, \
+and at `/html/` an `index.html` pointing at the latest version and a \
+`compare.html` to compare versions; everything links relatively and opens \
+straight from disk. `json` writes each version's documentation model \
+(`model.json`) and an `index.json`.
+
+A built version's folder is kept between runs while nothing it was rendered \
+from changes (`//.comline-doc.json` records why), so a run \
+re-renders only the unreleased state and new versions. `--version` documents \
+one built version alone (a version string, a commit hash or `HEAD`), and \
+`--changelog-from` then adds a changelog from an earlier one. A built version \
+keeps no source, so its protocols have no wire summary, and one built before \
+headers were frozen has no `//!` headers; its pages say so.
+
+`comline.toml`'s `[doc]` table sets the defaults: `out` (`docs/api`), \
+`formats` (`[\"markdown\"]`), `versions` (`\"all\"`, or `{ last = N }`, \
+`{ since = \"0.3.0\" }`, `{ releases_only = true }`), `renderer` (an external \
+renderer, run like an external generator), `links` (dependency docs URLs) and \
`changelog_from`.
Examples:
comline doc
- comline doc --out site/api --changelog-from 0.1.0
- comline doc --version 0.2.0
+ comline doc --format html,markdown
+ comline doc --version 0.2.0 --changelog-from 0.1.0
comline doc --format html --out site
comline doc --format json")]
Doc {
@@ -131,17 +143,17 @@ Examples:
#[arg(long, value_name = "DIR")]
out: Option,
- /// Document this built version instead of the working tree
+ /// Document only this built version, into `///`
#[arg(long = "version", value_name = "VERSION")]
doc_version: Option,
- /// Add a changelog from this built version to the documented one
+ /// With `--version`: add a changelog from this built version
#[arg(long, value_name = "VERSION")]
changelog_from: Option,
- /// `markdown` (pages), `html` (a static site) or `json` (the model); default from `[doc] format`
- #[arg(long, value_name = "FORMAT")]
- format: Option,
+ /// `markdown` (pages), `html` (a static site) or `json` (the model), repeatable or comma-separated; default from `[doc] formats`
+ #[arg(long = "format", value_name = "FORMAT", value_delimiter = ',')]
+ format: Vec,
},
/// Validate the project and write generated code for each configured target
diff --git a/src/commands/doc.rs b/src/commands/doc.rs
index d0ca6b8..755a2f4 100644
--- a/src/commands/doc.rs
+++ b/src/commands/doc.rs
@@ -1,27 +1,51 @@
-//! `comline doc` — the package's documentation (core#145).
+//! `comline doc` — the package's documentation (core#145, generation#101).
//!
-//! Core builds the documentation model (`comline_core::doc`): from the
-//! compiled working tree, or from a built version's frozen IR and `//!`
-//! headers with `--version`. `--changelog-from` adds what changed since an
-//! earlier built version. `--format json` writes the model itself; any other
-//! format is a renderer's id: `markdown` and `html` are the official ones,
-//! linked in like the official generators. `[doc] renderer` in `comline.toml` names an
-//! external renderer instead, run exactly like an external generator
+//! Core builds the documentation model (`comline_core::doc`): from a built
+//! version's frozen IR and `//!` headers, or from the compiled working tree.
+//! By default every version is documented: each release, each dev build and
+//! the unreleased working state (when it differs from the last build), each
+//! with the changelog from the version before it, computed by core's rules.
+//! `[doc] versions` trims the list; `--version` documents one version alone
+//! (with `--changelog-from` adding a changelog from an earlier one).
+//!
+//! Each of `[doc] formats` lands in `//`: one folder per version
+//! (`0.2.0/`, `0.3.0-dev.2/`, `unreleased/`), then the site's index, which
+//! the renderer writes at the format's root when it renders indexes
+//! (`RendererInfo::sites`): for HTML `index.html` pointing at the latest, the
+//! picker's `versions.js` and the comparison page; for Markdown an
+//! `index.md`. `json` writes each version's model (`model.json`) and an
+//! `index.json` of the versions. `markdown` and `html` are the official
+//! renderers, linked in like the official generators; `[doc] renderer` names
+//! an external one instead, run exactly like an external generator
//! ([`crate::external`]: the same sandbox, limits and path checks).
//!
+//! **Caching.** A built version never changes, so its folder is kept between
+//! runs: `//.comline-doc.json` records, per version folder, the
+//! key it was rendered with (its commit, the commit of the version before it,
+//! the renderer and its version, the model version and the links). A folder
+//! whose key matches is left alone; the unreleased state always re-renders.
+//! A folder for a version no longer listed is removed.
+//!
//! Like `check`, nothing is written to `.comline/`.
+use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
-use comline_codegen::config::{ComlineToml, DEFAULT_DOC_FORMAT, DEFAULT_DOC_OUT};
-use comline_codegen::protocol::{FileOut, RenderOptions, RenderRequest};
+use comline_codegen::config::{
+ ComlineToml, Doc, DocVersions, DEFAULT_DOC_FORMATS, DEFAULT_DOC_OUT,
+};
+use comline_codegen::protocol::{
+ self, Description, FileOut, RenderOptions, RenderRequest, SiteVersion, VersionKind,
+};
use comline_codegen::Registry;
-use comline_core::doc::{self, DocModel, DOC_MODEL_VERSION};
-use comline_core::package::build::cas::objects::Tree;
-use comline_core::package::build::cas::ObjectStore;
+use comline_core::doc::{self, DocModel, FrozenDocs, DOC_MODEL_VERSION};
+use comline_core::package::build::cas::objects::{Commit, Tree};
+use comline_core::package::build::cas::storage::Hash;
+use comline_core::package::build::cas::{refs, ObjectStore};
use comline_core::schema::ir::frozen::unit::FrozenUnit;
use miette::{miette, IntoDiagnostic, Result, WrapErr};
+use serde::{Deserialize, Serialize};
use crate::commands::{core_err, ensure_project};
use crate::{external, history, ui};
@@ -32,9 +56,15 @@ pub struct Flags {
pub out: Option,
pub version: Option,
pub changelog_from: Option,
- pub format: Option,
+ pub formats: Vec,
}
+/// The cache manifest's file name, in each format's folder.
+pub const MANIFEST: &str = ".comline-doc.json";
+
+/// The unreleased state's folder.
+pub const UNRELEASED: &str = "unreleased";
+
/// The renderers linked into this binary.
pub(crate) fn renderer_registry() -> Registry {
let mut registry = Registry::new();
@@ -43,6 +73,20 @@ pub(crate) fn renderer_registry() -> Registry {
registry
}
+/// One version to document.
+struct Version {
+ /// Its folder: the full version, or [`UNRELEASED`].
+ id: String,
+ release: String,
+ kind: VersionKind,
+ /// Its commit; `None` for the unreleased state.
+ commit: Option,
+ model: DocModel,
+ schemas: Vec>,
+ /// What its documentation lacks.
+ notes: Vec,
+}
+
pub fn run(work_dir: &Path, flags: Flags) -> Result<()> {
ensure_project(work_dir)?;
let cfg = ComlineToml::load(work_dir)?.doc;
@@ -52,97 +96,467 @@ pub fn run(work_dir: &Path, flags: Flags) -> Result<()> {
(None, Some(out)) => work_dir.join(out),
(None, None) => work_dir.join(DEFAULT_DOC_OUT),
};
- let format = flags
- .format
- .or(cfg.format.clone())
- .unwrap_or_else(|| DEFAULT_DOC_FORMAT.to_string());
+ let mut formats: Vec = if !flags.formats.is_empty() {
+ flags.formats.clone()
+ } else {
+ cfg.formats
+ .clone()
+ .unwrap_or_else(|| DEFAULT_DOC_FORMATS.iter().map(|f| f.to_string()).collect())
+ };
+ let mut seen = std::collections::BTreeSet::new();
+ formats.retain(|f| seen.insert(f.clone()));
+ if formats.is_empty() {
+ return Err(miette!(
+ "`[doc] formats` is empty: name at least one format"
+ ));
+ }
let changelog_from = flags.changelog_from.or(cfg.changelog_from.clone());
+ let renderers = Renderers::new(work_dir, &cfg)?;
- let (mut model, schemas) = match &flags.version {
- Some(spec) => frozen_model(work_dir, spec)?,
- None => working_tree_model(work_dir)?,
- };
+ if let Some(spec) = &flags.version {
+ let mut version = frozen_version(work_dir, spec)?;
+ if let Some(from) = &changelog_from {
+ let history = history::load(work_dir)?;
+ let commit = history::resolve(&history, from)?;
+ let old = history::load_schemas(&ObjectStore::new(work_dir), commit)?;
+ version.model.changelog.push(doc::changelog(
+ &commit.version,
+ &old,
+ &version.id,
+ &version.schemas,
+ ));
+ }
+ return document_one(&out, &formats, &renderers, &cfg, version);
+ }
+ if changelog_from.is_some() {
+ ui::warn(
+ "`changelog_from` only applies with `--version`: every version already carries \
+ the changelog from the one before it",
+ );
+ }
+ let versions = every_version(work_dir, cfg.versions.as_ref())?;
+ if versions.is_empty() {
+ return Err(miette!("`[doc] versions` leaves no version to document"));
+ }
- if let Some(from) = &changelog_from {
- let history = history::load(work_dir)?;
- let commit = history::resolve(&history, from)?;
- let store = ObjectStore::new(work_dir);
- let old = history::load_schemas(&store, commit)?;
- let to = model
- .package
- .version
- .clone()
- .unwrap_or_else(|| "working tree".to_string());
- model
- .changelog
- .push(doc::changelog(&commit.version, &old, &to, &schemas));
- }
-
- let files = if format == "json" {
- let json = serde_json::to_string_pretty(&model).into_diagnostic()?;
- vec![FileOut {
- path: "model.json".into(),
- contents: format!("{json}\n").into_bytes(),
- }]
- } else {
- let request = RenderRequest {
- renderer: format.clone(),
- model_version: DOC_MODEL_VERSION,
- model: serde_json::to_string(&model).into_diagnostic()?,
- options: RenderOptions {
- links: cfg.links.clone(),
- },
- };
- match &cfg.renderer {
+ for format in &formats {
+ let dir = out.join(format);
+ let (rendered, kept) = document_site(&dir, format, &renderers, &cfg, &versions)?;
+ ui::success(format!(
+ "Documented {} version(s) of {} into {} ({rendered} rendered, {kept} unchanged)",
+ versions.len(),
+ versions[0].model.package.name,
+ dir.display()
+ ));
+ }
+ Ok(())
+}
+
+/// `--version`: one version, into `///`. The cache
+/// forgets the folder, since what's in it may differ from a full run's.
+fn document_one(
+ out: &Path,
+ formats: &[String],
+ renderers: &Renderers,
+ cfg: &Doc,
+ version: Version,
+) -> Result<()> {
+ for format in formats {
+ let dir = out.join(format);
+ let files = renderers.render_version(format, cfg, &version)?;
+ let target = dir.join(&version.id);
+ replace_dir(&target)?;
+ write_files(&target, &files)?;
+ let mut manifest = Manifest::read(&dir);
+ if manifest.versions.remove(&version.id).is_some() {
+ manifest.write(&dir)?;
+ }
+ ui::success(format!(
+ "Documented {} {} into {} ({} file(s))",
+ version.model.package.name,
+ version.id,
+ target.display(),
+ files.len()
+ ));
+ }
+ Ok(())
+}
+
+/// Every version, each rendered unless its cached folder still matches,
+/// then the site's index. Returns how many were rendered and kept.
+fn document_site(
+ dir: &Path,
+ format: &str,
+ renderers: &Renderers,
+ cfg: &Doc,
+ versions: &[Version],
+) -> Result<(usize, usize)> {
+ let old = Manifest::read(dir);
+ let mut manifest = Manifest::default();
+ let renderer_key = renderers.key(format);
+ let (mut rendered, mut kept) = (0, 0);
+ for (i, version) in versions.iter().enumerate() {
+ let previous = i.checked_sub(1).and_then(|p| versions[p].commit);
+ let key = version
+ .commit
+ .map(|commit| cache_key(&commit, previous.as_ref(), &renderer_key, &cfg.links));
+ let target = dir.join(&version.id);
+ if old.reuses(&version.id, &key) && target.is_dir() {
+ manifest.versions.insert(version.id.clone(), key);
+ kept += 1;
+ continue;
+ }
+ let files = renderers.render_version(format, cfg, version)?;
+ replace_dir(&target)?;
+ write_files(&target, &files)?;
+ manifest.versions.insert(version.id.clone(), key);
+ rendered += 1;
+ }
+ // A version no longer listed (trimmed away, or the unreleased state now
+ // built): its folder goes.
+ for id in old.versions.keys() {
+ if !manifest.versions.contains_key(id) {
+ let stale = dir.join(id);
+ if stale.is_dir() {
+ std::fs::remove_dir_all(&stale)
+ .into_diagnostic()
+ .wrap_err_with(|| format!("failed to remove `{}`", stale.display()))?;
+ }
+ }
+ }
+ let index = renderers.render_index(format, cfg, versions)?;
+ write_files(dir, &index)?;
+ manifest.write(dir)?;
+ Ok((rendered, kept))
+}
+
+/// `//.comline-doc.json`: each version folder's cache key
+/// (`null` for the unreleased state, never reused).
+#[derive(Debug, Default, Serialize, Deserialize)]
+struct Manifest {
+ versions: BTreeMap>,
+}
+
+/// A built version folder's cache key: everything its pages are rendered
+/// from. `renderer_key` is [`Renderers::key`], which moves whenever the
+/// renderer's output can (a built-in's version carries a content hash of
+/// its sources and assets).
+fn cache_key(
+ commit: &Hash,
+ previous: Option<&Hash>,
+ renderer_key: &str,
+ links: &BTreeMap,
+) -> String {
+ let previous = previous
+ .map(|c| c.to_hex())
+ .unwrap_or_else(|| "none".into());
+ format!(
+ "commit {} after {previous}; {renderer_key}; model {DOC_MODEL_VERSION}; links {links:?}",
+ commit.to_hex()
+ )
+}
+
+impl Manifest {
+ /// Whether the folder `id` was rendered with `key`; never for the
+ /// unreleased state, which has none.
+ fn reuses(&self, id: &str, key: &Option) -> bool {
+ key.is_some() && self.versions.get(id) == Some(key)
+ }
+
+ /// The manifest in `dir`; empty when there's none or it doesn't parse.
+ fn read(dir: &Path) -> Self {
+ std::fs::read_to_string(dir.join(MANIFEST))
+ .ok()
+ .and_then(|text| serde_json::from_str(&text).ok())
+ .unwrap_or_default()
+ }
+
+ fn write(&self, dir: &Path) -> Result<()> {
+ let json = serde_json::to_string_pretty(self).into_diagnostic()?;
+ write_files(
+ dir,
+ &[FileOut {
+ path: MANIFEST.into(),
+ contents: format!("{json}\n").into_bytes(),
+ }],
+ )
+ }
+}
+
+/// The renderer side: the built-ins, or `[doc] renderer`.
+struct Renderers {
+ registry: Registry,
+ external: Option,
+}
+
+struct External {
+ renderer: external::External,
+ description: Description,
+ /// The renderer file's hash, part of the cache key.
+ hash: String,
+}
+
+impl Renderers {
+ fn new(work_dir: &Path, cfg: &Doc) -> Result {
+ let external = match &cfg.renderer {
Some(path) => {
+ let path = work_dir.join(path);
let timeout = cfg
.timeout
.map(Duration::from_secs)
.unwrap_or(external::DEFAULT_TIMEOUT);
- let renderer = external::External::open(&work_dir.join(path), timeout)?;
+ let renderer = external::External::open(&path, timeout)?;
let description = renderer.describe()?;
- renderer.render(&description, request)?
+ let bytes = std::fs::read(&path)
+ .into_diagnostic()
+ .wrap_err_with(|| format!("failed to read `{}`", path.display()))?;
+ Some(External {
+ renderer,
+ description,
+ hash: Hash::from_bytes(&bytes).to_hex(),
+ })
}
- None => external::builtin_render(&renderer_registry(), request)?,
+ None => None,
+ };
+ Ok(Renderers {
+ registry: renderer_registry(),
+ external,
+ })
+ }
+
+ fn description(&self) -> Description {
+ match &self.external {
+ Some(external) => external.description.clone(),
+ None => protocol::describe(&self.registry),
}
- };
+ }
- for file in &files {
- let path = out.join(file.path_buf());
- if let Some(parent) = path.parent() {
- std::fs::create_dir_all(parent)
- .into_diagnostic()
- .wrap_err_with(|| format!("failed to create `{}`", parent.display()))?;
+ /// What identifies `format`'s renderer in the cache key.
+ fn key(&self, format: &str) -> String {
+ if format == "json" {
+ return format!("json via comline {}", env!("CARGO_PKG_VERSION"));
+ }
+ let version = self
+ .description()
+ .renderers
+ .into_iter()
+ .find(|r| r.id == format)
+ .map(|r| r.version)
+ .unwrap_or_default();
+ match &self.external {
+ Some(external) => format!("{format}@{version} from {}", external.hash),
+ None => format!(
+ "{format}@{version} via comline {}",
+ env!("CARGO_PKG_VERSION")
+ ),
}
- std::fs::write(&path, &file.contents)
- .into_diagnostic()
- .wrap_err_with(|| format!("failed to write `{}`", path.display()))?;
}
- ui::success(format!(
- "Documented {} into {} ({} file(s))",
- match &model.package.version {
- Some(v) => format!("{} {v}", model.package.name),
- None => model.package.name.clone(),
- },
- out.display(),
- files.len()
- ));
- Ok(())
+
+ fn render(&self, request: RenderRequest) -> Result> {
+ match &self.external {
+ Some(external) => external.renderer.render(&external.description, request),
+ None => external::builtin_render(&self.registry, request),
+ }
+ }
+
+ /// One version's files, relative to its folder.
+ fn render_version(&self, format: &str, cfg: &Doc, version: &Version) -> Result> {
+ if format == "json" {
+ let json = serde_json::to_string_pretty(&version.model).into_diagnostic()?;
+ return Ok(vec![FileOut {
+ path: "model.json".into(),
+ contents: format!("{json}\n").into_bytes(),
+ }]);
+ }
+ self.render(RenderRequest {
+ renderer: format.to_string(),
+ model_version: DOC_MODEL_VERSION,
+ model: serde_json::to_string(&version.model).into_diagnostic()?,
+ options: RenderOptions {
+ links: cfg.links.clone(),
+ version: Some(version.id.clone()),
+ versions: vec![],
+ notes: version.notes.clone(),
+ },
+ })
+ }
+
+ /// The site's index, relative to the format's folder: `index.json` for
+ /// `json`, the renderer's own when it renders indexes, else nothing.
+ fn render_index(&self, format: &str, cfg: &Doc, versions: &[Version]) -> Result> {
+ let latest = latest(versions);
+ if format == "json" {
+ let list: Vec = versions
+ .iter()
+ .map(|v| {
+ serde_json::json!({
+ "id": v.id, "release": v.release, "kind": v.kind.as_str(),
+ "model": format!("{}/model.json", v.id),
+ })
+ })
+ .collect();
+ let index = serde_json::json!({
+ "package": latest.model.package.name,
+ "model_version": DOC_MODEL_VERSION,
+ "latest": latest.id,
+ "versions": list,
+ });
+ let json = serde_json::to_string_pretty(&index).into_diagnostic()?;
+ return Ok(vec![FileOut {
+ path: "index.json".into(),
+ contents: format!("{json}\n").into_bytes(),
+ }]);
+ }
+ let sites = self
+ .description()
+ .renderers
+ .iter()
+ .any(|r| r.id == format && r.sites);
+ if !sites {
+ ui::note(format!(
+ "the `{format}` renderer doesn't render a site index: each version has its own folder"
+ ));
+ return Ok(vec![]);
+ }
+ let mut site = vec![];
+ for v in versions {
+ site.push(SiteVersion {
+ id: v.id.clone(),
+ release: v.release.clone(),
+ kind: v.kind,
+ model: serde_json::to_string(&v.model).into_diagnostic()?,
+ });
+ }
+ self.render(RenderRequest {
+ renderer: format.to_string(),
+ model_version: DOC_MODEL_VERSION,
+ model: serde_json::to_string(&latest.model).into_diagnostic()?,
+ options: RenderOptions {
+ links: cfg.links.clone(),
+ version: None,
+ versions: site,
+ notes: vec![],
+ },
+ })
+ }
+}
+
+/// The newest release, else the newest dev build, else the unreleased state.
+fn latest(versions: &[Version]) -> &Version {
+ [
+ VersionKind::Release,
+ VersionKind::Dev,
+ VersionKind::Unreleased,
+ ]
+ .into_iter()
+ .find_map(|kind| versions.iter().rev().find(|v| v.kind == kind))
+ .expect("at least one version")
}
-/// The working tree's model, and its frozen schemas for a changelog.
-fn working_tree_model(work_dir: &Path) -> Result<(DocModel, Vec>)> {
+/// Every built version, oldest first, then the unreleased state when it
+/// differs from the last build; trimmed by `[doc] versions`; each with the
+/// changelog from the one before it.
+fn every_version(work_dir: &Path, select: Option<&DocVersions>) -> Result> {
+ let mut versions = vec![];
+ let mut head: Option<(Vec>, FrozenDocs)> = None;
+ if refs::ref_exists(work_dir, refs::main_ref()) {
+ let history = history::load(work_dir)?;
+ let mut seen = std::collections::BTreeSet::new();
+ for entry in &history {
+ // Newest first: a version built twice keeps its newest commit.
+ if !seen.insert(entry.commit.version.clone()) {
+ continue;
+ }
+ let (version, docs) = frozen(work_dir, entry.hash, &entry.commit)?;
+ if head.is_none() {
+ head = Some((version.schemas.clone(), docs));
+ }
+ versions.push(version);
+ }
+ versions.reverse();
+ }
+
let spinner = ui::spinner("compiling schemas");
let outcome = comline_core::package::build::compile_package(work_dir);
ui::finish_spinner(spinner);
let context = outcome.map_err(|e| core_err("validation failed", e))?;
- Ok((doc::model(&context, None), doc::frozen_schemas(&context)))
+ let schemas = doc::frozen_schemas(&context);
+ let docs = doc::frozen_docs(&context);
+ let changed = match &head {
+ Some((head_schemas, head_docs)) => *head_schemas != schemas || *head_docs != docs,
+ None => true,
+ };
+ if changed {
+ versions.push(Version {
+ id: UNRELEASED.into(),
+ release: UNRELEASED.into(),
+ kind: VersionKind::Unreleased,
+ commit: None,
+ model: doc::model(&context, None),
+ schemas,
+ notes: vec![],
+ });
+ }
+
+ if let Some(DocVersions::Select(select)) = select {
+ if select.releases_only {
+ versions.retain(|v| v.kind == VersionKind::Release);
+ }
+ if let Some(since) = &select.since {
+ let Some(at) = versions.iter().position(|v| &v.id == since) else {
+ let available: Vec<&str> = versions.iter().map(|v| v.id.as_str()).collect();
+ return Err(miette!(
+ "`[doc] versions` since `{since}`: no such version (available: {})",
+ available.join(", ")
+ ));
+ };
+ versions.drain(..at);
+ }
+ if let Some(last) = select.last {
+ let drop = versions.len().saturating_sub(last);
+ versions.drain(..drop);
+ }
+ }
+
+ // Each version's changelog from the one before it in the list.
+ for i in 1..versions.len() {
+ let (before, after) = versions.split_at_mut(i);
+ let previous = &before[i - 1];
+ let log = doc::changelog(
+ &previous.id,
+ &previous.schemas,
+ &after[0].id,
+ &after[0].schemas,
+ );
+ after[0].model.changelog = vec![log];
+ }
+ Ok(versions)
}
-/// A built version's model, from its frozen IR and headers.
-fn frozen_model(work_dir: &Path, spec: &str) -> Result<(DocModel, Vec>)> {
+/// `0.3.0-dev.2` leads to the release `0.3.0`; `0.3.0` is one.
+fn kind_of(version: &str) -> (VersionKind, String) {
+ match version.split_once('-') {
+ Some((release, _)) => (VersionKind::Dev, release.to_string()),
+ None => (VersionKind::Release, version.to_string()),
+ }
+}
+
+/// `--version`'s one built version.
+fn frozen_version(work_dir: &Path, spec: &str) -> Result {
let history = history::load(work_dir)?;
let commit = history::resolve(&history, spec)?;
+ let entry = history
+ .iter()
+ .find(|e| std::ptr::eq(&e.commit, commit))
+ .expect("resolved from this history");
+ Ok(frozen(work_dir, entry.hash, commit)?.0)
+}
+
+/// A built version's model, from its frozen IR and headers, with notes on
+/// what an old version lacks; and its headers, to compare the working
+/// tree's with.
+fn frozen(work_dir: &Path, hash: Hash, commit: &Commit) -> Result<(Version, FrozenDocs)> {
+ let spec = &commit.version;
let store = ObjectStore::new(work_dir);
let schemas = history::load_schemas(&store, commit)?;
let config = history::load_config(&store, commit)?;
@@ -169,6 +583,115 @@ fn frozen_model(work_dir: &Path, spec: &str) -> Result<(DocModel, Vec Result<()> {
+ if dir.is_dir() {
+ std::fs::remove_dir_all(dir)
+ .into_diagnostic()
+ .wrap_err_with(|| format!("failed to remove `{}`", dir.display()))?;
+ }
+ std::fs::create_dir_all(dir)
+ .into_diagnostic()
+ .wrap_err_with(|| format!("failed to create `{}`", dir.display()))
+}
+
+fn write_files(dir: &Path, files: &[FileOut]) -> Result<()> {
+ for file in files {
+ let path = dir.join(file.path_buf());
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)
+ .into_diagnostic()
+ .wrap_err_with(|| format!("failed to create `{}`", parent.display()))?;
+ }
+ std::fs::write(&path, &file.contents)
+ .into_diagnostic()
+ .wrap_err_with(|| format!("failed to write `{}`", path.display()))?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A built-in renderer's key carries its content-hashed version, so a
+ /// CLI with a changed renderer re-renders every folder.
+ #[test]
+ fn a_changed_renderer_invalidates_every_folder() {
+ let renderers = Renderers {
+ registry: renderer_registry(),
+ external: None,
+ };
+ for (format, version) in [
+ ("html", comline_doc_html::RENDERER.version),
+ ("markdown", comline_doc_markdown::RENDERER.version),
+ ] {
+ assert!(version.contains('+'), "{version}");
+ assert!(renderers
+ .key(format)
+ .contains(&format!("{format}@{version} ")));
+ }
+
+ let links = BTreeMap::new();
+ let commits: Vec = (0..3u8).map(|i| Hash::from_bytes(&[i])).collect();
+ let keyed = |renderer: &str| {
+ let mut manifest = Manifest::default();
+ for (i, commit) in commits.iter().enumerate() {
+ let previous = i.checked_sub(1).map(|p| &commits[p]);
+ let key = cache_key(commit, previous, renderer, &links);
+ manifest.versions.insert(format!("v{i}"), Some(key));
+ }
+ manifest
+ };
+ let old = keyed("html@0.1.0+0000000000000000 via comline 0.2.0");
+ let same = keyed("html@0.1.0+0000000000000000 via comline 0.2.0");
+ let changed = keyed("html@0.1.0+0000000000000001 via comline 0.2.0");
+ for (id, key) in &same.versions {
+ assert!(old.reuses(id, key), "{id} should be kept");
+ }
+ for (id, key) in &changed.versions {
+ assert!(!old.reuses(id, key), "{id} should re-render");
+ }
+ // The unreleased state is never reused.
+ assert!(!old.reuses("unreleased", &None));
+ }
}
diff --git a/src/commands/new.rs b/src/commands/new.rs
index 141bec5..522a486 100644
--- a/src/commands/new.rs
+++ b/src/commands/new.rs
@@ -26,6 +26,8 @@ const GITIGNORE: &str = "\
# `.comline/` holds the package's version history: commit it.
# Fetched git dependencies are a local cache.
.comline/deps-cache/
+# `comline doc --format html`: a generated site, rebuilt from `.comline/`.
+docs/api/html/
";
/// Consumer-owned code-generation config. Committed. All-commented by default —
diff --git a/src/main.rs b/src/main.rs
index aa0e8a5..a044cbf 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -130,7 +130,7 @@ fn run(cli: Cli) -> Result<()> {
out,
version: doc_version,
changelog_from,
- format,
+ formats: format,
},
),
Commands::Generate {
diff --git a/tests/cli/doc.rs b/tests/cli/doc.rs
index 3825b36..f25e04e 100644
--- a/tests/cli/doc.rs
+++ b/tests/cli/doc.rs
@@ -36,9 +36,12 @@ fn writes_markdown_pages_for_the_working_tree() {
.arg("doc")
.assert()
.success()
- .stderr(predicate::str::contains("Documented shop"));
+ .stderr(predicate::str::contains("Documented 1 version(s) of shop"));
- let out = shop.join("docs/api");
+ // Nothing built: the unreleased state is the one version.
+ let site = shop.join("docs/api/markdown");
+ assert!(read(&site.join("index.md")).contains("- [unreleased](unreleased/index.md)"));
+ let out = site.join("unreleased");
let index = read(&out.join("index.md"));
assert!(index.starts_with("# shop\n\nA shop.\n"), "{index}");
assert!(index.contains("| [`api`](api.md) | The shop's API. |"));
@@ -84,23 +87,30 @@ fn documents_a_built_version_with_its_frozen_headers_and_a_changelog() {
.args(["doc", "--version", "0.1.0-dev.1", "--out", "v1"])
.assert()
.success();
- let index = read(&shop.join("v1/index.md"));
+ assert!(!shop.join("v1/markdown/index.md").exists());
+ let index = read(&shop.join("v1/markdown/0.1.0-dev.1/index.md"));
assert!(
- index.starts_with("# shop 0.1.0-dev.1\n\nA shop.\n"),
+ index.starts_with("# shop 0.1.0-dev.1\n\n> **Note:** Built versions don't record")
+ && index.contains("\n\nA shop.\n"),
"{index}"
);
- let api = read(&shop.join("v1/api.md"));
- assert!(api.starts_with("# `api`\n\nThe shop's API.\n"), "{api}");
+ let api = read(&shop.join("v1/markdown/0.1.0-dev.1/api.md"));
+ assert!(api.starts_with("# `api`\n\n> **Note:**"), "{api}");
+ assert!(api.contains("\n\nThe shop's API.\n"), "{api}");
assert!(!api.contains("note"));
comline_cmd()
.current_dir(&shop)
- .args(["doc", "--changelog-from", "0.1.0-dev.1", "--out", "now"])
+ .args(["doc", "--out", "now"])
.assert()
.success();
- let changelog = read(&shop.join("now/changelog.md"));
+ // The working tree is the last build: no unreleased state, and each
+ // version carries the changelog from the one before it.
+ assert!(!shop.join("now/markdown/unreleased").exists());
+ assert!(!shop.join("now/markdown/0.1.0-dev.1/changelog.md").exists());
+ let changelog = read(&shop.join("now/markdown/0.1.0-dev.2/changelog.md"));
assert!(
- changelog.contains("## 0.1.0-dev.1 to working tree"),
+ changelog.contains("## 0.1.0-dev.1 to 0.1.0-dev.2"),
"{changelog}"
);
assert!(changelog.contains("field name: `note`"), "{changelog}");
@@ -113,7 +123,7 @@ fn json_writes_the_model_and_doc_settings_come_from_comline_toml() {
package(&shop, "", API);
fs::write(
shop.join("comline.toml"),
- "[doc]\nout = \"site\"\nformat = \"json\"\n",
+ "[doc]\nout = \"site\"\nformats = [\"json\"]\n",
)
.unwrap();
@@ -123,10 +133,14 @@ fn json_writes_the_model_and_doc_settings_come_from_comline_toml() {
.assert()
.success();
let model: serde_json::Value =
- serde_json::from_str(&read(&shop.join("site/model.json"))).unwrap();
+ serde_json::from_str(&read(&shop.join("site/json/unreleased/model.json"))).unwrap();
assert_eq!(model["model_version"], 1);
assert_eq!(model["package"]["name"], "shop");
assert_eq!(model["modules"][0]["docs"], "The shop's API.");
+ let index: serde_json::Value =
+ serde_json::from_str(&read(&shop.join("site/json/index.json"))).unwrap();
+ assert_eq!(index["latest"], "unreleased");
+ assert_eq!(index["versions"][0]["model"], "unreleased/model.json");
}
#[test]
@@ -146,7 +160,7 @@ fn an_unknown_format_names_what_is_offered() {
}
#[test]
-fn html_writes_a_self_contained_site() {
+fn html_writes_a_self_contained_site_per_version() {
let temp = tempfile::tempdir().unwrap();
let shop = temp.path().join("shop");
package(&shop, "//! A shop.\n\n", API);
@@ -155,22 +169,34 @@ fn html_writes_a_self_contained_site() {
.arg("build")
.assert()
.success();
+ package(
+ &shop,
+ "//! A shop.\n\n",
+ &API.replace(
+ " total: u64\n",
+ " total: u64\n optional note: string\n",
+ ),
+ );
comline_cmd()
.current_dir(&shop)
- .args([
- "doc",
- "--format",
- "html",
- "--out",
- "site",
- "--changelog-from",
- "0.1.0-dev.1",
- ])
+ .args(["doc", "--format", "html", "--out", "site"])
.assert()
.success();
- let out = shop.join("site");
+ let site = shop.join("site/html");
+ // The root points at the latest version, which is the dev build here.
+ let root = read(&site.join("index.html"));
+ assert!(root.contains("url=0.1.0-dev.1/index.html"), "{root}");
+ assert!(read(&site.join("versions.js")).contains("var LATEST = \"0.1.0-dev.1\";"));
+ let compare = read(&site.join("compare.js"));
+ assert!(
+ compare.contains("\"api::Order.note\":\"optional string\""),
+ "{compare}"
+ );
+ assert!(site.join("compare.html").exists());
+
+ let out = site.join("unreleased");
let index = read(&out.join("index.html"));
assert!(index.starts_with(""), "{index}");
assert!(index.contains("