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 #[serde(skip_serializing_if = "Vec::is_empty")]
24 pub crate_errors: Vec<String>,
25 #[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 pub status: Status,
61 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 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 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 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 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
144 .strip_prefix(&root)
145 .unwrap_or(&dir)
146 .to_string_lossy()
147 .replace('\\', "/");
148 crate_errors.push(format!("`{shown}`: {e:#}"));
149 continue;
150 }
151 };
152 if std::fs::canonicalize(&m.root).ok().as_deref() != Some(root.as_path()) {
153 continue;
154 }
155 ports.push(port(&root, &dir, &m));
156 }
157 ports.sort_by(|a, b| a.unit.cmp(&b.unit).then(a.crate_dir.cmp(&b.crate_dir)));
158
159 let (not_ported, broken_units, analyze_error) = match crate::analyze::analyze(&root) {
160 Ok(report) => {
161 let order = |id: &str| {
162 report
163 .start_here
164 .iter()
165 .position(|s| s == id)
166 .unwrap_or(usize::MAX)
167 };
168 let unported: Vec<_> = report
169 .units
170 .iter()
171 .filter(|u| !ports.iter().any(|p| covers(&p.unit, &u.id, &u.files)))
172 .collect();
173 let (covered, mut units): (Vec<_>, Vec<_>) = unported.into_iter().partition(|u| {
176 covered_by_broken
177 .iter()
178 .any(|unit| covers(unit, &u.id, &u.files))
179 });
180 units.sort_by(|a, b| {
181 order(&a.id)
182 .cmp(&order(&b.id))
183 .then(b.priority.cmp(&a.priority))
184 .then(a.id.cmp(&b.id))
185 });
186 let units = units
187 .into_iter()
188 .map(|u| Unported {
189 unit: u.id.clone(),
190 loc: u.loc,
191 readiness: u.readiness,
192 exports: u.exports,
193 status: u.status,
194 reasons: u.reasons.clone(),
195 })
196 .collect();
197 (units, covered.len(), None)
198 }
199 Err(e) => (Vec::new(), 0, Some(format!("{e:#}"))),
200 };
201
202 Ok(PortMap {
203 glue: glue(&root),
204 root,
205 ports,
206 not_ported,
207 crate_errors,
208 covered_by_broken: broken_units,
209 analyze_error,
210 })
211}
212
213fn covers(unit: &str, id: &str, files: &[String]) -> bool {
214 unit == id || files.iter().any(|f| f == unit)
215}
216
217fn port(root: &Path, dir: &Path, m: &Manifest) -> Port {
218 let in_rust = m
219 .exports
220 .iter()
221 .map(|f| f.name.clone())
222 .chain(m.classes.iter().map(|c| c.name.clone()))
223 .collect();
224 let kept_in_original = m.js_only.iter().map(|j| j.name.clone()).collect();
225 let cases = std::fs::read_to_string(dir.join(CASES))
226 .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
227 .unwrap_or(0);
228 Port {
229 unit: m.unit.clone(),
230 crate_dir: dir
231 .strip_prefix(root)
232 .unwrap_or(dir)
233 .to_string_lossy()
234 .replace('\\', "/"),
235 language: format!("{:?}", m.language).to_lowercase(),
236 kind: format!("{:?}", m.kind).to_lowercase(),
237 in_rust,
238 kept_in_original,
239 cases,
240 last_diff: recording::last_diff(dir),
241 changed_upstream: recording::stale(dir, m),
242 }
243}
244fn manifests(dir: &Path) -> Vec<PathBuf> {
245 ignore::WalkBuilder::new(dir)
246 .hidden(false)
247 .filter_entry(|e| {
248 !matches!(
249 e.file_name().to_str(),
250 Some("node_modules" | "target" | ".git" | "vendor" | ".venv" | "venv")
251 )
252 })
253 .build()
254 .filter_map(Result::ok)
255 .filter(|e| e.file_name() == MANIFEST && e.file_type().is_some_and(|t| t.is_file()))
256 .filter_map(|e| e.path().parent().map(Path::to_path_buf))
257 .collect()
258}
259
260fn glue(root: &Path) -> Vec<Glue> {
261 let units = root.join(APP_DIR).join("src/units");
262 let Ok(entries) = std::fs::read_dir(&units) else {
263 return Vec::new();
264 };
265 let mut glue: Vec<Glue> = entries
266 .filter_map(Result::ok)
267 .filter(|e| e.path().extension().is_some_and(|x| x == "rs") && e.file_name() != "mod.rs")
268 .map(|e| Glue {
269 file: format!("{APP_DIR}/src/units/{}", e.file_name().to_string_lossy()),
270 falls_back: std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")),
271 })
272 .collect();
273 glue.sort_by(|a, b| a.file.cmp(&b.file));
274 glue
275}
276
277fn status_name(status: Status) -> &'static str {
279 match status {
280 Status::Ready => "ready",
281 Status::Caution => "caution",
282 Status::Blocked => "blocked",
283 Status::Keep => "keep",
284 }
285}
286
287pub fn markdown(map: &PortMap) -> String {
288 let mut out = String::new();
289 let _ = render(&mut out, map);
290 out
291}
292
293fn render(out: &mut String, map: &PortMap) -> std::fmt::Result {
294 let name = map.root.file_name().map_or_else(
295 || map.root.display().to_string(),
296 |n| n.to_string_lossy().into(),
297 );
298 writeln!(out, "# Port map: {name}\n")?;
299 let ported = map.ported_units();
300 let total = ported + map.not_ported.len() + map.covered_by_broken;
301 write!(
302 out,
303 "{} of {} {} a Rust port",
304 ported,
305 if map.analyze_error.is_some() {
306 "the".to_string()
307 } else {
308 total.to_string()
309 },
310 if total == 1 && map.analyze_error.is_none() {
312 "unit has"
313 } else {
314 "units have"
315 }
316 )?;
317 match map.changed() {
318 _ if map.ports.is_empty() => writeln!(out, ".\n")?,
319 0 => writeln!(out, "; no original changed since it was recorded.\n")?,
320 n => writeln!(
321 out,
322 "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
323 )?,
324 }
325
326 if !map.crate_errors.is_empty() {
327 writeln!(out, "## Crate folders that could not be read\n")?;
328 writeln!(
329 out,
330 "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"
331 )?;
332 for e in &map.crate_errors {
333 writeln!(out, "- {e}")?;
334 }
335 writeln!(out)?;
336 }
337
338 writeln!(out, "## Ports\n")?;
339 if map.ports.is_empty() {
340 writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
341 } else {
342 writeln!(
343 out,
344 "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original |"
345 )?;
346 writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- |")?;
347 for p in &map.ports {
348 writeln!(
349 out,
350 "| `{}` | `{}` | {} | {} | {} | {} | {} |",
351 p.unit,
352 p.crate_dir,
353 list(&p.in_rust),
354 list(&p.kept_in_original),
355 p.cases,
356 p.last_diff
357 .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
358 if p.changed_upstream.is_some() {
359 format!("**changed**: `rust-anything record {}`", p.crate_dir)
360 } else {
361 "unchanged".into()
362 }
363 )?;
364 }
365 writeln!(out)?;
366 }
367
368 if !map.glue.is_empty() {
369 writeln!(out, "## Whole app\n")?;
370 writeln!(out, "| Glue | Runs |")?;
371 writeln!(out, "| --- | --- |")?;
372 for g in &map.glue {
373 writeln!(
374 out,
375 "| `{}` | {} |",
376 g.file,
377 if g.falls_back {
378 "Rust, handing some cases to the original"
379 } else {
380 "Rust only"
381 }
382 )?;
383 }
384 writeln!(out)?;
385 }
386
387 writeln!(out, "## Not ported yet\n")?;
388 if let Some(e) = &map.analyze_error {
389 writeln!(out, "`analyze` could not list the units: {e}\n")?;
390 } else if total == 0 {
391 writeln!(out, "No unit to port was found.\n")?;
392 } else if map.not_ported.is_empty() {
393 writeln!(out, "Every unit `analyze` found has a port.\n")?;
394 } else {
395 writeln!(out, "In the order `analyze` suggests.\n")?;
396 writeln!(out, "| Unit | Status | Lines | Exports | Readiness |")?;
397 writeln!(out, "| --- | --- | ---: | ---: | ---: |")?;
398 for u in &map.not_ported {
399 writeln!(
400 out,
401 "| `{}` | {} | {} | {} | {} |",
402 u.unit,
403 status_name(u.status),
404 u.loc,
405 u.exports,
406 u.readiness
407 )?;
408 }
409 writeln!(out)?;
410 let left: Vec<&Unported> = map
413 .not_ported
414 .iter()
415 .filter(|u| !matches!(u.status, Status::Keep | Status::Blocked))
416 .collect();
417 let stays: Vec<&Unported> = map
418 .not_ported
419 .iter()
420 .filter(|u| matches!(u.status, Status::Keep | Status::Blocked))
421 .collect();
422 if !stays.is_empty() {
423 writeln!(
424 out,
425 "{} of these {} no port on purpose ({} blocked, {} kept in the original), so {} {} left to port:\n",
426 stays.len(),
427 if stays.len() == 1 {
428 "unit has"
429 } else {
430 "units have"
431 },
432 map.not_ported
433 .iter()
434 .filter(|u| matches!(u.status, Status::Blocked))
435 .count(),
436 map.not_ported
437 .iter()
438 .filter(|u| matches!(u.status, Status::Keep))
439 .count(),
440 left.len(),
441 if left.len() == 1 {
442 "unit is"
443 } else {
444 "units are"
445 },
446 )?;
447 for u in stays {
448 let why = if u.reasons.is_empty() {
449 String::new()
450 } else {
451 let reasons: Vec<&str> =
452 u.reasons.iter().map(|n| n.trim_end_matches('.')).collect();
453 format!(", {}", reasons.join("; "))
454 };
455 writeln!(out, "- `{}`: {}{why}", u.unit, status_name(u.status))?;
456 }
457 writeln!(out)?;
458 }
459 }
460 writeln!(
461 out,
462 "Regenerate with `rust-anything map --write`. Commit this file: when the original changes \
463 upstream, the next map marks every port whose recording it outdated."
464 )
465}
466
467fn list(items: &[String]) -> String {
468 if items.is_empty() {
469 "-".into()
470 } else {
471 items
472 .iter()
473 .map(|i| format!("`{i}`"))
474 .collect::<Vec<_>>()
475 .join(", ")
476 }
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482
483 fn empty_map() -> PortMap {
484 PortMap {
485 root: PathBuf::from("empty"),
486 ports: Vec::new(),
487 not_ported: Vec::new(),
488 glue: Vec::new(),
489 crate_errors: Vec::new(),
490 covered_by_broken: 0,
491 analyze_error: None,
492 }
493 }
494
495 #[test]
496 fn a_unit_that_stays_in_the_original_is_not_counted_as_work_to_do() {
497 let mut map = empty_map();
500 map.not_ported = vec![
501 Unported {
502 unit: "src/util.ts".into(),
503 loc: 19,
504 readiness: 94,
505 exports: 3,
506 status: crate::analyze::Status::Ready,
507 reasons: Vec::new(),
508 },
509 Unported {
510 unit: "src/view/".into(),
511 loc: 3,
512 readiness: 100,
513 exports: 0,
514 status: crate::analyze::Status::Keep,
515 reasons: vec!["UI code: keep in the original language.".into()],
516 },
517 Unported {
518 unit: "src/svelte.ts".into(),
519 loc: 4,
520 readiness: 92,
521 exports: 0,
522 status: crate::analyze::Status::Blocked,
523 reasons: vec!["`svelte` has no Rust equivalent.".into()],
524 },
525 ];
526 let text = markdown(&map);
527 assert!(
528 text.contains("| Unit | Status | Lines | Exports | Readiness |"),
529 "{text}"
530 );
531 assert!(text.contains("| `src/util.ts` | ready |"), "{text}");
532 assert!(text.contains("| `src/view/` | keep |"), "{text}");
533 assert!(text.contains("| `src/svelte.ts` | blocked |"), "{text}");
534 assert!(
536 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:"),
537 "{text}"
538 );
539 assert!(
540 text.contains("- `src/svelte.ts`: blocked, `svelte` has no Rust equivalent\n"),
541 "{text}"
542 );
543 assert!(
544 text.contains("- `src/view/`: keep, UI code: keep in the original language\n"),
545 "{text}"
546 );
547 }
548
549 #[test]
550 fn an_empty_map_says_no_unit_was_found() {
551 let text = markdown(&empty_map());
552 assert!(text.contains("No unit to port was found."), "{text}");
553 assert!(
554 !text.contains("Every unit `analyze` found has a port."),
555 "{text}"
556 );
557 }
558}