rust-anything 4.0.0

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C# and PowerShell
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::Serialize;

use crate::bridge::{MANIFEST, Manifest, SCHEMA};
use crate::front_door::APP_DIR;
use crate::harness::CASES;
use crate::recording;

pub const MAP_FILE: &str = "rust/PORT_MAP.md";

#[derive(Debug, Serialize)]
pub struct PortMap {
    pub root: PathBuf,
    pub ports: Vec<Port>,
    pub not_ported: Vec<Unported>,
    pub glue: Vec<Glue>,
    /// Crate folders under `rust/` whose manifest could not be read. `map` has to skip them, and a
    /// skipped port is not a missing port: the file says so instead of listing the unit as unported.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub crate_errors: Vec<String>,
    /// Units a broken manifest still names: they are covered, so they belong in the total even
    /// though no `Port` could be built for them.
    #[serde(skip_serializing_if = "is_zero")]
    pub covered_by_broken: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub analyze_error: Option<String>,
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

#[derive(Debug, Serialize)]
pub struct Port {
    pub unit: String,
    #[serde(rename = "crate")]
    pub crate_dir: String,
    pub language: String,
    pub kind: String,
    pub in_rust: Vec<String>,
    pub kept_in_original: Vec<String>,
    pub cases: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_diff: Option<(usize, usize)>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub changed_upstream: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct Unported {
    pub unit: String,
    pub loc: usize,
    pub readiness: u32,
    pub exports: usize,
}

#[derive(Debug, Serialize)]
pub struct Glue {
    pub file: String,
    pub falls_back: bool,
}

impl PortMap {
    pub fn changed(&self) -> usize {
        self.ports
            .iter()
            .filter(|p| p.changed_upstream.is_some())
            .count()
    }
}

pub fn map(root: &Path, extra: &[PathBuf]) -> Result<PortMap> {
    let root =
        std::fs::canonicalize(root).with_context(|| format!("mapping {}", root.display()))?;
    // A file is not a repository: `analyze` says so, and a map over a file used to come out empty
    // and exit 0, or fail on the first directory read without naming what it read.
    if !root.is_dir() {
        bail!(
            "{} is a file; `map` takes the folder of a project's source code",
            root.display()
        );
    }
    let mut crate_dirs = manifests(&root);
    for dir in extra {
        let dir =
            std::fs::canonicalize(dir).with_context(|| format!("mapping {}", dir.display()))?;
        if !dir.is_dir() {
            bail!("{} is a file; `--crates` takes folders", dir.display());
        }
        crate_dirs.extend(manifests(&dir));
    }
    crate_dirs.sort();
    crate_dirs.dedup();

    let mut ports = Vec::new();
    let mut crate_errors = Vec::new();
    let mut covered_by_broken: Vec<String> = Vec::new();
    for dir in crate_dirs {
        let m = match Manifest::load(&dir) {
            Ok(m) => m,
            Err(e) => {
                // The manifest did not load, but its JSON can still say what it covers and where:
                // a folder that belongs to another repository stays skipped without a word, and a
                // local one still covers its unit, so the unit is not reported as unported.
                let raw: Option<serde_json::Value> = std::fs::read_to_string(dir.join(MANIFEST))
                    .ok()
                    .and_then(|t| serde_json::from_str(&t).ok());
                // Foreign only when the root actually resolves somewhere else: a `root` that does
                // not exist says nothing about ownership, and its unit still belongs here.
                let foreign = raw
                    .as_ref()
                    .and_then(|v| v["root"].as_str())
                    .and_then(|r| std::fs::canonicalize(dir.join(r)).ok())
                    .is_some_and(|resolved| resolved != root);
                let other_schema = raw
                    .as_ref()
                    .and_then(|v| v["schema"].as_str())
                    .is_some_and(|s| s != SCHEMA);
                if foreign || other_schema {
                    continue;
                }
                if let Some(unit) = raw.as_ref().and_then(|v| v["unit"].as_str()) {
                    covered_by_broken.push(unit.to_string());
                }
                let shown = dir
                    .strip_prefix(&root)
                    .unwrap_or(&dir)
                    .display()
                    .to_string();
                crate_errors.push(format!("`{shown}`: {e:#}"));
                continue;
            }
        };
        if std::fs::canonicalize(&m.root).ok().as_deref() != Some(root.as_path()) {
            continue;
        }
        ports.push(port(&root, &dir, &m));
    }
    ports.sort_by(|a, b| a.unit.cmp(&b.unit).then(a.crate_dir.cmp(&b.crate_dir)));

    let (not_ported, broken_units, analyze_error) = match crate::analyze::analyze(&root) {
        Ok(report) => {
            let order = |id: &str| {
                report
                    .start_here
                    .iter()
                    .position(|s| s == id)
                    .unwrap_or(usize::MAX)
            };
            let unported: Vec<_> = report
                .units
                .iter()
                .filter(|u| !ports.iter().any(|p| covers(&p.unit, &u.id, &u.files)))
                .collect();
            // A unit a broken manifest still names is covered, but it is still a unit of this
            // repository: the report counts it, or the summary reads as if it did not exist.
            let (covered, mut units): (Vec<_>, Vec<_>) = unported.into_iter().partition(|u| {
                covered_by_broken
                    .iter()
                    .any(|unit| covers(unit, &u.id, &u.files))
            });
            units.sort_by(|a, b| {
                order(&a.id)
                    .cmp(&order(&b.id))
                    .then(b.priority.cmp(&a.priority))
                    .then(a.id.cmp(&b.id))
            });
            let units = units
                .into_iter()
                .map(|u| Unported {
                    unit: u.id.clone(),
                    loc: u.loc,
                    readiness: u.readiness,
                    exports: u.exports,
                })
                .collect();
            (units, covered.len(), None)
        }
        Err(e) => (Vec::new(), 0, Some(format!("{e:#}"))),
    };

    Ok(PortMap {
        glue: glue(&root),
        root,
        ports,
        not_ported,
        crate_errors,
        covered_by_broken: broken_units,
        analyze_error,
    })
}

fn covers(unit: &str, id: &str, files: &[String]) -> bool {
    unit == id || files.iter().any(|f| f == unit)
}

fn port(root: &Path, dir: &Path, m: &Manifest) -> Port {
    let in_rust = m
        .exports
        .iter()
        .map(|f| f.name.clone())
        .chain(m.classes.iter().map(|c| c.name.clone()))
        .collect();
    let kept_in_original = m.js_only.iter().map(|j| j.name.clone()).collect();
    let cases = std::fs::read_to_string(dir.join(CASES))
        .map(|t| t.lines().filter(|l| !l.trim().is_empty()).count())
        .unwrap_or(0);
    Port {
        unit: m.unit.clone(),
        crate_dir: dir
            .strip_prefix(root)
            .unwrap_or(dir)
            .to_string_lossy()
            .replace('\\', "/"),
        language: format!("{:?}", m.language).to_lowercase(),
        kind: format!("{:?}", m.kind).to_lowercase(),
        in_rust,
        kept_in_original,
        cases,
        last_diff: recording::last_diff(dir),
        changed_upstream: recording::stale(dir, m),
    }
}
fn manifests(dir: &Path) -> Vec<PathBuf> {
    ignore::WalkBuilder::new(dir)
        .hidden(false)
        .filter_entry(|e| {
            !matches!(
                e.file_name().to_str(),
                Some("node_modules" | "target" | ".git" | "vendor" | ".venv" | "venv")
            )
        })
        .build()
        .filter_map(Result::ok)
        .filter(|e| e.file_name() == MANIFEST && e.file_type().is_some_and(|t| t.is_file()))
        .filter_map(|e| e.path().parent().map(Path::to_path_buf))
        .collect()
}

fn glue(root: &Path) -> Vec<Glue> {
    let units = root.join(APP_DIR).join("src/units");
    let Ok(entries) = std::fs::read_dir(&units) else {
        return Vec::new();
    };
    let mut glue: Vec<Glue> = entries
        .filter_map(Result::ok)
        .filter(|e| e.path().extension().is_some_and(|x| x == "rs") && e.file_name() != "mod.rs")
        .map(|e| Glue {
            file: format!("{APP_DIR}/src/units/{}", e.file_name().to_string_lossy()),
            falls_back: std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("original::")),
        })
        .collect();
    glue.sort_by(|a, b| a.file.cmp(&b.file));
    glue
}

pub fn markdown(map: &PortMap) -> String {
    let mut out = String::new();
    let _ = render(&mut out, map);
    out
}

fn render(out: &mut String, map: &PortMap) -> std::fmt::Result {
    let name = map.root.file_name().map_or_else(
        || map.root.display().to_string(),
        |n| n.to_string_lossy().into(),
    );
    writeln!(out, "# Port map: {name}\n")?;
    let total = map.ports.len() + map.not_ported.len() + map.covered_by_broken;
    write!(
        out,
        "{} of {} {} a Rust port",
        map.ports.len(),
        if map.analyze_error.is_some() {
            "the".to_string()
        } else {
            total.to_string()
        },
        // One unit reads "1 of 1 unit has", not "units have".
        if total == 1 && map.analyze_error.is_none() {
            "unit has"
        } else {
            "units have"
        }
    )?;
    match map.changed() {
        _ if map.ports.is_empty() => writeln!(out, ".\n")?,
        0 => writeln!(out, "; no original changed since it was recorded.\n")?,
        n => writeln!(
            out,
            "; **{n} changed upstream** since they were recorded: re-record them and run `diff`.\n"
        )?,
    }

    if !map.crate_errors.is_empty() {
        writeln!(out, "## Crate folders that could not be read\n")?;
        writeln!(
            out,
            "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"
        )?;
        for e in &map.crate_errors {
            writeln!(out, "- {e}")?;
        }
        writeln!(out)?;
    }

    writeln!(out, "## Ports\n")?;
    if map.ports.is_empty() {
        writeln!(out, "None yet: `rust-anything bridge` starts one.\n")?;
    } else {
        writeln!(
            out,
            "| Unit | Crate | In Rust | Kept in the original | Cases | Last diff | Original |"
        )?;
        writeln!(out, "| --- | --- | --- | --- | ---: | ---: | --- |")?;
        for p in &map.ports {
            writeln!(
                out,
                "| `{}` | `{}` | {} | {} | {} | {} | {} |",
                p.unit,
                p.crate_dir,
                list(&p.in_rust),
                list(&p.kept_in_original),
                p.cases,
                p.last_diff
                    .map_or("not run".into(), |(m, t)| format!("{m}/{t}")),
                if p.changed_upstream.is_some() {
                    format!("**changed**: `rust-anything record {}`", p.crate_dir)
                } else {
                    "unchanged".into()
                }
            )?;
        }
        writeln!(out)?;
    }

    if !map.glue.is_empty() {
        writeln!(out, "## Whole app\n")?;
        writeln!(out, "| Glue | Runs |")?;
        writeln!(out, "| --- | --- |")?;
        for g in &map.glue {
            writeln!(
                out,
                "| `{}` | {} |",
                g.file,
                if g.falls_back {
                    "Rust, handing some cases to the original"
                } else {
                    "Rust only"
                }
            )?;
        }
        writeln!(out)?;
    }

    writeln!(out, "## Not ported yet\n")?;
    if let Some(e) = &map.analyze_error {
        writeln!(out, "`analyze` could not list the units: {e}\n")?;
    } else if total == 0 {
        writeln!(out, "No unit to port was found.\n")?;
    } else if map.not_ported.is_empty() {
        writeln!(out, "Every unit `analyze` found has a port.\n")?;
    } else {
        writeln!(out, "In the order `analyze` suggests.\n")?;
        writeln!(out, "| Unit | Lines | Exports | Readiness |")?;
        writeln!(out, "| --- | ---: | ---: | ---: |")?;
        for u in &map.not_ported {
            writeln!(
                out,
                "| `{}` | {} | {} | {} |",
                u.unit, u.loc, u.exports, u.readiness
            )?;
        }
        writeln!(out)?;
    }
    writeln!(
        out,
        "Regenerate with `rust-anything map --write`. Commit this file: when the original changes \
         upstream, the next map marks every port whose recording it outdated."
    )
}

fn list(items: &[String]) -> String {
    if items.is_empty() {
        "-".into()
    } else {
        items
            .iter()
            .map(|i| format!("`{i}`"))
            .collect::<Vec<_>>()
            .join(", ")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn empty_map() -> PortMap {
        PortMap {
            root: PathBuf::from("empty"),
            ports: Vec::new(),
            not_ported: Vec::new(),
            glue: Vec::new(),
            crate_errors: Vec::new(),
            covered_by_broken: 0,
            analyze_error: None,
        }
    }

    #[test]
    fn an_empty_map_says_no_unit_was_found() {
        let text = markdown(&empty_map());
        assert!(text.contains("No unit to port was found."), "{text}");
        assert!(
            !text.contains("Every unit `analyze` found has a port."),
            "{text}"
        );
    }
}