diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
Documentation
use std::net::IpAddr;
use std::path::PathBuf;

use clap::{Args, Parser, Subcommand};

#[derive(Debug, Parser)]
#[command(name = "diplodocus", version, about = env!("CARGO_PKG_DESCRIPTION"), styles = terminal_styles())]
pub(super) struct Cli {
    /// Control terminal colors in help, diagnostics, and status output.
    #[arg(long, global = true, value_enum, default_value_t = clap::ColorChoice::Auto)]
    pub(super) color: clap::ColorChoice,
    /// Print stage summaries instead of animated progress bars.
    #[arg(long, global = true)]
    pub(super) no_progress: bool,
    /// Suppress routine status output while retaining warnings and errors.
    #[arg(short, long, global = true)]
    pub(super) quiet: bool,
    #[command(subcommand)]
    pub(super) command: Command,
}

const fn terminal_styles() -> clap::builder::styling::Styles {
    use clap::builder::styling::{AnsiColor, Styles};
    Styles::styled()
        .header(AnsiColor::Cyan.on_default().bold())
        .usage(AnsiColor::Cyan.on_default().bold())
        .literal(AnsiColor::Green.on_default().bold())
        .placeholder(AnsiColor::Cyan.on_default())
        .error(AnsiColor::Red.on_default().bold())
        .invalid(AnsiColor::Red.on_default())
        .valid(AnsiColor::Green.on_default())
}

#[derive(Debug, Subcommand)]
pub(super) enum Command {
    /// Build a static documentation site.
    Build(BuildArgs),
    /// Check documentation without writing a site.
    Check(CheckArgs),
    /// Extract a portable SQLite documentation snapshot.
    Extract(ExtractArgs),
    /// Work with portable package API bundles.
    Bundle {
        #[command(subcommand)]
        command: BundleCommand,
    },
    /// Generate a site using only a completed snapshot.
    Generate(GenerateArgs),
    /// Build and serve a site, rebuilding when declared inputs change.
    Serve(ServeArgs),
}

#[derive(Debug, Subcommand)]
pub(super) enum BundleCommand {
    /// Extract and export one package API bundle.
    Export {
        /// Recompute results without using incremental caches.
        #[arg(long)]
        no_cache: bool,
        /// Producer configuration file.
        #[arg(long, default_value = "./diplodocus.yaml")]
        config: PathBuf,
        /// Destination SQLite artifact.
        #[arg(long)]
        output: PathBuf,
    },
}

#[derive(Debug, Args)]
pub(super) struct BuildArgs {
    /// Recompute results without reading or writing incremental caches.
    #[arg(long)]
    pub(super) no_cache: bool,
    /// Path to the workspace configuration file.
    #[arg(long, value_name = "PATH", default_value = "./diplodocus.yaml")]
    pub(super) config: PathBuf,
    /// Directory in which to write the generated site.
    #[arg(long, value_name = "PATH", default_value = "./site")]
    pub(super) output: PathBuf,
}

#[derive(Debug, Args)]
pub(super) struct CheckArgs {
    /// Recompute results without reading or writing incremental caches.
    #[arg(long)]
    pub(super) no_cache: bool,
    /// Path to the workspace configuration file.
    #[arg(long, value_name = "PATH", default_value = "./diplodocus.yaml")]
    pub(super) config: PathBuf,
}

#[derive(Debug, Args)]
pub(super) struct ExtractArgs {
    /// Recompute results without reading or writing incremental caches.
    #[arg(long)]
    pub(super) no_cache: bool,
    /// Path to the workspace configuration file.
    #[arg(long, value_name = "PATH", default_value = "./diplodocus.yaml")]
    pub(super) config: PathBuf,
    /// Snapshot destination (defaults to .diplodocus/documentation.sqlite beside the configuration).
    #[arg(long, value_name = "PATH")]
    pub(super) output: Option<PathBuf>,
    /// Re-extract changed inputs and emit a JSON line after each published snapshot.
    #[arg(long)]
    pub(super) watch: bool,
}

#[derive(Debug, Args)]
pub(super) struct GenerateArgs {
    /// Emit executable browser bundles retained in this trusted snapshot.
    #[arg(long)]
    pub(super) allow_components: bool,
    /// Completed SQLite documentation snapshot.
    #[arg(long, value_name = "PATH")]
    pub(super) input: PathBuf,
    /// Directory in which to write the generated site.
    #[arg(long, value_name = "PATH", default_value = "./site")]
    pub(super) output: PathBuf,
    /// Output complete site pages or embeddable HTML and Markdown fragments.
    #[arg(long, value_enum, default_value = "site")]
    pub(super) format: GenerateFormat,
    /// Public document and asset URL map (requires --format fragments).
    #[arg(long, value_name = "PATH")]
    pub(super) url_map: Option<PathBuf>,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub(super) enum GenerateFormat {
    Site,
    Fragments,
}

#[derive(Debug, Args)]
pub(super) struct ServeArgs {
    /// Recompute results without reading or writing incremental caches.
    #[arg(long)]
    pub(super) no_cache: bool,
    /// Path to the workspace configuration file.
    #[arg(long, value_name = "PATH", default_value = "./diplodocus.yaml")]
    pub(super) config: PathBuf,
    /// Directory in which to write the generated site.
    #[arg(long, value_name = "PATH", default_value = "./site")]
    pub(super) output: PathBuf,
    /// Address on which to serve the generated site.
    #[arg(long, value_name = "ADDRESS", default_value = "127.0.0.1")]
    pub(super) host: IpAddr,
    /// Port on which to serve the generated site.
    #[arg(long, value_name = "PORT", default_value_t = 8000)]
    pub(super) port: u16,
    /// Refresh open browser pages after successful rebuilds (enabled by default).
    #[arg(long, default_value_t = true, action = clap::ArgAction::SetTrue)]
    pub(super) live_reload: bool,
    /// Disable automatic browser refresh after successful rebuilds.
    #[arg(long, conflicts_with = "live_reload")]
    pub(super) no_live_reload: bool,
    /// Open the local preview in a browser after the first successful build.
    #[arg(long)]
    pub(super) open: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn build_defaults_match_the_command_contract() {
        let cli = Cli::try_parse_from(["diplodocus", "build"]).unwrap();
        let Command::Build(args) = cli.command else {
            panic!("expected the build command");
        };
        assert_eq!(args.config, PathBuf::from("./diplodocus.yaml"));
        assert_eq!(args.output, PathBuf::from("./site"));
    }

    #[test]
    fn check_defaults_match_the_command_contract() {
        let cli = Cli::try_parse_from(["diplodocus", "check"]).unwrap();
        let Command::Check(args) = cli.command else {
            panic!("expected the check command");
        };
        assert_eq!(args.config, PathBuf::from("./diplodocus.yaml"));
    }

    #[test]
    fn extract_defaults_match_the_command_contract() {
        let cli = Cli::try_parse_from(["diplodocus", "extract"]).unwrap();
        let Command::Extract(args) = cli.command else {
            panic!("expected the extract command");
        };
        assert_eq!(args.config, PathBuf::from("./diplodocus.yaml"));
        assert!(args.output.is_none());
        assert!(!args.watch);
    }

    #[test]
    fn serve_defaults_match_the_command_contract() {
        let cli = Cli::try_parse_from(["diplodocus", "serve"]).unwrap();
        let Command::Serve(args) = cli.command else {
            panic!("expected the serve command");
        };
        assert_eq!(args.config, PathBuf::from("./diplodocus.yaml"));
        assert_eq!(args.output, PathBuf::from("./site"));
        assert_eq!(args.host, IpAddr::from([127, 0, 0, 1]));
        assert_eq!(args.port, 8000);
        assert!(args.live_reload);
        assert!(!args.no_live_reload);
        assert!(!args.open);
    }

    #[test]
    fn serve_accepts_browser_opening_with_live_reload() {
        let cli = Cli::try_parse_from(["diplodocus", "serve", "--open", "--live-reload"]).unwrap();
        let Command::Serve(args) = cli.command else {
            panic!("expected the serve command");
        };
        assert!(args.open);
        assert!(args.live_reload);
    }

    #[test]
    fn serve_can_disable_browser_refresh() {
        let cli = Cli::try_parse_from(["diplodocus", "serve", "--no-live-reload"]).unwrap();
        let Command::Serve(args) = cli.command else {
            panic!("expected the serve command");
        };
        assert!(args.no_live_reload);
        assert!(
            Cli::try_parse_from(["diplodocus", "serve", "--no-live-reload", "--live-reload"])
                .is_err()
        );
    }

    #[test]
    fn source_commands_accept_cache_bypass() {
        for command in ["check", "extract", "build", "serve"] {
            let cli = Cli::try_parse_from(["diplodocus", command, "--no-cache"]).unwrap();
            match cli.command {
                Command::Check(args) => assert!(args.no_cache),
                Command::Extract(args) => assert!(args.no_cache),
                Command::Build(args) => assert!(args.no_cache),
                Command::Serve(args) => assert!(args.no_cache),
                Command::Generate(_) | Command::Bundle { .. } => unreachable!(),
            }
        }
    }
}