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