Skip to main content

rust_anything/
port_map.rs

1use std::fmt::Write as _;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result, bail};
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    // A file is not a repository: `analyze` says so, and a map over a file used to come out empty
79    // and exit 0, or fail on the first directory read without naming what it read.
80    if !root.is_dir() {
81        bail!(
82            "{} is a file; `map` takes the folder of a project's source code",
83            root.display()
84        );
85    }
86    let mut crate_dirs = manifests(&root);
87    for dir in extra {
88        let dir =
89            std::fs::canonicalize(dir).with_context(|| format!("mapping {}", dir.display()))?;
90        if !dir.is_dir() {
91            bail!("{} is a file; `--crates` takes folders", dir.display());
92        }
93        crate_dirs.extend(manifests(&dir));
94    }
95    crate_dirs.sort();
96    crate_dirs.dedup();
97
98    let mut ports = Vec::new();
99    let mut crate_errors = Vec::new();
100    let mut covered_by_broken: Vec<String> = Vec::new();
101    for dir in crate_dirs {
102        let m = match Manifest::load(&dir) {
103            Ok(m) => m,
104            Err(e) => {
105                // The manifest did not load, but its JSON can still say what it covers and where:
106                // a folder that belongs to another repository stays skipped without a word, and a
107                // local one still covers its unit, so the unit is not reported as unported.
108                let raw: Option<serde_json::Value> = std::fs::read_to_string(dir.join(MANIFEST))
109                    .ok()
110                    .and_then(|t| serde_json::from_str(&t).ok());
111                // Foreign only when the root actually resolves somewhere else: a `root` that does
112                // not exist says nothing about ownership, and its unit still belongs here.
113                let foreign = raw
114                    .as_ref()
115                    .and_then(|v| v["root"].as_str())
116                    .and_then(|r| std::fs::canonicalize(dir.join(r)).ok())
117                    .is_some_and(|resolved| resolved != root);
118                let other_schema = raw
119                    .as_ref()
120                    .and_then(|v| v["schema"].as_str())
121                    .is_some_and(|s| s != SCHEMA);
122                if foreign || other_schema {
123                    continue;
124                }
125                if let Some(unit) = raw.as_ref().and_then(|v| v["unit"].as_str()) {
126                    covered_by_broken.push(unit.to_string());
127                }
128                let shown = dir
129                    .strip_prefix(&root)
130                    .unwrap_or(&dir)
131                    .display()
132                    .to_string();
133                crate_errors.push(format!("`{shown}`: {e:#}"));
134                continue;
135            }
136        };
137        if std::fs::canonicalize(&m.root).ok().as_deref() != Some(root.as_path()) {
138            continue;
139        }
140        ports.push(port(&root, &dir, &m));
141    }
142    ports.sort_by(|a, b| a.unit.cmp(&b.unit).then(a.crate_dir.cmp(&b.crate_dir)));
143
144    let (not_ported, broken_units, analyze_error) = match crate::analyze::analyze(&root) {
145        Ok(report) => {
146            let order = |id: &str| {
147                report
148                    .start_here
149                    .iter()
150                    .position(|s| s == id)
151                    .unwrap_or(usize::MAX)
152            };
153            let unported: Vec<_> = report
154                .units
155                .iter()
156                .filter(|u| !ports.iter().any(|p| covers(&p.unit, &u.id, &u.files)))
157                .collect();
158            // A unit a broken manifest still names is covered, but it is still a unit of this
159            // repository: the report counts it, or the summary reads as if it did not exist.
160            let (covered, mut units): (Vec<_>, Vec<_>) = unported.into_iter().partition(|u| {
161                covered_by_broken
162                    .iter()
163                    .any(|unit| covers(unit, &u.id, &u.files))
164            });
165            units.sort_by(|a, b| {
166                order(&a.id)
167                    .cmp(&order(&b.id))
168                    .then(b.priority.cmp(&a.priority))
169                    .then(a.id.cmp(&b.id))
170            });
171            let units = units
172                .into_iter()
173                .map(|u| Unported {
174                    unit: u.id.clone(),
175                    loc: u.loc,
176                    readiness: u.readiness,
177                    exports: u.exports,
178                })
179                .collect();
180            (units, covered.len(), None)
181        }
182        Err(e) => (Vec::new(), 0, Some(format!("{e:#}"))),
183    };
184
185    Ok(PortMap {
186        glue: glue(&root),
187        root,
188        ports,
189        not_ported,
190        crate_errors,
191        covered_by_broken: broken_units,
192        analyze_error,
193    })
194}
195
196fn covers(unit: &str, id: &str, files: &[String]) -> bool {
197    unit == id || files.iter().any(|f| f == unit)
198}
199
200fn port(root: &Path, dir: &Path, m: &Manifest) -> Port {
201    let in_rust = m
202        .exports
203        .iter()
204        .map(|f| f.name.clone())
205        .chain(m.classes.iter().map(|c| c.name.clone()))
206        .collect();
207    let kept_in_original = m.js_only.iter().map(|j| j.name.clone()).collect();
208    let cases = std::fs::read_to_string(dir.join(CASES))
209        .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
210        .unwrap_or(0);
211    Port {
212        unit: m.unit.clone(),
213        crate_dir: dir
214            .strip_prefix(root)
215            .unwrap_or(dir)
216            .to_string_lossy()
217            .replace('\\', "/"),
218        language: format!("{:?}", m.language).to_lowercase(),
219        kind: format!("{:?}", m.kind).to_lowercase(),
220        in_rust,
221        kept_in_original,
222        cases,
223        last_diff: recording::last_diff(dir),
224        changed_upstream: recording::stale(dir, m),
225    }
226}
227fn manifests(dir: &Path) -> Vec<PathBuf> {
228    ignore::WalkBuilder::new(dir)
229        .hidden(false)
230        .filter_entry(|e| {
231            !matches!(
232                e.file_name().to_str(),
233                Some("node_modules" | "target" | ".git" | "vendor" | ".venv" | "venv")
234            )
235        })
236        .build()
237        .filter_map(Result::ok)
238        .filter(|e| e.file_name() == MANIFEST && e.file_type().is_some_and(|t| t.is_file()))
239        .filter_map(|e| e.path().parent().map(Path::to_path_buf))
240        .collect()
241}
242
243fn glue(root: &Path) -> Vec<Glue> {
244    let units = root.join(APP_DIR).join("src/units");
245    let Ok(entries) = std::fs::read_dir(&units) else {
246        return Vec::new();
247    };
248    let mut glue: Vec<Glue> = entries
249        .filter_map(Result::ok)
250        .filter(|e| e.path().extension().is_some_and(|x| x == "rs") && e.file_name() != "mod.rs")
251        .map(|e| Glue {
252            file: format!("{APP_DIR}/src/units/{}", e.file_name().to_string_lossy()),
253            falls_back: std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")),
254        })
255        .collect();
256    glue.sort_by(|a, b| a.file.cmp(&b.file));
257    glue
258}
259
260pub fn markdown(map: &PortMap) -> String {
261    let mut out = String::new();
262    let _ = render(&mut out, map);
263    out
264}
265
266fn render(out: &mut String, map: &PortMap) -> std::fmt::Result {
267    let name = map.root.file_name().map_or_else(
268        || map.root.display().to_string(),
269        |n| n.to_string_lossy().into(),
270    );
271    writeln!(out, "# Port map: {name}\n")?;
272    let total = map.ports.len() + map.not_ported.len() + map.covered_by_broken;
273    write!(
274        out,
275        "{} of {} {} a Rust port",
276        map.ports.len(),
277        if map.analyze_error.is_some() {
278            "the".to_string()
279        } else {
280            total.to_string()
281        },
282        // One unit reads "1 of 1 unit has", not "units have".
283        if total == 1 && map.analyze_error.is_none() {
284            "unit has"
285        } else {
286            "units have"
287        }
288    )?;
289    match map.changed() {
290        _ if map.ports.is_empty() => writeln!(out, ".\n")?,
291        0 => writeln!(out, "; no original changed since it was recorded.\n")?,
292        n => writeln!(
293            out,
294            "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
295        )?,
296    }
297
298    if !map.crate_errors.is_empty() {
299        writeln!(out, "## Crate folders that could not be read\n")?;
300        writeln!(
301            out,
302            "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"
303        )?;
304        for e in &map.crate_errors {
305            writeln!(out, "- {e}")?;
306        }
307        writeln!(out)?;
308    }
309
310    writeln!(out, "## Ports\n")?;
311    if map.ports.is_empty() {
312        writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
313    } else {
314        writeln!(
315            out,
316            "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original |"
317        )?;
318        writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- |")?;
319        for p in &map.ports {
320            writeln!(
321                out,
322                "| `{}` | `{}` | {} | {} | {} | {} | {} |",
323                p.unit,
324                p.crate_dir,
325                list(&p.in_rust),
326                list(&p.kept_in_original),
327                p.cases,
328                p.last_diff
329                    .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
330                if p.changed_upstream.is_some() {
331                    format!("**changed**: `rust-anything record {}`", p.crate_dir)
332                } else {
333                    "unchanged".into()
334                }
335            )?;
336        }
337        writeln!(out)?;
338    }
339
340    if !map.glue.is_empty() {
341        writeln!(out, "## Whole app\n")?;
342        writeln!(out, "| Glue | Runs |")?;
343        writeln!(out, "| --- | --- |")?;
344        for g in &map.glue {
345            writeln!(
346                out,
347                "| `{}` | {} |",
348                g.file,
349                if g.falls_back {
350                    "Rust, handing some cases to the original"
351                } else {
352                    "Rust only"
353                }
354            )?;
355        }
356        writeln!(out)?;
357    }
358
359    writeln!(out, "## Not ported yet\n")?;
360    if let Some(e) = &map.analyze_error {
361        writeln!(out, "`analyze` could not list the units: {e}\n")?;
362    } else if total == 0 {
363        writeln!(out, "No unit to port was found.\n")?;
364    } else if map.not_ported.is_empty() {
365        writeln!(out, "Every unit `analyze` found has a port.\n")?;
366    } else {
367        writeln!(out, "In the order `analyze` suggests.\n")?;
368        writeln!(out, "| Unit | Lines | Exports | Readiness |")?;
369        writeln!(out, "| --- | ---: | ---: | ---: |")?;
370        for u in &map.not_ported {
371            writeln!(
372                out,
373                "| `{}` | {} | {} | {} |",
374                u.unit, u.loc, u.exports, u.readiness
375            )?;
376        }
377        writeln!(out)?;
378    }
379    writeln!(
380        out,
381        "Regenerate with `rust-anything map --write`. Commit this file: when the original changes \
382         upstream, the next map marks every port whose recording it outdated."
383    )
384}
385
386fn list(items: &[String]) -> String {
387    if items.is_empty() {
388        "-".into()
389    } else {
390        items
391            .iter()
392            .map(|i| format!("`{i}`"))
393            .collect::<Vec<_>>()
394            .join(", ")
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    fn empty_map() -> PortMap {
403        PortMap {
404            root: PathBuf::from("empty"),
405            ports: Vec::new(),
406            not_ported: Vec::new(),
407            glue: Vec::new(),
408            crate_errors: Vec::new(),
409            covered_by_broken: 0,
410            analyze_error: None,
411        }
412    }
413
414    #[test]
415    fn an_empty_map_says_no_unit_was_found() {
416        let text = markdown(&empty_map());
417        assert!(text.contains("No unit to port was found."), "{text}");
418        assert!(
419            !text.contains("Every unit `analyze` found has a port."),
420            "{text}"
421        );
422    }
423}