Skip to main content

rust_anything/
port_map.rs

1use std::fmt::Write as _;
2use std::path::{Path, PathBuf};
3
4use anyhow::Result;
5use serde::Serialize;
6
7use crate::bridge::{MANIFEST, Manifest};
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    #[serde(skip_serializing_if = "Option::is_none")]
21    pub analyze_error: Option<String>,
22}
23
24#[derive(Debug, Serialize)]
25pub struct Port {
26    pub unit: String,
27    #[serde(rename = "crate")]
28    pub crate_dir: String,
29    pub language: String,
30    pub kind: String,
31    pub in_rust: Vec<String>,
32    pub kept_in_original: Vec<String>,
33    pub cases: usize,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub last_diff: Option<(usize, usize)>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub changed_upstream: Option<String>,
38}
39
40#[derive(Debug, Serialize)]
41pub struct Unported {
42    pub unit: String,
43    pub loc: usize,
44    pub readiness: u32,
45    pub exports: usize,
46}
47
48#[derive(Debug, Serialize)]
49pub struct Glue {
50    pub file: String,
51    pub falls_back: bool,
52}
53
54impl PortMap {
55    pub fn changed(&self) -> usize {
56        self.ports
57            .iter()
58            .filter(|p| p.changed_upstream.is_some())
59            .count()
60    }
61}
62
63pub fn map(root: &Path, extra: &[PathBuf]) -> Result<PortMap> {
64    let root = std::fs::canonicalize(root)?;
65    let mut crate_dirs = manifests(&root);
66    for dir in extra {
67        crate_dirs.extend(manifests(&std::fs::canonicalize(dir)?));
68    }
69    crate_dirs.sort();
70    crate_dirs.dedup();
71
72    let mut ports = Vec::new();
73    for dir in crate_dirs {
74        let Ok(m) = Manifest::load(&dir) else {
75            continue;
76        };
77        if std::fs::canonicalize(&m.root).ok().as_deref() != Some(root.as_path()) {
78            continue;
79        }
80        ports.push(port(&root, &dir, &m));
81    }
82    ports.sort_by(|a, b| a.unit.cmp(&b.unit).then(a.crate_dir.cmp(&b.crate_dir)));
83
84    let (not_ported, analyze_error) = match crate::analyze::analyze(&root) {
85        Ok(report) => {
86            let order = |id: &str| {
87                report
88                    .start_here
89                    .iter()
90                    .position(|s| s == id)
91                    .unwrap_or(usize::MAX)
92            };
93            let mut units: Vec<_> = report
94                .units
95                .iter()
96                .filter(|u| !ports.iter().any(|p| covers(&p.unit, &u.id, &u.files)))
97                .collect();
98            units.sort_by(|a, b| {
99                order(&a.id)
100                    .cmp(&order(&b.id))
101                    .then(b.priority.cmp(&a.priority))
102                    .then(a.id.cmp(&b.id))
103            });
104            let units = units
105                .into_iter()
106                .map(|u| Unported {
107                    unit: u.id.clone(),
108                    loc: u.loc,
109                    readiness: u.readiness,
110                    exports: u.exports,
111                })
112                .collect();
113            (units, None)
114        }
115        Err(e) => (Vec::new(), Some(format!("{e:#}"))),
116    };
117
118    Ok(PortMap {
119        glue: glue(&root),
120        root,
121        ports,
122        not_ported,
123        analyze_error,
124    })
125}
126
127fn covers(unit: &str, id: &str, files: &[String]) -> bool {
128    unit == id || files.iter().any(|f| f == unit)
129}
130
131fn port(root: &Path, dir: &Path, m: &Manifest) -> Port {
132    let in_rust = m
133        .exports
134        .iter()
135        .map(|f| f.name.clone())
136        .chain(m.classes.iter().map(|c| c.name.clone()))
137        .collect();
138    let kept_in_original = m.js_only.iter().map(|j| j.name.clone()).collect();
139    let cases = std::fs::read_to_string(dir.join(CASES))
140        .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
141        .unwrap_or(0);
142    Port {
143        unit: m.unit.clone(),
144        crate_dir: dir
145            .strip_prefix(root)
146            .unwrap_or(dir)
147            .to_string_lossy()
148            .replace('\\', "/"),
149        language: format!("{:?}", m.language).to_lowercase(),
150        kind: format!("{:?}", m.kind).to_lowercase(),
151        in_rust,
152        kept_in_original,
153        cases,
154        last_diff: recording::last_diff(dir),
155        changed_upstream: recording::stale(dir, m),
156    }
157}
158fn manifests(dir: &Path) -> Vec<PathBuf> {
159    ignore::WalkBuilder::new(dir)
160        .hidden(false)
161        .filter_entry(|e| {
162            !matches!(
163                e.file_name().to_str(),
164                Some("node_modules" | "target" | ".git" | "vendor" | ".venv" | "venv")
165            )
166        })
167        .build()
168        .filter_map(Result::ok)
169        .filter(|e| e.file_name() == MANIFEST && e.file_type().is_some_and(|t| t.is_file()))
170        .filter_map(|e| e.path().parent().map(Path::to_path_buf))
171        .collect()
172}
173
174fn glue(root: &Path) -> Vec<Glue> {
175    let units = root.join(APP_DIR).join("src/units");
176    let Ok(entries) = std::fs::read_dir(&units) else {
177        return Vec::new();
178    };
179    let mut glue: Vec<Glue> = entries
180        .filter_map(Result::ok)
181        .filter(|e| e.path().extension().is_some_and(|x| x == "rs") && e.file_name() != "mod.rs")
182        .map(|e| Glue {
183            file: format!("{APP_DIR}/src/units/{}", e.file_name().to_string_lossy()),
184            falls_back: std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")),
185        })
186        .collect();
187    glue.sort_by(|a, b| a.file.cmp(&b.file));
188    glue
189}
190
191pub fn markdown(map: &PortMap) -> String {
192    let mut out = String::new();
193    let _ = render(&mut out, map);
194    out
195}
196
197fn render(out: &mut String, map: &PortMap) -> std::fmt::Result {
198    let name = map.root.file_name().map_or_else(
199        || map.root.display().to_string(),
200        |n| n.to_string_lossy().into(),
201    );
202    writeln!(out, "# Port map: {name}\n")?;
203    let total = map.ports.len() + map.not_ported.len();
204    write!(
205        out,
206        "{} of {} units have a Rust port",
207        map.ports.len(),
208        if map.analyze_error.is_some() {
209            "the".to_string()
210        } else {
211            total.to_string()
212        }
213    )?;
214    match map.changed() {
215        _ if map.ports.is_empty() => writeln!(out, ".\n")?,
216        0 => writeln!(out, "; no original changed since it was recorded.\n")?,
217        n => writeln!(
218            out,
219            "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
220        )?,
221    }
222
223    writeln!(out, "## Ports\n")?;
224    if map.ports.is_empty() {
225        writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
226    } else {
227        writeln!(
228            out,
229            "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original |"
230        )?;
231        writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- |")?;
232        for p in &map.ports {
233            writeln!(
234                out,
235                "| `{}` | `{}` | {} | {} | {} | {} | {} |",
236                p.unit,
237                p.crate_dir,
238                list(&p.in_rust),
239                list(&p.kept_in_original),
240                p.cases,
241                p.last_diff
242                    .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
243                if p.changed_upstream.is_some() {
244                    format!("**changed**: `rust-anything record {}`", p.crate_dir)
245                } else {
246                    "unchanged".into()
247                }
248            )?;
249        }
250        writeln!(out)?;
251    }
252
253    if !map.glue.is_empty() {
254        writeln!(out, "## Whole app\n")?;
255        writeln!(out, "| Glue | Runs |")?;
256        writeln!(out, "| --- | --- |")?;
257        for g in &map.glue {
258            writeln!(
259                out,
260                "| `{}` | {} |",
261                g.file,
262                if g.falls_back {
263                    "Rust, handing some cases to the original"
264                } else {
265                    "Rust only"
266                }
267            )?;
268        }
269        writeln!(out)?;
270    }
271
272    writeln!(out, "## Not ported yet\n")?;
273    if let Some(e) = &map.analyze_error {
274        writeln!(out, "`analyze` could not list the units: {e}\n")?;
275    } else if map.not_ported.is_empty() {
276        writeln!(out, "Every unit `analyze` found has a port.\n")?;
277    } else {
278        writeln!(out, "In the order `analyze` suggests.\n")?;
279        writeln!(out, "| Unit | Lines | Exports | Readiness |")?;
280        writeln!(out, "| --- | ---: | ---: | ---: |")?;
281        for u in &map.not_ported {
282            writeln!(
283                out,
284                "| `{}` | {} | {} | {} |",
285                u.unit, u.loc, u.exports, u.readiness
286            )?;
287        }
288        writeln!(out)?;
289    }
290    writeln!(
291        out,
292        "Regenerate with `rust-anything map --write`. Commit this file: when the original changes \
293         upstream, the next map marks every port whose recording it outdated."
294    )
295}
296
297fn list(items: &[String]) -> String {
298    if items.is_empty() {
299        "-".into()
300    } else {
301        items
302            .iter()
303            .map(|i| format!("`{i}`"))
304            .collect::<Vec<_>>()
305            .join(", ")
306    }
307}