cdk-rsx-cli 0.1.1

Build and test Internet Computer canisters with CDK RSX
use crate::{cargo, receipt};
use anyhow::{Context, Result, ensure};
use clap::{Args, Subcommand};
use serde_json::Value;
use std::{
    io::{Seek, Write},
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

const GENERATOR: &str = "cdk-rsx-takt-generator";

#[derive(Args)]
pub(crate) struct Options {
    #[arg(long, global = true, default_value = "Cargo.toml")]
    manifest_path: PathBuf,
    #[arg(short = 'p', long, global = true)]
    package: Option<String>,
    #[arg(short = 'F', long, global = true)]
    features: Vec<String>,
    #[arg(long, global = true)]
    all_features: bool,
    #[arg(long, global = true)]
    no_default_features: bool,
    #[arg(long, global = true)]
    offline: bool,
    #[command(subcommand)]
    command: Operation,
}

#[derive(Subcommand)]
enum Operation {
    /// Validate a workflow graph with the application's generator.
    Check { document: PathBuf },
    /// Draft missing workflow modules alongside the graph.
    Scaffold {
        document: PathBuf,
        #[arg(long)]
        scope: Option<String>,
    },
    /// Check the selected canister and map generated Rust errors to JSON.
    CheckProject,
}

pub(crate) fn run(options: Options) -> Result<()> {
    let manifest = options
        .manifest_path
        .canonicalize()
        .with_context(|| format!("open Takt app manifest {}", options.manifest_path.display()))?;
    let compiler = cargo::Compiler::select(options.offline)?;
    compiler.prepare_lock(&manifest, false, options.offline)?;
    let features = cargo::feature_flags(
        options.features,
        options.all_features,
        options.no_default_features,
    );
    if !options.offline {
        compiler.fetch(&manifest, None)?;
    }
    let metadata = compiler.metadata(&manifest, &features, Some(&compiler.host), true)?;
    let (app, _) = cargo::app_library(&metadata, &manifest, options.package.as_deref())?;
    let app_manifest = Path::new(
        app["manifest_path"]
            .as_str()
            .context("missing canister manifest path")?,
    );
    let directory = app_manifest
        .parent()
        .context("missing canister directory")?;
    let package = generator_package(&metadata, app)?;
    let generator = generator(&compiler, directory, &metadata, package, options.offline)?;
    let mut command = compiler.command(&generator, directory);
    command.env("CARGO", &compiler.cargo);
    match options.command {
        Operation::Check { document } => {
            command.arg("check").arg(document.canonicalize()?);
        }
        Operation::Scaffold { document, scope } => {
            let document = document.canonicalize()?;
            command
                .arg("scaffold")
                .arg(document.strip_prefix(directory).unwrap_or(&document));
            if let Some(scope) = scope {
                command.arg("--scope").arg(scope);
            }
        }
        Operation::CheckProject => {
            let package = app["name"]
                .as_str()
                .context("missing Cargo app package name")?;
            command
                .args(["check-project", "--manifest-path"])
                .arg(app_manifest)
                .args([
                    "--",
                    "--locked",
                    "--offline",
                    "--target",
                    &compiler.host,
                    "--package",
                    package,
                ])
                .args(features);
        }
    }
    let status = command
        .status()
        .context("run the selected Takt generator")?;
    ensure!(status.success(), "Takt generator exited with {status}");
    Ok(())
}

fn generator_package<'a>(metadata: &'a Value, app: &Value) -> Result<&'a Value> {
    let nodes = metadata["resolve"]["nodes"]
        .as_array()
        .context("missing Cargo resolve graph")?;
    let selected = nodes
        .iter()
        .find(|node| node["id"] == app["id"])
        .context("selected canister is missing from the Cargo resolve graph")?;
    let dependencies = selected["deps"]
        .as_array()
        .context("missing canister dependencies")?;
    let packages = metadata["packages"]
        .as_array()
        .context("missing Cargo packages")?;
    let mut matches = packages.iter().filter(|package| {
        package["name"] == GENERATOR
            && dependencies.iter().any(|entry| {
                entry["pkg"] == package["id"]
                    && entry["dep_kinds"]
                        .as_array()
                        .is_some_and(|kinds| kinds.iter().any(|kind| kind["kind"] == "build"))
            })
    });
    let package = matches
        .next()
        .with_context(|| format!("{} has no active {GENERATOR} build dependency", app["name"]))?;
    ensure!(
        matches.next().is_none(),
        "{} selects multiple {GENERATOR} build dependency versions",
        app["name"]
    );
    Ok(package)
}

fn generator(
    compiler: &cargo::Compiler,
    directory: &Path,
    metadata: &Value,
    package: &Value,
    offline: bool,
) -> Result<PathBuf> {
    let manifest = Path::new(
        package["manifest_path"]
            .as_str()
            .context("missing Takt generator manifest path")?,
    )
    .canonicalize()?;
    let target = Path::new(
        metadata["target_directory"]
            .as_str()
            .context("missing Cargo target directory")?,
    )
    .join("cdk-rsx-takt-tools")
    .join(receipt::hash_bytes(manifest.as_os_str().as_encoded_bytes()));
    // Build the binary from Cargo's resolved source. The tool has its own
    // lockfile and target so it never rewrites the app's dependency graph.
    let mut build = compiler.command(&compiler.cargo, directory);
    build
        .arg("build")
        .arg("--manifest-path")
        .arg(manifest)
        .args(["--bin", "takt-gen", "--target", &compiler.host, "--locked"])
        .env("CARGO_TARGET_DIR", target);
    if offline {
        build.arg("--offline");
    }
    let outputs =
        cargo::compile(build, &[]).context("build the locked Takt generator's takt-gen tool")?;
    let mut executables = outputs
        .iter()
        .filter(|row| row["reason"] == "compiler-artifact" && row["target"]["name"] == "takt-gen")
        .filter_map(|row| row["executable"].as_str());
    let tool = executables
        .next()
        .context("Cargo did not report the takt-gen executable")?;
    ensure!(
        executables.next().is_none(),
        "Cargo reported multiple takt-gen executables"
    );
    Ok(PathBuf::from(tool))
}

fn locate_generated(value: &mut Value, base: &Path, remaps: &[(PathBuf, String)]) -> bool {
    match value {
        Value::Object(fields) => {
            let physical = fields
                .get("file_name")
                .and_then(Value::as_str)
                .and_then(|path| {
                    let path = Path::new(path);
                    let physical = base.join(path);
                    std::iter::once(physical)
                        .chain(remaps.iter().rev().filter_map(|(root, logical)| {
                            path.strip_prefix(logical)
                                .ok()
                                .map(|suffix| root.join(suffix))
                        }))
                        .find(|candidate| candidate.with_extension("rs.source.json").is_file())
                });
            let mut found = physical.is_some();
            if let Some(path) = physical.and_then(|path| path.to_str().map(str::to_owned)) {
                fields.insert("file_name".into(), Value::String(path));
            }
            for child in fields.values_mut() {
                found |= locate_generated(child, base, remaps);
            }
            found
        }
        Value::Array(values) => values.iter_mut().fold(false, |found, child| {
            locate_generated(child, base, remaps) | found
        }),
        _ => false,
    }
}

/// The ordinary compiler output remains the fallback if a source map or the
/// selected generator's machine interface is unavailable.
pub(crate) fn render_build_diagnostics(
    compiler: &cargo::Compiler,
    directory: &Path,
    metadata: &Value,
    app: &Value,
    messages: &[Value],
    remaps: &[(PathBuf, String)],
) -> bool {
    let Ok(package) = generator_package(metadata, app) else {
        return false;
    };
    let format = || -> Result<Option<Vec<u8>>> {
        let mut diagnostics: Vec<_> = messages
            .iter()
            .filter(|event| event["reason"] == "compiler-message")
            .cloned()
            .collect();
        let mut found = false;
        for event in &mut diagnostics {
            let base = event["manifest_path"]
                .as_str()
                .and_then(|path| Path::new(path).parent())
                .map_or_else(|| directory.to_owned(), |path| directory.join(path));
            found |= locate_generated(&mut event["message"], &base, remaps);
        }
        if !found {
            return Ok(None);
        }
        let generator = generator(compiler, directory, metadata, package, true)?;
        let mut input = tempfile::tempfile()?;
        for event in &diagnostics {
            serde_json::to_writer(&mut input, event)?;
            input.write_all(b"\n")?;
        }
        input.rewind()?;
        let output = Command::new(generator)
            .arg("format-diagnostics")
            .arg(directory)
            .stdin(Stdio::from(input))
            .output()?;
        Ok(output.status.success().then_some(output.stdout))
    };
    if let Ok(Some(rendered)) = format() {
        eprint!("{}", String::from_utf8_lossy(&rendered));
        return true;
    }
    false
}

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

    #[test]
    fn selects_the_canisters_build_dependency() {
        let metadata = json!({
            "packages": [
                {"id": "generator@1", "name": GENERATOR},
                {"id": "generator@2", "name": GENERATOR}
            ],
            "resolve": {"nodes": [
                {"id": "app1", "deps": [
                    {"pkg": "generator@2", "dep_kinds": [{"kind": "dev"}]},
                    {"pkg": "generator@1", "dep_kinds": [{"kind": "build"}]}
                ]},
                {"id": "app2", "deps": [
                    {"pkg": "generator@2", "dep_kinds": [{"kind": "build"}]}
                ]}
            ]}
        });
        for (app, expected) in [("app1", "generator@1"), ("app2", "generator@2")] {
            assert_eq!(
                generator_package(&metadata, &json!({"id": app})).unwrap()["id"],
                expected
            );
        }
    }

    #[test]
    fn finds_original_takt_map_for_remapped_out_dir_spans() {
        let target = tempfile::tempdir().unwrap();
        let source = target.path().join("flow.rs");
        std::fs::write(source.with_extension("rs.source.json"), b"").unwrap();
        let mut diagnostic = json!({
            "rendered": "original diagnostic\n",
            "spans": [{"file_name": "src/lib.rs", "expansion":
                {"span": {"file_name": "/build/flow.rs", "line_start": 1}}
            }]
        });
        assert!(locate_generated(
            &mut diagnostic,
            Path::new("/workspace"),
            &[(target.path().to_owned(), "/build".into())],
        ));
        assert_eq!(
            diagnostic["spans"][0]["expansion"]["span"]["file_name"],
            source.to_str().unwrap()
        );
        assert_eq!(diagnostic["spans"][0]["file_name"], "src/lib.rs");
        assert_eq!(diagnostic["rendered"], "original diagnostic\n");
    }
}