From 901cada824ac1024837d7de8c0f8733afaf6a0fd Mon Sep 17 00:00:00 2001 From: Kinflou Date: Sun, 1 Nov 2026 21:41:09 +0800 Subject: [PATCH 1/5] doc: every version, per-format paths, a cache, and [doc] formats/versions comline doc now documents every release, dev build and the unreleased working state (when it differs from the last build), each into /// with the changelog from the version before it, then asks the renderer for the site's index: index.html, the version picker's versions.js and compare.html for HTML, index.md for Markdown, index.json for json. A built version's folder is cached by its commit, the previous version's commit, the renderer and its version, the model version and the links, in //.comline-doc.json; a second run re-renders only the unreleased state and new versions. [doc] versions trims the list (all, last, since, releases_only); --version documents one version alone. Old versions carry notes for what they lack (headers before core#152, wire tables until core#153). --format is repeatable and comma-separated; [doc] format is now formats. comline new gitignores docs/api/html/. Pins comline-codegen and the doc renderers at generation 5eb12c0, comline-rust b999d67 and comline-typescript 355b67c. --- Cargo.lock | 10 +- Cargo.toml | 10 +- src/cli.rs | 58 ++-- src/commands/doc.rs | 616 ++++++++++++++++++++++++++++++++++++------ src/commands/new.rs | 2 + src/main.rs | 2 +- tests/cli/doc.rs | 180 ++++++++++-- tests/cli/external.rs | 6 +- tests/cli/new.rs | 1 + 9 files changed, 742 insertions(+), 143 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d93203c..7dc07b5 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=5eb12c00a6ce93842695a27f175d873609617bd9#5eb12c00a6ce93842695a27f175d873609617bd9" 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=b999d6793f17f2fc1356ddf4bbeddc989c117d69#b999d6793f17f2fc1356ddf4bbeddc989c117d69" 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=355b67c4ef89ec398c79c42122f47988faba62cd#355b67c4ef89ec398c79c42122f47988faba62cd" 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=5eb12c00a6ce93842695a27f175d873609617bd9#5eb12c00a6ce93842695a27f175d873609617bd9" 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=5eb12c00a6ce93842695a27f175d873609617bd9#5eb12c00a6ce93842695a27f175d873609617bd9" dependencies = [ "comline-codegen", "eyre", diff --git a/Cargo.toml b/Cargo.toml index 1bc7615..8e9895f 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 = "5eb12c00a6ce93842695a27f175d873609617bd9" } # 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 = "5eb12c00a6ce93842695a27f175d873609617bd9" } +comline-doc-html = { git = "https://github.com/ComlineProject/generation", rev = "5eb12c00a6ce93842695a27f175d873609617bd9" } +comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "b999d6793f17f2fc1356ddf4bbeddc989c117d69", optional = true } +comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "355b67c4ef89ec398c79c42122f47988faba62cd", 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/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..0725ddc 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,441 @@ 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 key = version.commit.map(|commit| { + let previous = i + .checked_sub(1) + .and_then(|p| versions[p].commit) + .map(|c| c.to_hex()) + .unwrap_or_else(|| "none".into()); + format!( + "commit {} after {previous}; {renderer_key}; model {DOC_MODEL_VERSION}; links {:?}", + commit.to_hex(), + cfg.links + ) + }); + let target = dir.join(&version.id); + if key.is_some() && old.versions.get(&version.id) == Some(&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>, +} + +impl Manifest { + /// 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) +} + +/// `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()), + } } -/// A built version's model, from its frozen IR and headers. -fn frozen_model(work_dir: &Path, spec: &str) -> Result<(DocModel, Vec>)> { +/// `--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 +557,68 @@ 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(()) } 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..f9fca38 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,28 @@ 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("

shop

\n

A shop.

"), "{index}"); @@ -183,10 +203,17 @@ fn html_writes_a_self_contained_site() { assert!(api.contains("Order")); assert!(api.contains("

On the wire

")); assert!(api.contains("")); + assert!(api.contains("")); + assert!(api.contains("