Skip to main content

rust_anything/
port_map.rs

1use std::fmt::Write as _;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result};
5use serde::Serialize;
6
7use crate::bridge::{MANIFEST, Manifest, SCHEMA};
8use crate::front_door::APP_DIR;
9use crate::harness::CASES;
10use crate::recording;
11
12pub const MAP_FILE: &str = "rust/PORT_MAP.md";
13
14#[derive(Debug, Serialize)]
15pub struct PortMap {
16    pub root: PathBuf,
17    pub ports: Vec<Port>,
18    pub not_ported: Vec<Unported>,
19    pub glue: Vec<Glue>,
20    /// Crate folders under `rust/` whose manifest could not be read. `map` has to skip them, and a
21    /// skipped port is not a missing port: the file says so instead of listing the unit as unported.
22    #[serde(skip_serializing_if = "Vec::is_empty")]
23    pub crate_errors: Vec<String>,
24    /// Units a broken manifest still names: they are covered, so they belong in the total even
25    /// though no `Port` could be built for them.
26    #[serde(skip_serializing_if = "is_zero")]
27    pub covered_by_broken: usize,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub analyze_error: Option<String>,
30}
31
32fn is_zero(n: &usize) -> bool {
33    *n == 0
34}
35
36#[derive(Debug, Serialize)]
37pub struct Port {
38    pub unit: String,
39    #[serde(rename = "crate")]
40    pub crate_dir: String,
41    pub language: String,
42    pub kind: String,
43    pub in_rust: Vec<String>,
44    pub kept_in_original: Vec<String>,
45    pub cases: usize,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub last_diff: Option<(usize, usize)>,
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub changed_upstream: Option<String>,
50}
51
52#[derive(Debug, Serialize)]
53pub struct Unported {
54    pub unit: String,
55    pub loc: usize,
56    pub readiness: u32,
57    pub exports: usize,
58}
59
60#[derive(Debug, Serialize)]
61pub struct Glue {
62    pub file: String,
63    pub falls_back: bool,
64}
65
66impl PortMap {
67    pub fn changed(&self) -> usize {
68        self.ports
69            .iter()
70            .filter(|p| p.changed_upstream.is_some())
71            .count()
72    }
73}
74
75pub fn map(root: &Path, extra: &[PathBuf]) -> Result<PortMap> {
76    let root =
77        std::fs::canonicalize(root).with_context(|| format!("mapping {}", root.display()))?;
78    let mut crate_dirs = manifests(&root);
79    for dir in extra {
80        let dir =
81            std::fs::canonicalize(dir).with_context(|| format!("mapping {}", dir.display()))?;
82        crate_dirs.extend(manifests(&dir));
83    }
84    crate_dirs.sort();
85    crate_dirs.dedup();
86
87    let mut ports = Vec::new();
88    let mut crate_errors = Vec::new();
89    let mut covered_by_broken: Vec<String> = Vec::new();
90    for dir in crate_dirs {
91        let m = match Manifest::load(&dir) {
92            Ok(m) => m,
93            Err(e) => {
94                // The manifest did not load, but its JSON can still say what it covers and where:
95                // a folder that belongs to another repository stays skipped without a word, and a
96                // local one still covers its unit, so the unit is not reported as unported.
97                let raw: Option<serde_json::Value> = std::fs::read_to_string(dir.join(MANIFEST))
98                    .ok()
99                    .and_then(|t| serde_json::from_str(&t).ok());
100                // Foreign only when the root actually resolves somewhere else: a `root` that does
101                // not exist says nothing about ownership, and its unit still belongs here.
102                let foreign = raw
103                    .as_ref()
104                    .and_then(|v| v["root"].as_str())
105                    .and_then(|r| std::fs::canonicalize(dir.join(r)).ok())
106                    .is_some_and(|resolved| resolved != root);
107                let other_schema = raw
108                    .as_ref()
109                    .and_then(|v| v["schema"].as_str())
110                    .is_some_and(|s| s != SCHEMA);
111                if foreign || other_schema {
112                    continue;
113                }
114                if let Some(unit) = raw.as_ref().and_then(|v| v["unit"].as_str()) {
115                    covered_by_broken.push(unit.to_string());
116                }
117                let shown = dir
118                    .strip_prefix(&root)
119                    .unwrap_or(&dir)
120                    .display()
121                    .to_string();
122                crate_errors.push(format!("`{shown}`: {e:#}"));
123                continue;
124            }
125        };
126        if std::fs::canonicalize(&m.root).ok().as_deref() != Some(root.as_path()) {
127            continue;
128        }
129        ports.push(port(&root, &dir, &m));
130    }
131    ports.sort_by(|a, b| a.unit.cmp(&b.unit).then(a.crate_dir.cmp(&b.crate_dir)));
132
133    let (not_ported, broken_units, analyze_error) = match crate::analyze::analyze(&root) {
134        Ok(report) => {
135            let order = |id: &str| {
136                report
137                    .start_here
138                    .iter()
139                    .position(|s| s == id)
140                    .unwrap_or(usize::MAX)
141            };
142            let unported: Vec<_> = report
143                .units
144                .iter()
145                .filter(|u| !ports.iter().any(|p| covers(&p.unit, &u.id, &u.files)))
146                .collect();
147            // A unit a broken manifest still names is covered, but it is still a unit of this
148            // repository: the report counts it, or the summary reads as if it did not exist.
149            let (covered, mut units): (Vec<_>, Vec<_>) = unported.into_iter().partition(|u| {
150                covered_by_broken
151                    .iter()
152                    .any(|unit| covers(unit, &u.id, &u.files))
153            });
154            units.sort_by(|a, b| {
155                order(&a.id)
156                    .cmp(&order(&b.id))
157                    .then(b.priority.cmp(&a.priority))
158                    .then(a.id.cmp(&b.id))
159            });
160            let units = units
161                .into_iter()
162                .map(|u| Unported {
163                    unit: u.id.clone(),
164                    loc: u.loc,
165                    readiness: u.readiness,
166                    exports: u.exports,
167                })
168                .collect();
169            (units, covered.len(), None)
170        }
171        Err(e) => (Vec::new(), 0, Some(format!("{e:#}"))),
172    };
173
174    Ok(PortMap {
175        glue: glue(&root),
176        root,
177        ports,
178        not_ported,
179        crate_errors,
180        covered_by_broken: broken_units,
181        analyze_error,
182    })
183}
184
185fn covers(unit: &str, id: &str, files: &[String]) -> bool {
186    unit == id || files.iter().any(|f| f == unit)
187}
188
189fn port(root: &Path, dir: &Path, m: &Manifest) -> Port {
190    let in_rust = m
191        .exports
192        .iter()
193        .map(|f| f.name.clone())
194        .chain(m.classes.iter().map(|c| c.name.clone()))
195        .collect();
196    let kept_in_original = m.js_only.iter().map(|j| j.name.clone()).collect();
197    let cases = std::fs::read_to_string(dir.join(CASES))
198        .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
199        .unwrap_or(0);
200    Port {
201        unit: m.unit.clone(),
202        crate_dir: dir
203            .strip_prefix(root)
204            .unwrap_or(dir)
205            .to_string_lossy()
206            .replace('\\', "/"),
207        language: format!("{:?}", m.language).to_lowercase(),
208        kind: format!("{:?}", m.kind).to_lowercase(),
209        in_rust,
210        kept_in_original,
211        cases,
212        last_diff: recording::last_diff(dir),
213        changed_upstream: recording::stale(dir, m),
214    }
215}
216fn manifests(dir: &Path) -> Vec<PathBuf> {
217    ignore::WalkBuilder::new(dir)
218        .hidden(false)
219        .filter_entry(|e| {
220            !matches!(
221                e.file_name().to_str(),
222                Some("node_modules" | "target" | ".git" | "vendor" | ".venv" | "venv")
223            )
224        })
225        .build()
226        .filter_map(Result::ok)
227        .filter(|e| e.file_name() == MANIFEST && e.file_type().is_some_and(|t| t.is_file()))
228        .filter_map(|e| e.path().parent().map(Path::to_path_buf))
229        .collect()
230}
231
232fn glue(root: &Path) -> Vec<Glue> {
233    let units = root.join(APP_DIR).join("src/units");
234    let Ok(entries) = std::fs::read_dir(&units) else {
235        return Vec::new();
236    };
237    let mut glue: Vec<Glue> = entries
238        .filter_map(Result::ok)
239        .filter(|e| e.path().extension().is_some_and(|x| x == "rs") && e.file_name() != "mod.rs")
240        .map(|e| Glue {
241            file: format!("{APP_DIR}/src/units/{}", e.file_name().to_string_lossy()),
242            falls_back: std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")),
243        })
244        .collect();
245    glue.sort_by(|a, b| a.file.cmp(&b.file));
246    glue
247}
248
249pub fn markdown(map: &PortMap) -> String {
250    let mut out = String::new();
251    let _ = render(&mut out, map);
252    out
253}
254
255fn render(out: &mut String, map: &PortMap) -> std::fmt::Result {
256    let name = map.root.file_name().map_or_else(
257        || map.root.display().to_string(),
258        |n| n.to_string_lossy().into(),
259    );
260    writeln!(out, "# Port map: {name}\n")?;
261    let total = map.ports.len() + map.not_ported.len() + map.covered_by_broken;
262    write!(
263        out,
264        "{} of {} units have a Rust port",
265        map.ports.len(),
266        if map.analyze_error.is_some() {
267            "the".to_string()
268        } else {
269            total.to_string()
270        }
271    )?;
272    match map.changed() {
273        _ if map.ports.is_empty() => writeln!(out, ".\n")?,
274        0 => writeln!(out, "; no original changed since it was recorded.\n")?,
275        n => writeln!(
276            out,
277            "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
278        )?,
279    }
280
281    if !map.crate_errors.is_empty() {
282        writeln!(out, "## Crate folders that could not be read\n")?;
283        writeln!(
284            out,
285            "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"
286        )?;
287        for e in &map.crate_errors {
288            writeln!(out, "- {e}")?;
289        }
290        writeln!(out)?;
291    }
292
293    writeln!(out, "## Ports\n")?;
294    if map.ports.is_empty() {
295        writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
296    } else {
297        writeln!(
298            out,
299            "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original |"
300        )?;
301        writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- |")?;
302        for p in &map.ports {
303            writeln!(
304                out,
305                "| `{}` | `{}` | {} | {} | {} | {} | {} |",
306                p.unit,
307                p.crate_dir,
308                list(&p.in_rust),
309                list(&p.kept_in_original),
310                p.cases,
311                p.last_diff
312                    .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
313                if p.changed_upstream.is_some() {
314                    format!("**changed**: `rust-anything record {}`", p.crate_dir)
315                } else {
316                    "unchanged".into()
317                }
318            )?;
319        }
320        writeln!(out)?;
321    }
322
323    if !map.glue.is_empty() {
324        writeln!(out, "## Whole app\n")?;
325        writeln!(out, "| Glue | Runs |")?;
326        writeln!(out, "| --- | --- |")?;
327        for g in &map.glue {
328            writeln!(
329                out,
330                "| `{}` | {} |",
331                g.file,
332                if g.falls_back {
333                    "Rust, handing some cases to the original"
334                } else {
335                    "Rust only"
336                }
337            )?;
338        }
339        writeln!(out)?;
340    }
341
342    writeln!(out, "## Not ported yet\n")?;
343    if let Some(e) = &map.analyze_error {
344        writeln!(out, "`analyze` could not list the units: {e}\n")?;
345    } else if map.not_ported.is_empty() {
346        writeln!(out, "Every unit `analyze` found has a port.\n")?;
347    } else {
348        writeln!(out, "In the order `analyze` suggests.\n")?;
349        writeln!(out, "| Unit | Lines | Exports | Readiness |")?;
350        writeln!(out, "| --- | ---: | ---: | ---: |")?;
351        for u in &map.not_ported {
352            writeln!(
353                out,
354                "| `{}` | {} | {} | {} |",
355                u.unit, u.loc, u.exports, u.readiness
356            )?;
357        }
358        writeln!(out)?;
359    }
360    writeln!(
361        out,
362        "Regenerate with `rust-anything map --write`. Commit this file: when the original changes \
363         upstream, the next map marks every port whose recording it outdated."
364    )
365}
366
367fn list(items: &[String]) -> String {
368    if items.is_empty() {
369        "-".into()
370    } else {
371        items
372            .iter()
373            .map(|i| format!("`{i}`"))
374            .collect::<Vec<_>>()
375            .join(", ")
376    }
377}