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 #[serde(skip_serializing_if = "Vec::is_empty")]
23 pub crate_errors: Vec<String>,
24 #[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 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 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 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 {} {} 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 if total == 1 && map.analyze_error.is_none() {
273 "unit has"
274 } else {
275 "units have"
276 }
277 )?;
278 match map.changed() {
279 _ if map.ports.is_empty() => writeln!(out, ".\n")?,
280 0 => writeln!(out, "; no original changed since it was recorded.\n")?,
281 n => writeln!(
282 out,
283 "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
284 )?,
285 }
286
287 if !map.crate_errors.is_empty() {
288 writeln!(out, "## Crate folders that could not be read\n")?;
289 writeln!(
290 out,
291 "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"
292 )?;
293 for e in &map.crate_errors {
294 writeln!(out, "- {e}")?;
295 }
296 writeln!(out)?;
297 }
298
299 writeln!(out, "## Ports\n")?;
300 if map.ports.is_empty() {
301 writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
302 } else {
303 writeln!(
304 out,
305 "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original |"
306 )?;
307 writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- |")?;
308 for p in &map.ports {
309 writeln!(
310 out,
311 "| `{}` | `{}` | {} | {} | {} | {} | {} |",
312 p.unit,
313 p.crate_dir,
314 list(&p.in_rust),
315 list(&p.kept_in_original),
316 p.cases,
317 p.last_diff
318 .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
319 if p.changed_upstream.is_some() {
320 format!("**changed**: `rust-anything record {}`", p.crate_dir)
321 } else {
322 "unchanged".into()
323 }
324 )?;
325 }
326 writeln!(out)?;
327 }
328
329 if !map.glue.is_empty() {
330 writeln!(out, "## Whole app\n")?;
331 writeln!(out, "| Glue | Runs |")?;
332 writeln!(out, "| --- | --- |")?;
333 for g in &map.glue {
334 writeln!(
335 out,
336 "| `{}` | {} |",
337 g.file,
338 if g.falls_back {
339 "Rust, handing some cases to the original"
340 } else {
341 "Rust only"
342 }
343 )?;
344 }
345 writeln!(out)?;
346 }
347
348 writeln!(out, "## Not ported yet\n")?;
349 if let Some(e) = &map.analyze_error {
350 writeln!(out, "`analyze` could not list the units: {e}\n")?;
351 } else if map.not_ported.is_empty() {
352 writeln!(out, "Every unit `analyze` found has a port.\n")?;
353 } else {
354 writeln!(out, "In the order `analyze` suggests.\n")?;
355 writeln!(out, "| Unit | Lines | Exports | Readiness |")?;
356 writeln!(out, "| --- | ---: | ---: | ---: |")?;
357 for u in &map.not_ported {
358 writeln!(
359 out,
360 "| `{}` | {} | {} | {} |",
361 u.unit, u.loc, u.exports, u.readiness
362 )?;
363 }
364 writeln!(out)?;
365 }
366 writeln!(
367 out,
368 "Regenerate with `rust-anything map --write`. Commit this file: when the original changes \
369 upstream, the next map marks every port whose recording it outdated."
370 )
371}
372
373fn list(items: &[String]) -> String {
374 if items.is_empty() {
375 "-".into()
376 } else {
377 items
378 .iter()
379 .map(|i| format!("`{i}`"))
380 .collect::<Vec<_>>()
381 .join(", ")
382 }
383}