Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

34.1 KB
Raw Blame
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::Serialize;

use crate::analyze::Status;
use crate::bridge::{MANIFEST, Manifest, SCHEMA};
use crate::front_door::APP_DIR;
use crate::harness::CASES;
use crate::recording;

pub const MAP_FILE: &str = "rust/PORT_MAP.md";

#[derive(Debug, Serialize)]
pub struct PortMap {
    /// Version of this JSON ([`crate::state::schema`]).
    pub schema: String,
    pub root: PathBuf,
    pub ports: Vec<Port>,
    pub not_ported: Vec<Unported>,
    pub glue: Vec<Glue>,
    /// Crate folders under `rust/` whose manifest could not be read. `map` has to skip them, and a
    /// skipped port is not a missing port: the file says so instead of listing the unit as unported.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub crate_errors: Vec<String>,
    /// Units a broken manifest still names: they are covered, so they belong in the total even
    /// though no `Port` could be built for them.
    #[serde(skip_serializing_if = "is_zero")]
    pub covered_by_broken: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub analyze_error: Option<String>,
    /// `analyze`'s warning when the folder has no source file of a supported language.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_source: Option<String>,
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

/// `Kind`'s own serde name (`"c-abi"` for `Kind::CAbi`), matching the manifest and `bridge
/// --kind`, rather than `Debug`'s `"cabi"`.
fn kind_str(kind: crate::bridge::Kind) -> String {
    serde_json::to_value(kind)
        .ok()
        .and_then(|v| v.as_str().map(str::to_string))
        .unwrap_or_else(|| format!("{kind:?}").to_lowercase())
}

#[derive(Debug, Serialize)]
pub struct Port {
    pub unit: String,
    #[serde(rename = "crate")]
    pub crate_dir: String,
    /// The language id (`ts`, `python`, ...); `language_name` is how people write it.
    pub language: String,
    pub language_name: String,
    pub kind: String,
    /// The port version now ([`crate::state::port_version`]); a saved gate or diff with another
    /// `port` was made before the port last changed.
    pub port: String,
    /// The original calls Rust now (`enable` added its block).
    pub enabled: bool,
    pub in_rust: Vec<String>,
    pub kept_in_original: Vec<String>,
    pub cases: usize,
    pub recorded: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_diff: Option<(usize, usize)>,
    /// When that diff ran and on which port version, from `.rust-anything/last-diff.json`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_diff_at: Option<Saved>,
    /// The last `gate`, from `.rust-anything/last-gate.json`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_gate: Option<LastGate>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub changed_upstream: Option<String>,
    /// Why the recording cannot be trusted besides a changed original: its fingerprint file is
    /// missing, recorded cases were edited or removed, a case was dropped. `map --check` fails on
    /// any, as it does on a changed original.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub recording_problems: Vec<String>,
    /// The last `enable`, `disable`, `app wire` or `app lift` of this crate in the audit log.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_change: Option<crate::audit::Entry>,
}

#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)]
pub struct Saved {
    pub at: String,
    pub port: String,
}

#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)]
pub struct LastGate {
    pub passed: bool,
    #[serde(default)]
    pub failed: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub behavior: Option<crate::audit::Count>,
    pub at: String,
    pub port: String,
}

#[derive(Debug, Serialize)]
pub struct Unported {
    pub unit: String,
    pub loc: usize,
    pub readiness: u32,
    pub exports: usize,
    /// `analyze`'s verdict: ready, caution, blocked or keep.
    pub status: Status,
    /// Why `analyze` calls it blocked or keep, when it says.
    pub reasons: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct Glue {
    pub file: String,
    pub falls_back: bool,
}

impl PortMap {
    /// Units with at least one port. `ports` has a row per crate, and one unit can have several
    /// (napi and wasm, or a second `bridge --out`).
    pub fn ported_units(&self) -> usize {
        let mut units: Vec<&str> = self.ports.iter().map(|p| p.unit.as_str()).collect();
        units.sort_unstable();
        units.dedup();
        units.len()
    }

    pub fn changed(&self) -> usize {
        self.ports
            .iter()
            .filter(|p| p.changed_upstream.is_some())
            .count()
    }

    /// Ports whose recording cannot be trusted for another reason than a changed original
    /// (`recording::verify`): `map --check` fails on these too.
    pub fn untrusted(&self) -> usize {
        self.ports
            .iter()
            .filter(|p| !p.recording_problems.is_empty())
            .count()
    }

    /// `analyze` found no source of a supported language, and nothing else would go in the map:
    /// no port, no unit, no whole-app glue and no crate folder that could not be read.
    fn nothing_to_map(&self) -> bool {
        self.no_source.is_some()
            && self.ports.is_empty()
            && self.not_ported.is_empty()
            && self.covered_by_broken == 0
            && self.glue.is_empty()
            && self.crate_errors.is_empty()
            && self.analyze_error.is_none()
    }
}

pub fn map(root: &Path, extra: &[PathBuf]) -> Result<PortMap> {
    // `no folder <root>` for a missing folder, as `analyze` says it. The paths in the map keep
    // `std::fs::canonicalize`'s form, as the `--crates` folders below do.
    crate::walk::resolve_root(root)?;
    let root =
        std::fs::canonicalize(root).with_context(|| format!("mapping {}", root.display()))?;
    // A file is not a repository: `analyze` says so, and a map over a file used to come out empty
    // and exit 0, or fail on the first directory read without naming what it read.
    if !root.is_dir() {
        bail!(
            "{} is a file; `map` takes the folder of a project's source code",
            root.display()
        );
    }
    let mut crate_dirs = manifests(&root);
    for dir in extra {
        let dir =
            std::fs::canonicalize(dir).with_context(|| format!("mapping {}", dir.display()))?;
        if !dir.is_dir() {
            bail!("{} is a file; `--crates` takes folders", dir.display());
        }
        crate_dirs.extend(manifests(&dir));
    }
    crate_dirs.sort();
    crate_dirs.dedup();

    let log = crate::audit::read(&root)
        .map(|log| log.entries)
        .unwrap_or_default();
    let mut ports = Vec::new();
    let mut crate_errors = Vec::new();
    let mut covered_by_broken: Vec<String> = Vec::new();
    for dir in crate_dirs {
        let m = match Manifest::load(&dir) {
            Ok(m) => m,
            Err(e) => {
                // The manifest did not load, but its JSON can still say what it covers and where:
                // a folder that belongs to another repository stays skipped without a word, and a
                // local one still covers its unit, so the unit is not reported as unported.
                let raw: Option<serde_json::Value> = std::fs::read_to_string(dir.join(MANIFEST))
                    .ok()
                    .and_then(|t| serde_json::from_str(&t).ok());
                // Foreign only when the root actually resolves somewhere else: a `root` that does
                // not exist says nothing about ownership, and its unit still belongs here.
                let foreign = raw
                    .as_ref()
                    .and_then(|v| v["root"].as_str())
                    .and_then(|r| std::fs::canonicalize(dir.join(r)).ok())
                    .is_some_and(|resolved| resolved != root);
                let other_schema = raw
                    .as_ref()
                    .and_then(|v| v["schema"].as_str())
                    .is_some_and(|s| s != SCHEMA);
                if foreign || other_schema {
                    continue;
                }
                if let Some(unit) = raw.as_ref().and_then(|v| v["unit"].as_str()) {
                    covered_by_broken.push(unit.to_string());
                }
                // With `/` on every OS, as a readable port's `crate_dir` is.
                let shown = dir
                    .strip_prefix(&root)
                    .unwrap_or(&dir)
                    .to_string_lossy()
                    .replace('\\', "/");
                crate_errors.push(format!("`{shown}`: {e:#}"));
                continue;
            }
        };
        if std::fs::canonicalize(&m.root).ok().as_deref() != Some(root.as_path()) {
            continue;
        }
        ports.push(port(&root, &dir, &m, &log));
    }
    ports.sort_by(|a, b| a.unit.cmp(&b.unit).then(a.crate_dir.cmp(&b.crate_dir)));

    let mut no_source = None;
    let (not_ported, broken_units, analyze_error) = match crate::analyze::analyze(&root) {
        Ok(report) => {
            no_source = report.no_source_warning().map(str::to_string);
            let order = |id: &str| {
                report
                    .start_here
                    .iter()
                    .position(|s| s == id)
                    .unwrap_or(usize::MAX)
            };
            let unported: Vec<_> = report
                .units
                .iter()
                .filter(|u| !ports.iter().any(|p| covers(&p.unit, &u.id, &u.files)))
                .collect();
            // A unit a broken manifest still names is covered, but it is still a unit of this
            // repository: the report counts it, or the summary reads as if it did not exist.
            let (covered, mut units): (Vec<_>, Vec<_>) = unported.into_iter().partition(|u| {
                covered_by_broken
                    .iter()
                    .any(|unit| covers(unit, &u.id, &u.files))
            });
            units.sort_by(|a, b| {
                order(&a.id)
                    .cmp(&order(&b.id))
                    .then(b.priority.cmp(&a.priority))
                    .then(a.id.cmp(&b.id))
            });
            let units = units
                .into_iter()
                .map(|u| Unported {
                    unit: u.id.clone(),
                    loc: u.loc,
                    readiness: u.readiness,
                    exports: u.exports,
                    status: u.status,
                    reasons: u.reasons.clone(),
                })
                .collect();
            (units, covered.len(), None)
        }
        Err(e) => (Vec::new(), 0, Some(format!("{e:#}"))),
    };

    Ok(PortMap {
        schema: crate::state::schema("map"),
        glue: glue(&root),
        root,
        ports,
        not_ported,
        crate_errors,
        covered_by_broken: broken_units,
        analyze_error,
        no_source,
    })
}

fn covers(unit: &str, id: &str, files: &[String]) -> bool {
    unit == id || files.iter().any(|f| f == unit)
}

fn port(root: &Path, dir: &Path, m: &Manifest, log: &[crate::audit::Entry]) -> Port {
    let in_rust = m
        .exports
        .iter()
        .map(|f| f.name.clone())
        .chain(m.classes.iter().map(|c| c.name.clone()))
        .collect();
    let kept_in_original = m.js_only.iter().map(|j| j.name.clone()).collect();
    let cases = std::fs::read_to_string(dir.join(CASES))
        .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
        .unwrap_or(0);
    let crate_dir = dir
        .strip_prefix(root)
        .unwrap_or(dir)
        .to_string_lossy()
        .replace('\\', "/");
    let logged_dir = match dir.strip_prefix(root) {
        Ok(_) => crate_dir.clone(),
        Err(_) => crate::shadow::relative(root, dir),
    };
    Port {
        unit: m.unit.clone(),
        last_change: crate::audit::last_switch(log, &logged_dir, &m.crate_name).cloned(),
        crate_dir,
        language: format!("{:?}", m.language).to_lowercase(),
        language_name: m.language.name().to_string(),
        kind: kind_str(m.kind),
        port: crate::state::port_version(dir),
        enabled: crate::enable::is_supported(m) && crate::enable::is_enabled(dir).unwrap_or(false),
        in_rust,
        kept_in_original,
        cases,
        recorded: dir.join(recording::RECORDED_FROM).is_file(),
        last_diff: recording::last_diff(dir),
        last_diff_at: crate::state::load(dir, crate::state::LAST_DIFF),
        last_gate: crate::state::load(dir, crate::state::LAST_GATE),
        changed_upstream: recording::stale(dir, m),
        recording_problems: recording::verify(
            dir,
            m,
            recording::VerifyOptions {
                per_export: false,
                accept_dropped: crate::gate::tests_baseline(dir).and_then(|b| b.dropped_accepted),
            },
        )
        .problems
        .into_iter()
        .filter(|p| !p.contains("changed since it was recorded"))
        .collect(),
    }
}
fn manifests(dir: &Path) -> Vec<PathBuf> {
    ignore::WalkBuilder::new(dir)
        .hidden(false)
        .filter_entry(|e| {
            !matches!(
                e.file_name().to_str(),
                Some("node_modules" | "target" | ".git" | "vendor" | ".venv" | "venv")
            )
        })
        .build()
        .filter_map(Result::ok)
        .filter(|e| e.file_name() == MANIFEST && e.file_type().is_some_and(|t| t.is_file()))
        .filter_map(|e| e.path().parent().map(Path::to_path_buf))
        .collect()
}

fn glue(root: &Path) -> Vec<Glue> {
    let units = root.join(APP_DIR).join("src/units");
    let Ok(entries) = std::fs::read_dir(&units) else {
        return Vec::new();
    };
    let mut glue: Vec<Glue> = entries
        .filter_map(Result::ok)
        .filter(|e| e.path().extension().is_some_and(|x| x == "rs") && e.file_name() != "mod.rs")
        .map(|e| Glue {
            file: format!("{APP_DIR}/src/units/{}", e.file_name().to_string_lossy()),
            falls_back: std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")),
        })
        .collect();
    glue.sort_by(|a, b| a.file.cmp(&b.file));
    glue
}

/// The status word `analyze` uses, for the table and the list under it.
fn status_name(status: Status) -> &'static str {
    match status {
        Status::Ready => "ready",
        Status::Caution => "caution",
        Status::Blocked => "blocked",
        Status::Keep => "keep",
    }
}

pub fn markdown(map: &PortMap) -> String {
    markdown_with(map, Path::new("."), true)
}

pub fn markdown_with(map: &PortMap, repo: &Path, written: bool) -> String {
    let mut out = String::new();
    let _ = render(&mut out, map, repo, written);
    out
}

fn render(out: &mut String, map: &PortMap, repo: &Path, written: bool) -> std::fmt::Result {
    let name = map.root.file_name().map_or_else(
        || map.root.display().to_string(),
        |n| n.to_string_lossy().into(),
    );
    writeln!(out, "# Port map: {name}\n")?;
    // "0 of 0 units have a Rust port" reads like a finished, empty port, where the path is most
    // likely wrong or `analyze` skipped every file (ignore rules, compiled files only).
    let cli_repo = crate::app::cli_path(repo);
    if map.nothing_to_map() {
        // No offer to write the map either: there is nothing to put in it.
        return writeln!(
            out,
            "Nothing to map under `{cli_repo}`: {}.",
            crate::analyze::NO_SOURCE
        );
    }
    let ported = map.ported_units();
    let total = ported + map.not_ported.len() + map.covered_by_broken;
    if total == 0 && map.analyze_error.is_none() {
        writeln!(
            out,
            "`analyze` found no unit to port under `{cli_repo}`, and no unit has a Rust port: \
             `rust-anything analyze {cli_repo}` says why.\n"
        )?;
    } else {
        write!(
            out,
            "{} of {} {} a Rust port",
            ported,
            if map.analyze_error.is_some() {
                "the".to_string()
            } else {
                total.to_string()
            },
            // One unit reads "1 of 1 unit has", not "units have".
            if total == 1 && map.analyze_error.is_none() {
                "unit has"
            } else {
                "units have"
            }
        )?;
        match map.changed() {
            _ if map.ports.is_empty() => writeln!(out, ".\n")?,
            0 if !map.ports.iter().any(|p| p.recorded) => writeln!(out, "; none recorded yet.\n")?,
            0 => writeln!(out, "; no original changed since it was recorded.\n")?,
            1 => writeln!(
                out,
                "; **1 changed upstream** since it was recorded: re-record it and run `diff`.\n"
            )?,
            n => writeln!(
                out,
                "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
            )?,
        }
    }

    if map.untrusted() > 0 {
        writeln!(
            out,
            "**{} {} cannot be trusted** (fingerprint missing, cases edited, removed or dropped): `rust-anything record` it again.\n",
            map.untrusted(),
            if map.untrusted() == 1 {
                "recording"
            } else {
                "recordings"
            }
        )?;
    }

    if !map.crate_errors.is_empty() {
        writeln!(out, "## Crate folders that could not be read\n")?;
        writeln!(
            out,
            "A folder under `rust/` whose manifest does not parse: fix its `rust-anything.json` and run `map` again. A unit the file still names is not listed as unported, so it does not read as work to do:\n"
        )?;
        for e in &map.crate_errors {
            writeln!(out, "- {e}")?;
        }
        writeln!(out)?;
    }

    writeln!(out, "## Ports\n")?;
    if map.ports.is_empty() {
        writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
    } else {
        writeln!(
            out,
            "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original | Last change |"
        )?;
        writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- | --- |")?;
        for p in &map.ports {
            writeln!(
                out,
                "| `{}` | `{}` | {} | {} | {} | {} | {} | {} |",
                p.unit,
                p.crate_dir,
                list(&p.in_rust),
                list(&p.kept_in_original),
                p.cases,
                p.last_diff
                    .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
                if !p.recording_problems.is_empty() {
                    format!(
                        "**cannot be trusted**: `rust-anything record {}`",
                        crate::app::cli_path(&p.crate_dir)
                    )
                } else if !p.recorded {
                    "not recorded".into()
                } else if p.changed_upstream.is_some() {
                    format!(
                        "**changed**: `rust-anything record {}`",
                        crate::app::cli_path(&p.crate_dir)
                    )
                } else {
                    "unchanged".into()
                },
                p.last_change.as_ref().map_or("none".into(), |e| format!(
                    "{}: {}",
                    e.time.get(..10).unwrap_or(&e.time),
                    crate::audit::summary(e)
                ))
            )?;
        }
        writeln!(out)?;
    }

    if !map.glue.is_empty() {
        writeln!(out, "## Whole app\n")?;
        writeln!(out, "| Glue | Runs |")?;
        writeln!(out, "| --- | --- |")?;
        for g in &map.glue {
            writeln!(
                out,
                "| `{}` | {} |",
                g.file,
                if g.falls_back {
                    "Rust, handing some cases to the original"
                } else {
                    "Rust only"
                }
            )?;
        }
        writeln!(out)?;
    }

    writeln!(out, "## Not ported yet\n")?;
    if let Some(e) = &map.analyze_error {
        writeln!(out, "`analyze` could not list the units: {e}\n")?;
    } else if total == 0 {
        writeln!(out, "No unit to port was found.\n")?;
    } else if map.not_ported.is_empty() {
        writeln!(out, "Every unit `analyze` found has a port.\n")?;
    } else {
        writeln!(out, "In the order `analyze` suggests.\n")?;
        writeln!(out, "| Unit | Status | Lines | Exports | Readiness |")?;
        writeln!(out, "| --- | --- | ---: | ---: | ---: |")?;
        for u in &map.not_ported {
            writeln!(
                out,
                "| `{}` | {} | {} | {} | {} |",
                u.unit,
                status_name(u.status),
                u.loc,
                u.exports,
                u.readiness
            )?;
        }
        writeln!(out)?;
        // A unit that stays in the original is not work to do: say so in its own short list,
        // with the reason `analyze` gave, or the table above reads as remaining work.
        let left: Vec<&Unported> = map
            .not_ported
            .iter()
            .filter(|u| !matches!(u.status, Status::Keep | Status::Blocked))
            .collect();
        let stays: Vec<&Unported> = map
            .not_ported
            .iter()
            .filter(|u| matches!(u.status, Status::Keep | Status::Blocked))
            .collect();
        if !stays.is_empty() {
            writeln!(
                out,
                "{} of these {} no port on purpose ({} blocked, {} kept in the original), so {} {} left to port:\n",
                stays.len(),
                if stays.len() == 1 {
                    "unit has"
                } else {
                    "units have"
                },
                map.not_ported
                    .iter()
                    .filter(|u| matches!(u.status, Status::Blocked))
                    .count(),
                map.not_ported
                    .iter()
                    .filter(|u| matches!(u.status, Status::Keep))
                    .count(),
                left.len(),
                if left.len() == 1 {
                    "unit is"
                } else {
                    "units are"
                },
            )?;
            for u in stays {
                let why = if u.reasons.is_empty() {
                    String::new()
                } else {
                    let reasons: Vec<&str> =
                        u.reasons.iter().map(|n| n.trim_end_matches('.')).collect();
                    format!(", {}", reasons.join("; "))
                };
                writeln!(out, "- `{}`: {}{why}", u.unit, status_name(u.status))?;
            }
            writeln!(out)?;
        }
    }
    let cmd = format!(
        "rust-anything map{} --write",
        crate::app::cli_root_arg(repo)
    );
    if written {
        writeln!(
            out,
            "Regenerate with `{cmd}`. Commit this file: when the original changes \
             upstream, the next map marks every port whose recording it outdated."
        )
    } else {
        writeln!(
            out,
            "Write `{MAP_FILE}` with `{cmd}`: when the original changes \
             upstream, the next map marks every port whose recording it outdated."
        )
    }
}

fn list(items: &[String]) -> String {
    if items.is_empty() {
        "-".into()
    } else {
        items
            .iter()
            .map(|i| format!("`{i}`"))
            .collect::<Vec<_>>()
            .join(", ")
    }
}

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

    fn empty_map() -> PortMap {
        PortMap {
            schema: crate::state::schema("map"),
            root: PathBuf::from("empty"),
            ports: Vec::new(),
            not_ported: Vec::new(),
            glue: Vec::new(),
            crate_errors: Vec::new(),
            covered_by_broken: 0,
            analyze_error: None,
            no_source: None,
        }
    }

    #[test]
    fn a_unit_that_stays_in_the_original_is_not_counted_as_work_to_do() {
        // `analyze` says why a unit is blocked or kept; without that column and the list under the
        // table, `map` reads as if every unported unit were remaining work.
        let mut map = empty_map();
        map.not_ported = vec![
            Unported {
                unit: "src/util.ts".into(),
                loc: 19,
                readiness: 94,
                exports: 3,
                status: crate::analyze::Status::Ready,
                reasons: Vec::new(),
            },
            Unported {
                unit: "src/view/".into(),
                loc: 3,
                readiness: 100,
                exports: 0,
                status: crate::analyze::Status::Keep,
                reasons: vec!["UI code: keep in the original language.".into()],
            },
            Unported {
                unit: "src/svelte.ts".into(),
                loc: 4,
                readiness: 92,
                exports: 0,
                status: crate::analyze::Status::Blocked,
                reasons: vec!["`svelte` has no Rust equivalent.".into()],
            },
        ];
        let text = markdown(&map);
        assert!(
            text.contains("| Unit | Status | Lines | Exports | Readiness |"),
            "{text}"
        );
        assert!(text.contains("| `src/util.ts` | ready |"), "{text}");
        assert!(text.contains("| `src/view/` | keep |"), "{text}");
        assert!(text.contains("| `src/svelte.ts` | blocked |"), "{text}");
        // The two that stay are named with their reason, and only the ready one counts as work.
        assert!(
            text.contains("2 of these units have no port on purpose (1 blocked, 1 kept in the original), so 1 unit is left to port:"),
            "{text}"
        );
        assert!(
            text.contains("- `src/svelte.ts`: blocked, `svelte` has no Rust equivalent\n"),
            "{text}"
        );
        assert!(
            text.contains("- `src/view/`: keep, UI code: keep in the original language\n"),
            "{text}"
        );
    }

    #[test]
    fn dropped_cases_a_passing_gate_accepted_do_not_make_the_recording_a_problem() {
        let dir = crate::app::temp_dir("map-accepted-dropped").unwrap();
        std::fs::write(
            dir.join("lib.ts"),
            "export function f(x: number) { return x }\n",
        )
        .unwrap();
        std::fs::write(dir.join(CASES), "{\"fn\":\"f\",\"args\":[1],\"ok\":1}\n").unwrap();
        let m: Manifest = serde_json::from_value(serde_json::json!({
            "schema": crate::bridge::SCHEMA,
            "root": dir,
            "unit": "lib.ts",
            "crate_name": "demo",
            "kind": "napi",
            "exports": [{"name": "f", "file": "lib.ts", "line": 1, "params": [], "returns": "number", "is_async": false}],
        }))
        .unwrap();
        let fingerprint = recording::fingerprint(&m).unwrap();
        recording::save_recorded_from(
            &dir,
            &m,
            &fingerprint,
            None,
            serde_json::json!({"generated": 3, "dropped": 2}),
        )
        .unwrap();
        let before = port(&dir, &dir, &m, &[]).recording_problems;
        std::fs::create_dir_all(dir.join(".rust-anything")).unwrap();
        std::fs::write(
            dir.join(".rust-anything/tests.json"),
            "{\"tests\":0,\"asserts\":0,\"ignored\":0,\"should_panic\":0,\"dropped_accepted\":2}\n",
        )
        .unwrap();
        let after = port(&dir, &dir, &m, &[]).recording_problems;
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(
            before.iter().any(|p| p.contains("could not record 2")),
            "{before:?}"
        );
        assert!(after.is_empty(), "{after:?}");
    }

    #[test]
    fn an_empty_map_says_no_unit_was_found() {
        // Issue #1444: no "0 of 0" count; `analyze` is the one that says why.
        let text = markdown(&empty_map());
        assert!(
            text.contains(
                "`analyze` found no unit to port under `.`, and no unit has a Rust port: \
                 `rust-anything analyze .` says why."
            ),
            "{text}"
        );
        assert!(text.contains("No unit to port was found."), "{text}");
        assert!(!text.contains("0 of 0"), "{text}");
        assert!(!text.contains("nothing to map"), "{text}");
        assert!(
            !text.contains("Every unit `analyze` found has a port."),
            "{text}"
        );
    }

    fn no_source_map() -> PortMap {
        PortMap {
            no_source: Some(format!("{} under x", crate::analyze::NO_SOURCE)),
            ..empty_map()
        }
    }

    fn unit(id: &str) -> Unported {
        Unported {
            unit: id.into(),
            loc: 19,
            readiness: 94,
            exports: 3,
            status: crate::analyze::Status::Ready,
            reasons: Vec::new(),
        }
    }

    #[test]
    fn a_folder_with_no_source_says_there_is_nothing_to_map() {
        let dir = std::env::temp_dir().join(format!("ra-map-no-source-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("README.md"), "# docs only\n").unwrap();
        let map = super::map(&dir, &[]).unwrap();
        let text = markdown_with(&map, Path::new("docs"), false);
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(
            map.no_source
                .as_deref()
                .is_some_and(|w| w.starts_with(crate::analyze::NO_SOURCE)),
            "{:?}",
            map.no_source
        );
        assert!(
            text.contains(&format!(
                "Nothing to map under `docs`: {}.",
                crate::analyze::NO_SOURCE
            )),
            "{text}"
        );
        assert!(!text.contains("0 of 0"), "{text}");
        assert!(!text.contains("--write"), "{text}");
        assert!(!text.contains("## Ports"), "{text}");
    }

    #[test]
    fn a_folder_whose_source_is_all_ignored_is_not_called_empty() {
        // `analyze` warns that ignore rules hid the source, not that there is none: the map must
        // not say there is nothing to map.
        let dir = std::env::temp_dir().join(format!("ra-map-ignored-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join(".ignore"), "src/\n").unwrap();
        std::fs::write(dir.join("src/a.ts"), "export const a = 1;\n").unwrap();
        let map = super::map(&dir, &[]).unwrap();
        let text = markdown_with(&map, Path::new("app"), false);
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(map.no_source.is_none(), "{:?}", map.no_source);
        assert!(!text.contains("nothing to map"), "{text}");
        assert!(
            text.contains("`rust-anything analyze app` says why"),
            "{text}"
        );
        assert!(!text.contains("0 of 0"), "{text}");
    }

    #[test]
    fn whatever_else_is_in_the_map_keeps_it_from_reading_as_empty() {
        // Each of these makes a map with no source still worth reading.
        let glue = PortMap {
            glue: vec![Glue {
                file: "rust/app/src/units/foo.rs".into(),
                falls_back: true,
            }],
            ..no_source_map()
        };
        let broken = PortMap {
            crate_errors: vec!["rust/x: rust-anything.json does not parse".into()],
            ..no_source_map()
        };
        let covered = PortMap {
            covered_by_broken: 1,
            ..no_source_map()
        };
        let failed = PortMap {
            analyze_error: Some("boom".into()),
            ..no_source_map()
        };
        let unported = PortMap {
            not_ported: vec![unit("src/util.ts")],
            ..no_source_map()
        };
        // A port whose original is gone: its crate still says what it ports.
        let ported = PortMap {
            ports: vec![Port {
                unit: "src/util.ts".into(),
                crate_dir: "rust/util-rs".into(),
                language: "ts".into(),
                language_name: "TypeScript/JavaScript".into(),
                kind: "napi".into(),
                port: String::new(),
                enabled: false,
                in_rust: Vec::new(),
                kept_in_original: Vec::new(),
                cases: 0,
                recorded: false,
                last_diff: None,
                last_diff_at: None,
                last_gate: None,
                changed_upstream: None,
                recording_problems: Vec::new(),
                last_change: None,
            }],
            ..no_source_map()
        };
        for (map, expect) in [
            (ported, "1 of 1 unit has a Rust port"),
            (glue, "rust/app/src/units/foo.rs"),
            (broken, "## Crate folders that could not be read"),
            (covered, "0 of 1 unit has a Rust port."),
            (failed, "`analyze` could not list the units: boom"),
            (unported, "0 of 1 unit has a Rust port."),
        ] {
            let text = markdown(&map);
            assert!(text.contains(expect), "{expect}: {text}");
            assert!(!text.contains("Nothing to map"), "{expect}: {text}");
        }
        assert!(markdown(&no_source_map()).contains("Nothing to map under `.`"));
    }

    #[test]
    fn footer_names_passed_root_and_omits_commit_claim_on_stdout() {
        let map = empty_map();
        let stdout_footer = markdown_with(&map, Path::new("tests/fixtures/mini"), false);
        assert!(
            stdout_footer.contains("`rust-anything map tests/fixtures/mini --write`"),
            "{stdout_footer}"
        );
        assert!(
            !stdout_footer.contains("Commit this file"),
            "{stdout_footer}"
        );

        let written_footer = markdown_with(&map, Path::new("my repo"), true);
        // Single quotes for POSIX shells, double quotes on Windows, where cmd takes no others.
        let quoted = if cfg!(windows) && std::env::var_os("MSYSTEM").is_none() {
            "\"my repo\""
        } else {
            "'my repo'"
        };
        assert!(
            written_footer.contains(&format!(
                "Regenerate with `rust-anything map {quoted} --write`. Commit this file:"
            )),
            "{written_footer}"
        );
    }
}