rust-anything 5.0.2

Migrate your app to 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Libraries (no `main`, no server): the front door is the library's public API as a Rust crate,
//! `rust/app`, re-exporting each unit's `port.rs` once it is wired. Until the lift, the original
//! package keeps its callers and reaches Rust through each unit's bindings and shadow drop-in,
//! which honors the unit's kill switch.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;

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

use crate::app::{Failure, Fallback, Problem, ReplayOutcome};
use crate::front_door::{APP_DIR, State, ident};
use crate::lang::Lang;

/// One unit of the library's public API, as `analyze` found it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiUnit {
    pub unit: String,
    /// The module that re-exports it in `rust/app`.
    pub module: String,
    pub exports: Vec<String>,
}

/// The exported functions and classes of `files`, as `bridge` sees them.
fn exports_of(root: &Path, lang: Lang, files: &[String]) -> Vec<String> {
    let mut out = Vec::new();
    for file in files {
        let Ok(text) = std::fs::read_to_string(root.join(file)) else {
            continue;
        };
        if lang == Lang::Ts {
            out.extend(
                crate::ts::exports::exported_functions(file, &text)
                    .into_iter()
                    .map(|f| f.name),
            );
            out.extend(
                crate::ts::exports::exported_classes(file, &text)
                    .into_iter()
                    .map(|c| c.name),
            );
        } else {
            let (functions, classes) = crate::lang::exports(lang, file, &text);
            out.extend(functions.into_iter().map(|f| f.name));
            out.extend(classes.into_iter().map(|c| c.name));
        }
    }
    out
}

/// The public API: every unit that moves to Rust, with its exports.
pub(crate) fn public_api(root: &Path, report: &crate::analyze::Report) -> Vec<ApiUnit> {
    let mut taken = BTreeMap::new();
    let mut out = Vec::new();
    for unit in report
        .units
        .iter()
        .filter(|u| u.status != crate::analyze::Status::Keep)
    {
        let exports = exports_of(root, report.language, &unit.files);
        if exports.is_empty() {
            continue;
        }
        let stem = unit
            .id
            .trim_end_matches('/')
            .rsplit('/')
            .next()
            .unwrap_or(&unit.id);
        let stem = stem.split('.').next().unwrap_or(stem);
        let mut module = ident(stem);
        let n = taken.entry(module.clone()).or_insert(0);
        *n += 1;
        if *n > 1 {
            module = format!("{module}_{n}");
        }
        out.push(ApiUnit {
            unit: unit.id.clone(),
            module,
            exports,
        });
    }
    out
}

pub(crate) fn cargo_toml(package: &str, name: &str) -> String {
    format!(
        "[package]\nname = \"{package}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
         description = \"`{name}`'s public API in Rust, generated by rust-anything: each unit's port, re-exported\"\n\n\
         [lib]\npath = \"src/lib.rs\"\n\n\
         [dependencies]\n\n\
         [workspace]\n"
    )
}

/// `rust/app/src/lib.rs`: the wired units' ports, one module each.
pub(crate) fn lib_rs(state: &State, lifted: bool) -> String {
    let mut out = if lifted {
        format!(
            "//! `{}`'s public API in Rust. Written by `rust-anything app lift`: every unit is a plain\n\
             //! Rust library here.\n",
            state.name
        )
    } else {
        format!(
            "//! `{}`'s public API in Rust. Generated by `rust-anything app wire` from rust-anything.json;\n\
             //! it is rewritten on every wire until the lift.\n",
            state.name
        )
    };
    let wired = |api: &ApiUnit| {
        state
            .units
            .iter()
            .find(|u| u.unit.as_deref() == Some(&api.unit))
    };
    let pending: Vec<String> = state
        .api
        .iter()
        .filter(|a| wired(a).is_none())
        .map(|a| format!("`{}`", a.unit))
        .collect();
    if !pending.is_empty() {
        out += &format!(
            "//!\n//! Still only in the original: {}.\n",
            pending.join(", ")
        );
    }
    out.push('\n');
    for api in &state.api {
        if let Some(unit) = wired(api) {
            out += &format!(
                "pub use {}::port as {};\n",
                unit.crate_name.replace('-', "_"),
                api.module
            );
        }
    }
    out
}

pub(crate) const CARGO_CONFIG: &str = ".cargo/config.toml";

/// A PyO3 unit's `cdylib` gets linked when `rust/app` depends on it; on macOS the Python symbols
/// are only there at load time.
pub(crate) fn allow_python_symbols(app_dir: &Path) -> Result<()> {
    let path = app_dir.join(CARGO_CONFIG);
    if path.exists() {
        return Ok(());
    }
    std::fs::create_dir_all(app_dir.join(".cargo"))?;
    std::fs::write(
        &path,
        "[target.'cfg(target_os = \"macos\")']
         rustflags = [\"-C\", \"link-arg=-undefined\", \"-C\", \"link-arg=dynamic_lookup\"]
",
    )?;
    Ok(())
}

pub(crate) fn cargo_build_lib(app_dir: &Path, target_dir: Option<&Path>) -> Result<()> {
    let mut cmd = Command::new("cargo");
    cmd.args(["build", "--quiet", "--manifest-path"])
        .arg(app_dir.join("Cargo.toml"))
        .current_dir(app_dir);
    if let Some(dir) = target_dir {
        cmd.env("CARGO_TARGET_DIR", dir);
    }
    let out = crate::process::output(&mut cmd, crate::process::BUILD).context("running cargo")?;
    ensure!(
        out.status.success(),
        "cargo build in {} failed:\n{}",
        app_dir.display(),
        String::from_utf8_lossy(&out.stderr)
    );
    Ok(())
}

/// The public API exports Rust does not answer yet: unwired units, and exports kept in the
/// original language.
pub(crate) fn pending(state: &State) -> Vec<String> {
    let mut out = Vec::new();
    for api in &state.api {
        let wired = state
            .units
            .iter()
            .find(|u| u.unit.as_deref() == Some(&api.unit));
        for name in &api.exports {
            if wired.is_none_or(|u| u.kept.contains(name)) {
                out.push(format!("{}: {name}", api.unit));
            }
        }
    }
    out
}

/// The recorded cases of every wired unit, through its bindings (`diff`), and the share of the
/// API still answered by the original.
pub(crate) fn replay(repo: &Path, state: &State, unit: Option<&str>) -> Result<ReplayOutcome> {
    crate::app::write_report(crate::app::grouped(replay_unwritten(repo, state, unit)?))
}

/// `replay` without writing the report.
pub(crate) fn replay_unwritten(
    repo: &Path,
    state: &State,
    unit: Option<&str>,
) -> Result<ReplayOutcome> {
    let app_dir = repo.join(APP_DIR);
    let mut outcome = ReplayOutcome {
        build: vec!["the units' bindings".to_string()],
        passed: 0,
        total: 0,
        skipped: 0,
        failures: Vec::new(),
        fallback: None,
        report: app_dir.join(crate::app::REPORT_FILE),
        groups: Vec::new(),
    };
    let units = crate::app::only_case(state.units.iter().collect(), unit, |u| &u.name)?;
    for unit in units {
        let crate_dir = app_dir.join(&unit.path);
        match crate::harness::diff(&crate::harness::DiffOptions {
            crate_dir: &crate_dir,
            module: None,
            ignore_key_order: false,
            float_tolerance: None,
            node_args: &[],
        }) {
            Ok(d) => {
                outcome.total += d.total;
                outcome.passed += d.passed;
                for m in &d.mismatches {
                    let args = m["args"]
                        .as_array()
                        .map(|a| a.iter().map(ToString::to_string).collect())
                        .unwrap_or_default();
                    outcome.failures.push(Failure {
                        case: format!("{}: {}", unit.name, m["fn"].as_str().unwrap_or("?")),
                        args,
                        problems: vec![{
                            let p = Problem::new(
                                "result",
                                format!("- {}\n+ {}\n", m["expected"], m["actual"]),
                            );
                            match serde_json::from_value(m["at"].clone()) {
                                Ok(at) => p.at(at),
                                Err(_) => p,
                            }
                        }],
                    });
                }
                if !d.missing.is_empty() {
                    outcome.total += 1;
                    outcome.failures.push(Failure {
                        case: format!("{}: api", unit.name),
                        args: Vec::new(),
                        problems: vec![
                            Problem::new("exports", format!("missing: {}\n", d.missing.join(", ")))
                                .at(crate::mismatch::At::new("missing key")),
                        ],
                    });
                }
            }
            Err(e) => {
                outcome.total += 1;
                outcome.failures.push(Failure {
                    case: unit.name.clone(),
                    args: Vec::new(),
                    problems: vec![
                        Problem::new(
                            "replay",
                            format!(
                                "{e:#}\n(build it first: rust-anything build {})\n",
                                crate_dir.display()
                            ),
                        )
                        .at(crate::mismatch::At::new("no response")),
                    ],
                });
            }
        }
    }
    let names = pending(state);
    let exports: usize = state.api.iter().map(|a| a.exports.len()).sum();
    outcome.fallback = Some(Fallback {
        cases: names.len(),
        total: exports,
        rate: names.len() as f64 / exports.max(1) as f64,
        names,
    });
    Ok(outcome)
}

/// Files of the original that name a unit's bindings or shadow: after the lift those are gone.
pub(crate) fn original_references(repo: &Path, state: &State) -> Vec<String> {
    let needles: Vec<String> = state
        .units
        .iter()
        .flat_map(|u| [u.crate_name.clone(), u.crate_name.replace('-', "_")])
        .collect();
    let mut out = Vec::new();
    let walker = crate::walk::filtered(repo, |e| {
        !matches!(
            e.file_name().to_string_lossy().as_ref(),
            "rust" | "target" | "node_modules" | ".git"
        )
    })
    .build();
    for entry in walker.flatten() {
        let path = entry.path();
        if !path.is_file() || std::fs::metadata(path).is_ok_and(|m| m.len() > 1 << 20) {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if needles.iter().any(|n| text.contains(n.as_str())) {
            out.push(
                path.strip_prefix(repo)
                    .unwrap_or(path)
                    .to_string_lossy()
                    .into_owned(),
            );
        }
    }
    out.sort();
    out
}

/// The unit a library crate ports, checked against the public API.
pub(crate) fn api_unit<'s>(state: &'s State, unit: &str) -> Result<&'s ApiUnit> {
    let wanted = unit.trim_end_matches('/');
    match state
        .api
        .iter()
        .find(|a| a.unit.trim_end_matches('/') == wanted)
    {
        Some(a) => Ok(a),
        None => bail!(
            "`{unit}` is not part of the public API (units: {})",
            state
                .api
                .iter()
                .map(|a| a.unit.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

/// The shadow drop-in for a crate: written once, then kept.
pub(crate) fn shadow_for(crate_dir: &Path, previous: Option<&str>) -> Result<Option<PathBuf>> {
    if let Some(p) = previous {
        return Ok(Some(PathBuf::from(p)));
    }
    match crate::shadow::shadow(crate_dir, None) {
        Ok(o) => Ok(Some(o.path)),
        Err(e) if format!("{e:#}").contains("exists") => Ok(None),
        Err(e) => Err(e),
    }
}

#[cfg(test)]
mod tests {
    use super::{api_unit, pending};
    use crate::front_door::{State, WiredUnit};

    /// `state(api, wired)`: the public API, and the units that are wired, each with its exports.
    fn state(api: &[(&str, &[&str])], wired: &[(&str, Option<&str>, &[&str])]) -> State {
        State {
            schema: String::new(),
            name: "lib".into(),
            commands: Vec::new(),
            units: wired
                .iter()
                .map(|(name, unit, kept)| WiredUnit {
                    name: (*name).into(),
                    crate_name: format!("{name}-rs"),
                    path: format!("../{name}-rs"),
                    commands: Vec::new(),
                    routes: Vec::new(),
                    switch: format!("RUST_ANYTHING_UNIT_{}", name.to_uppercase()),
                    unit: unit.map(ToString::to_string),
                    shadow: None,
                    kept: kept.iter().map(|k| (*k).to_string()).collect(),
                })
                .collect(),
            lifted: false,
            kind: crate::front_door::AppKind::Library,
            routes: Vec::new(),
            api: api
                .iter()
                .map(|(unit, exports)| crate::library::ApiUnit {
                    unit: (*unit).to_string(),
                    module: (*unit).replace('/', "_"),
                    exports: exports.iter().map(|e| (*e).to_string()).collect(),
                })
                .collect(),
        }
    }

    #[test]
    fn every_export_is_pending_until_its_unit_is_wired() {
        // Issue #719: the fallback rate comes from this list, so an unwired unit has to list every
        // export it still answers for.
        let s = state(
            &[("src/textkit", &["split", "join"]), ("src/net", &["get"])],
            &[],
        );
        assert_eq!(
            pending(&s),
            vec!["src/textkit: split", "src/textkit: join", "src/net: get"]
        );
    }

    #[test]
    fn a_wired_unit_is_pending_only_for_the_exports_it_kept() {
        let s = state(
            &[("src/textkit", &["split", "join"])],
            &[("textkit", Some("src/textkit"), &["join"])],
        );
        assert_eq!(pending(&s), vec!["src/textkit: join"]);
    }

    #[test]
    fn nothing_is_pending_once_every_unit_is_wired_and_keeps_nothing() {
        let s = state(
            &[("src/textkit", &["split"]), ("src/net", &["get"])],
            &[
                ("textkit", Some("src/textkit"), &[]),
                ("net", Some("src/net"), &[]),
            ],
        );
        assert!(pending(&s).is_empty(), "{:?}", pending(&s));
    }

    #[test]
    fn a_unit_is_found_with_or_without_a_trailing_slash() {
        let s = state(&[("src/textkit", &["split"])], &[]);
        assert_eq!(api_unit(&s, "src/textkit").unwrap().unit, "src/textkit");
        assert_eq!(
            api_unit(&s, "src/textkit/").unwrap().unit,
            "src/textkit",
            "a trailing slash on the argument still finds the unit"
        );
        // The other way round: the saved unit carries the slash and the argument does not.
        let slashed = state(&[("src/textkit/", &["split"])], &[]);
        assert_eq!(
            api_unit(&slashed, "src/textkit").unwrap().unit,
            "src/textkit/"
        );
    }

    #[test]
    fn an_unknown_unit_names_itself_and_the_units_that_exist() {
        let s = state(&[("src/textkit", &["split"]), ("src/net", &["get"])], &[]);
        let err = api_unit(&s, "src/missing").unwrap_err().to_string();
        assert!(
            err.contains("`src/missing` is not part of the public API"),
            "{err}"
        );
        assert!(
            err.contains("src/textkit, src/net"),
            "the units are listed: {err}"
        );
    }
}