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::analyze::Status;
8use crate::bridge::{MANIFEST, Manifest, SCHEMA};
9use crate::front_door::APP_DIR;
10use crate::harness::CASES;
11use crate::recording;
12
13pub const MAP_FILE: &str = "rust/PORT_MAP.md";
14
15#[derive(Debug, Serialize)]
16pub struct PortMap {
17    pub root: PathBuf,
18    pub ports: Vec<Port>,
19    pub not_ported: Vec<Unported>,
20    pub glue: Vec<Glue>,
21    /// Crate folders under `rust/` whose manifest could not be read. `map` has to skip them, and a
22    /// skipped port is not a missing port: the file says so instead of listing the unit as unported.
23    #[serde(skip_serializing_if = "Vec::is_empty")]
24    pub crate_errors: Vec<String>,
25    /// Units a broken manifest still names: they are covered, so they belong in the total even
26    /// though no `Port` could be built for them.
27    #[serde(skip_serializing_if = "is_zero")]
28    pub covered_by_broken: usize,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub analyze_error: Option<String>,
31}
32
33fn is_zero(n: &usize) -> bool {
34    *n == 0
35}
36
37#[derive(Debug, Serialize)]
38pub struct Port {
39    pub unit: String,
40    #[serde(rename = "crate")]
41    pub crate_dir: String,
42    pub language: String,
43    pub kind: String,
44    pub in_rust: Vec<String>,
45    pub kept_in_original: Vec<String>,
46    pub cases: usize,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub last_diff: Option<(usize, usize)>,
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub changed_upstream: Option<String>,
51}
52
53#[derive(Debug, Serialize)]
54pub struct Unported {
55    pub unit: String,
56    pub loc: usize,
57    pub readiness: u32,
58    pub exports: usize,
59    /// `analyze`'s verdict: ready, caution, blocked or keep.
60    pub status: Status,
61    /// Why `analyze` calls it blocked or keep, when it says.
62    pub reasons: Vec<String>,
63}
64
65#[derive(Debug, Serialize)]
66pub struct Glue {
67    pub file: String,
68    pub falls_back: bool,
69}
70
71impl PortMap {
72    /// Units with at least one port. `ports` has a row per crate, and one unit can have several
73    /// (napi and wasm, or a second `bridge --out`).
74    pub fn ported_units(&self) -> usize {
75        let mut units: Vec<&str> = self.ports.iter().map(|p| p.unit.as_str()).collect();
76        units.sort_unstable();
77        units.dedup();
78        units.len()
79    }
80
81    pub fn changed(&self) -> usize {
82        self.ports
83            .iter()
84            .filter(|p| p.changed_upstream.is_some())
85            .count()
86    }
87}
88
89pub fn map(root: &Path, extra: &[PathBuf]) -> Result<PortMap> {
90    let root =
91        std::fs::canonicalize(root).with_context(|| format!("mapping {}", root.display()))?;
92    // A file is not a repository: `analyze` says so, and a map over a file used to come out empty
93    // and exit 0, or fail on the first directory read without naming what it read.
94    if !root.is_dir() {
95        bail!(
96            "{} is a file; `map` takes the folder of a project's source code",
97            root.display()
98        );
99    }
100    let mut crate_dirs = manifests(&root);
101    for dir in extra {
102        let dir =
103            std::fs::canonicalize(dir).with_context(|| format!("mapping {}", dir.display()))?;
104        if !dir.is_dir() {
105            bail!("{} is a file; `--crates` takes folders", dir.display());
106        }
107        crate_dirs.extend(manifests(&dir));
108    }
109    crate_dirs.sort();
110    crate_dirs.dedup();
111
112    let mut ports = Vec::new();
113    let mut crate_errors = Vec::new();
114    let mut covered_by_broken: Vec<String> = Vec::new();
115    for dir in crate_dirs {
116        let m = match Manifest::load(&dir) {
117            Ok(m) => m,
118            Err(e) => {
119                // The manifest did not load, but its JSON can still say what it covers and where:
120                // a folder that belongs to another repository stays skipped without a word, and a
121                // local one still covers its unit, so the unit is not reported as unported.
122                let raw: Option<serde_json::Value> = std::fs::read_to_string(dir.join(MANIFEST))
123                    .ok()
124                    .and_then(|t| serde_json::from_str(&t).ok());
125                // Foreign only when the root actually resolves somewhere else: a `root` that does
126                // not exist says nothing about ownership, and its unit still belongs here.
127                let foreign = raw
128                    .as_ref()
129                    .and_then(|v| v["root"].as_str())
130                    .and_then(|r| std::fs::canonicalize(dir.join(r)).ok())
131                    .is_some_and(|resolved| resolved != root);
132                let other_schema = raw
133                    .as_ref()
134                    .and_then(|v| v["schema"].as_str())
135                    .is_some_and(|s| s != SCHEMA);
136                if foreign || other_schema {
137                    continue;
138                }
139                if let Some(unit) = raw.as_ref().and_then(|v| v["unit"].as_str()) {
140                    covered_by_broken.push(unit.to_string());
141                }
142                let shown = dir
143                    .strip_prefix(&root)
144                    .unwrap_or(&dir)
145                    .display()
146                    .to_string();
147                crate_errors.push(format!("`{shown}`: {e:#}"));
148                continue;
149            }
150        };
151        if std::fs::canonicalize(&m.root).ok().as_deref() != Some(root.as_path()) {
152            continue;
153        }
154        ports.push(port(&root, &dir, &m));
155    }
156    ports.sort_by(|a, b| a.unit.cmp(&b.unit).then(a.crate_dir.cmp(&b.crate_dir)));
157
158    let (not_ported, broken_units, analyze_error) = match crate::analyze::analyze(&root) {
159        Ok(report) => {
160            let order = |id: &str| {
161                report
162                    .start_here
163                    .iter()
164                    .position(|s| s == id)
165                    .unwrap_or(usize::MAX)
166            };
167            let unported: Vec<_> = report
168                .units
169                .iter()
170                .filter(|u| !ports.iter().any(|p| covers(&p.unit, &u.id, &u.files)))
171                .collect();
172            // A unit a broken manifest still names is covered, but it is still a unit of this
173            // repository: the report counts it, or the summary reads as if it did not exist.
174            let (covered, mut units): (Vec<_>, Vec<_>) = unported.into_iter().partition(|u| {
175                covered_by_broken
176                    .iter()
177                    .any(|unit| covers(unit, &u.id, &u.files))
178            });
179            units.sort_by(|a, b| {
180                order(&a.id)
181                    .cmp(&order(&b.id))
182                    .then(b.priority.cmp(&a.priority))
183                    .then(a.id.cmp(&b.id))
184            });
185            let units = units
186                .into_iter()
187                .map(|u| Unported {
188                    unit: u.id.clone(),
189                    loc: u.loc,
190                    readiness: u.readiness,
191                    exports: u.exports,
192                    status: u.status,
193                    reasons: u.reasons.clone(),
194                })
195                .collect();
196            (units, covered.len(), None)
197        }
198        Err(e) => (Vec::new(), 0, Some(format!("{e:#}"))),
199    };
200
201    Ok(PortMap {
202        glue: glue(&root),
203        root,
204        ports,
205        not_ported,
206        crate_errors,
207        covered_by_broken: broken_units,
208        analyze_error,
209    })
210}
211
212fn covers(unit: &str, id: &str, files: &[String]) -> bool {
213    unit == id || files.iter().any(|f| f == unit)
214}
215
216fn port(root: &Path, dir: &Path, m: &Manifest) -> Port {
217    let in_rust = m
218        .exports
219        .iter()
220        .map(|f| f.name.clone())
221        .chain(m.classes.iter().map(|c| c.name.clone()))
222        .collect();
223    let kept_in_original = m.js_only.iter().map(|j| j.name.clone()).collect();
224    let cases = std::fs::read_to_string(dir.join(CASES))
225        .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
226        .unwrap_or(0);
227    Port {
228        unit: m.unit.clone(),
229        crate_dir: dir
230            .strip_prefix(root)
231            .unwrap_or(dir)
232            .to_string_lossy()
233            .replace('\\', "/"),
234        language: format!("{:?}", m.language).to_lowercase(),
235        kind: format!("{:?}", m.kind).to_lowercase(),
236        in_rust,
237        kept_in_original,
238        cases,
239        last_diff: recording::last_diff(dir),
240        changed_upstream: recording::stale(dir, m),
241    }
242}
243fn manifests(dir: &Path) -> Vec<PathBuf> {
244    ignore::WalkBuilder::new(dir)
245        .hidden(false)
246        .filter_entry(|e| {
247            !matches!(
248                e.file_name().to_str(),
249                Some("node_modules" | "target" | ".git" | "vendor" | ".venv" | "venv")
250            )
251        })
252        .build()
253        .filter_map(Result::ok)
254        .filter(|e| e.file_name() == MANIFEST && e.file_type().is_some_and(|t| t.is_file()))
255        .filter_map(|e| e.path().parent().map(Path::to_path_buf))
256        .collect()
257}
258
259fn glue(root: &Path) -> Vec<Glue> {
260    let units = root.join(APP_DIR).join("src/units");
261    let Ok(entries) = std::fs::read_dir(&units) else {
262        return Vec::new();
263    };
264    let mut glue: Vec<Glue> = entries
265        .filter_map(Result::ok)
266        .filter(|e| e.path().extension().is_some_and(|x| x == "rs") && e.file_name() != "mod.rs")
267        .map(|e| Glue {
268            file: format!("{APP_DIR}/src/units/{}", e.file_name().to_string_lossy()),
269            falls_back: std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")),
270        })
271        .collect();
272    glue.sort_by(|a, b| a.file.cmp(&b.file));
273    glue
274}
275
276/// The status word `analyze` uses, for the table and the list under it.
277fn status_name(status: Status) -> &'static str {
278    match status {
279        Status::Ready => "ready",
280        Status::Caution => "caution",
281        Status::Blocked => "blocked",
282        Status::Keep => "keep",
283    }
284}
285
286pub fn markdown(map: &PortMap) -> String {
287    let mut out = String::new();
288    let _ = render(&mut out, map);
289    out
290}
291
292fn render(out: &mut String, map: &PortMap) -> std::fmt::Result {
293    let name = map.root.file_name().map_or_else(
294        || map.root.display().to_string(),
295        |n| n.to_string_lossy().into(),
296    );
297    writeln!(out, "# Port map: {name}\n")?;
298    let ported = map.ported_units();
299    let total = ported + map.not_ported.len() + map.covered_by_broken;
300    write!(
301        out,
302        "{} of {} {} a Rust port",
303        ported,
304        if map.analyze_error.is_some() {
305            "the".to_string()
306        } else {
307            total.to_string()
308        },
309        // One unit reads "1 of 1 unit has", not "units have".
310        if total == 1 && map.analyze_error.is_none() {
311            "unit has"
312        } else {
313            "units have"
314        }
315    )?;
316    match map.changed() {
317        _ if map.ports.is_empty() => writeln!(out, ".\n")?,
318        0 => writeln!(out, "; no original changed since it was recorded.\n")?,
319        n => writeln!(
320            out,
321            "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
322        )?,
323    }
324
325    if !map.crate_errors.is_empty() {
326        writeln!(out, "## Crate folders that could not be read\n")?;
327        writeln!(
328            out,
329            "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"
330        )?;
331        for e in &map.crate_errors {
332            writeln!(out, "- {e}")?;
333        }
334        writeln!(out)?;
335    }
336
337    writeln!(out, "## Ports\n")?;
338    if map.ports.is_empty() {
339        writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
340    } else {
341        writeln!(
342            out,
343            "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original |"
344        )?;
345        writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- |")?;
346        for p in &map.ports {
347            writeln!(
348                out,
349                "| `{}` | `{}` | {} | {} | {} | {} | {} |",
350                p.unit,
351                p.crate_dir,
352                list(&p.in_rust),
353                list(&p.kept_in_original),
354                p.cases,
355                p.last_diff
356                    .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
357                if p.changed_upstream.is_some() {
358                    format!("**changed**: `rust-anything record {}`", p.crate_dir)
359                } else {
360                    "unchanged".into()
361                }
362            )?;
363        }
364        writeln!(out)?;
365    }
366
367    if !map.glue.is_empty() {
368        writeln!(out, "## Whole app\n")?;
369        writeln!(out, "| Glue | Runs |")?;
370        writeln!(out, "| --- | --- |")?;
371        for g in &map.glue {
372            writeln!(
373                out,
374                "| `{}` | {} |",
375                g.file,
376                if g.falls_back {
377                    "Rust, handing some cases to the original"
378                } else {
379                    "Rust only"
380                }
381            )?;
382        }
383        writeln!(out)?;
384    }
385
386    writeln!(out, "## Not ported yet\n")?;
387    if let Some(e) = &map.analyze_error {
388        writeln!(out, "`analyze` could not list the units: {e}\n")?;
389    } else if total == 0 {
390        writeln!(out, "No unit to port was found.\n")?;
391    } else if map.not_ported.is_empty() {
392        writeln!(out, "Every unit `analyze` found has a port.\n")?;
393    } else {
394        writeln!(out, "In the order `analyze` suggests.\n")?;
395        writeln!(out, "| Unit | Status | Lines | Exports | Readiness |")?;
396        writeln!(out, "| --- | --- | ---: | ---: | ---: |")?;
397        for u in &map.not_ported {
398            writeln!(
399                out,
400                "| `{}` | {} | {} | {} | {} |",
401                u.unit,
402                status_name(u.status),
403                u.loc,
404                u.exports,
405                u.readiness
406            )?;
407        }
408        writeln!(out)?;
409        // A unit that stays in the original is not work to do: say so in its own short list,
410        // with the reason `analyze` gave, or the table above reads as remaining work.
411        let left: Vec<&Unported> = map
412            .not_ported
413            .iter()
414            .filter(|u| !matches!(u.status, Status::Keep | Status::Blocked))
415            .collect();
416        let stays: Vec<&Unported> = map
417            .not_ported
418            .iter()
419            .filter(|u| matches!(u.status, Status::Keep | Status::Blocked))
420            .collect();
421        if !stays.is_empty() {
422            writeln!(
423                out,
424                "{} of these {} no port on purpose ({} blocked, {} kept in the original), so {} {} left to port:\n",
425                stays.len(),
426                if stays.len() == 1 {
427                    "unit has"
428                } else {
429                    "units have"
430                },
431                map.not_ported
432                    .iter()
433                    .filter(|u| matches!(u.status, Status::Blocked))
434                    .count(),
435                map.not_ported
436                    .iter()
437                    .filter(|u| matches!(u.status, Status::Keep))
438                    .count(),
439                left.len(),
440                if left.len() == 1 {
441                    "unit is"
442                } else {
443                    "units are"
444                },
445            )?;
446            for u in stays {
447                let why = if u.reasons.is_empty() {
448                    String::new()
449                } else {
450                    let reasons: Vec<&str> =
451                        u.reasons.iter().map(|n| n.trim_end_matches('.')).collect();
452                    format!(", {}", reasons.join("; "))
453                };
454                writeln!(out, "- `{}`: {}{why}", u.unit, status_name(u.status))?;
455            }
456            writeln!(out)?;
457        }
458    }
459    writeln!(
460        out,
461        "Regenerate with `rust-anything map --write`. Commit this file: when the original changes \
462         upstream, the next map marks every port whose recording it outdated."
463    )
464}
465
466fn list(items: &[String]) -> String {
467    if items.is_empty() {
468        "-".into()
469    } else {
470        items
471            .iter()
472            .map(|i| format!("`{i}`"))
473            .collect::<Vec<_>>()
474            .join(", ")
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481
482    fn empty_map() -> PortMap {
483        PortMap {
484            root: PathBuf::from("empty"),
485            ports: Vec::new(),
486            not_ported: Vec::new(),
487            glue: Vec::new(),
488            crate_errors: Vec::new(),
489            covered_by_broken: 0,
490            analyze_error: None,
491        }
492    }
493
494    #[test]
495    fn a_unit_that_stays_in_the_original_is_not_counted_as_work_to_do() {
496        // `analyze` says why a unit is blocked or kept; without that column and the list under the
497        // table, `map` reads as if every unported unit were remaining work.
498        let mut map = empty_map();
499        map.not_ported = vec![
500            Unported {
501                unit: "src/util.ts".into(),
502                loc: 19,
503                readiness: 94,
504                exports: 3,
505                status: crate::analyze::Status::Ready,
506                reasons: Vec::new(),
507            },
508            Unported {
509                unit: "src/view/".into(),
510                loc: 3,
511                readiness: 100,
512                exports: 0,
513                status: crate::analyze::Status::Keep,
514                reasons: vec!["UI code: keep in the original language.".into()],
515            },
516            Unported {
517                unit: "src/svelte.ts".into(),
518                loc: 4,
519                readiness: 92,
520                exports: 0,
521                status: crate::analyze::Status::Blocked,
522                reasons: vec!["`svelte` has no Rust equivalent.".into()],
523            },
524        ];
525        let text = markdown(&map);
526        assert!(
527            text.contains("| Unit | Status | Lines | Exports | Readiness |"),
528            "{text}"
529        );
530        assert!(text.contains("| `src/util.ts` | ready |"), "{text}");
531        assert!(text.contains("| `src/view/` | keep |"), "{text}");
532        assert!(text.contains("| `src/svelte.ts` | blocked |"), "{text}");
533        // The two that stay are named with their reason, and only the ready one counts as work.
534        assert!(
535            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:"),
536            "{text}"
537        );
538        assert!(
539            text.contains("- `src/svelte.ts`: blocked, `svelte` has no Rust equivalent\n"),
540            "{text}"
541        );
542        assert!(
543            text.contains("- `src/view/`: keep, UI code: keep in the original language\n"),
544            "{text}"
545        );
546    }
547
548    #[test]
549    fn an_empty_map_says_no_unit_was_found() {
550        let text = markdown(&empty_map());
551        assert!(text.contains("No unit to port was found."), "{text}");
552        assert!(
553            !text.contains("Every unit `analyze` found has a port."),
554            "{text}"
555        );
556    }
557}