rudzio-migrate 0.1.2

Best-effort converter of stock cargo-style Rust tests into rudzio tests. Runs on a clean git tree, rewrites sources in place, keeps backups and pre-migration copies as block comments, and asks before wiring a shared runner.
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
//! Cargo.toml edits via `toml_edit`. Preserves comments, key order,
//! and whitespace outside the regions we touch.

use std::collections::BTreeSet;
use std::fs;
use std::path::Path;

use anyhow::{Context as _, Result};
use toml_edit::{Array, ArrayOfTables, DocumentMut, InlineTable, Item, Table, value};

use crate::backup;
use crate::cli::RuntimeChoice;

/// Per-package collection of edits to apply to a `Cargo.toml`.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct Edits {
    /// `[[bin]]` target names from `cargo metadata`. Each one gets a
    /// `[[bin]] test = false` entry in the manifest after migration,
    /// so the rudzio-main binaries don't fire libtest on every
    /// `cargo test` pass with zero test functions to report.
    pub bin_names: Vec<String>,
    /// Whether ANY src/**/*.rs file in this package was rewritten —
    /// drives the `autotests = false` decision. A tests-only
    /// migration doesn't need it; the user's lib unit tests aren't
    /// affected.
    pub had_src_conversion: bool,
    /// Whether this package has a `src/lib.rs` that could host the
    /// `#[cfg(test)] #[rudzio::main] fn main() {}` entry point.
    /// When false (bin-only crates, or libs whose root isn't at
    /// the canonical path), `[lib] harness = false` isn't safe to
    /// emit — Cargo would complain about `[lib]` with no actual
    /// lib target — and we skip that edit.
    pub has_lib_rs: bool,
    /// Bool subset for "we need to add this dep / cfg" — split out so
    /// the parent struct doesn't trip `struct_excessive_bools`.
    pub needs: Needs,
    /// Async runtimes referenced by any rewritten test in this
    /// package. Used to compute the `features = [...]` list when
    /// emitting the `rudzio` dev-dependency. Empty means a
    /// tests-only / cfg-broadening run with no runtime promotion;
    /// the dep emit is skipped entirely.
    pub runtimes: BTreeSet<RuntimeChoice>,
    /// Synthesized `[[test]]` entries: one per integration test file
    /// the rewriter touched.
    pub tests_integration: Vec<IntegrationTestEntry>,
    /// Names found in the workspace's `[workspace.dependencies]`.
    /// When `rudzio` / `anyhow` is in here we emit
    /// `{ workspace = true, ... }` instead of hard-coding a version.
    pub workspace_dep_names: BTreeSet<String>,
}

/// One synthesized `[[test]]` entry to ensure exists in the package's
/// `Cargo.toml`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct IntegrationTestEntry {
    /// `[[test]] name` value.
    pub name: String,
    /// `[[test]] path` value, relative to the package root.
    pub path: String,
}

/// Bool flags gating a Cargo.toml *addition* (a new dep / cfg). Split
/// from [`Edits`] so neither trips `struct_excessive_bools`.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct Needs {
    /// True when the rewriter introduced an `anyhow::*` reference and
    /// the manifest needs `anyhow` as a dev-dep.
    pub anyhow: bool,
    /// True when a rewritten file references the `rudzio_test` cfg
    /// symbol (via the `cfg(any(test, rudzio_test))` rewrite or the
    /// synthesized integration-file wrapper module). The package's
    /// Cargo.toml then needs a
    /// `[lints.rust] unexpected_cfgs = { check-cfg = ['cfg(rudzio_test)'] }`
    /// entry so Rust 1.80+'s unknown-cfg warning doesn't fire.
    pub rudzio_test_cfg: bool,
}

/// Apply `edits` to `manifest_path`, writing back when the document
/// changed. Returns `true` iff the file was rewritten.
///
/// # Errors
///
/// Returns the underlying I/O or TOML parse error if reading,
/// parsing, backing up, or writing the manifest fails.
#[inline]
pub fn apply(manifest_path: &Path, edits: &Edits) -> Result<bool> {
    let source = fs::read_to_string(manifest_path)
        .with_context(|| format!("reading {}", manifest_path.display()))?;
    let mut doc: DocumentMut = source
        .parse()
        .with_context(|| format!("parsing {}", manifest_path.display()))?;

    let before = doc.to_string();

    if edits.had_src_conversion {
        set_autotests_false(&mut doc);
        if edits.has_lib_rs {
            // Unit tests live in the lib's own test target; libtest
            // doesn't understand `#[rudzio::test]`, so we have to
            // swap it out for a custom main. The matching
            // `#[cfg(test)] #[rudzio::main] fn main()` in src/lib.rs
            // is handled by `run.rs::ensure_lib_has_rudzio_main`.
            // Bin-only crates have no `[lib]` target, so setting
            // `[lib] harness = false` there would tell Cargo we
            // have a library that doesn't exist.
            set_lib_harness_false(&mut doc);
        }
    }
    if edits.has_lib_rs {
        set_lib_test_false(&mut doc);
    }
    for name in &edits.bin_names {
        set_bin_test_false(&mut doc, name);
    }
    // Only add `rudzio` as a dev-dep when at least one test fn was
    // actually wrapped into a rudzio suite — a crate whose only rewrite
    // was a `cfg_attr(test, ...) → cfg_attr(any(test, rudzio_test), ...)`
    // broadening doesn't need rudzio itself (that rewrite only
    // references the cfg symbol, not the crate).
    if !edits.runtimes.is_empty() {
        set_rudzio_dependency(
            &mut doc,
            &edits.runtimes,
            edits.workspace_dep_names.contains("rudzio"),
        );
    }
    if edits.needs.anyhow {
        set_anyhow_dependency(&mut doc, edits.workspace_dep_names.contains("anyhow"));
    }
    for entry in &edits.tests_integration {
        ensure_test_entry(&mut doc, entry);
    }
    if edits.needs.rudzio_test_cfg {
        ensure_check_cfg_rudzio_test(&mut doc);
    }

    let after = doc.to_string();
    if before == after {
        return Ok(false);
    }
    let _backup = backup::copy_before_write(manifest_path)
        .with_context(|| format!("backing up {}", manifest_path.display()))?;
    fs::write(manifest_path, &after)
        .with_context(|| format!("writing {}", manifest_path.display()))?;
    Ok(true)
}

/// True if either `[dependencies]` or `[dev-dependencies]` already
/// declares the named crate. Used to keep the tool from clobbering
/// a manually-curated entry — features may be tuned, paths may
/// point at a workspace fork, etc.
fn dep_already_present(doc: &DocumentMut, name: &str) -> bool {
    for section in ["dependencies", "dev-dependencies"] {
        if let Some(tbl) = doc.as_table().get(section).and_then(Item::as_table)
            && tbl.contains_key(name)
        {
            return true;
        }
    }
    false
}

/// Ensure `[lints.rust] unexpected_cfgs = { level = "warn", check-cfg
/// = ['cfg(rudzio_test)'] }` is present. Merge-safe: if `[lints.rust]`
/// already exists, only the `check-cfg` array is touched (and only
/// to add the `cfg(rudzio_test)` entry if it's missing). `level` is
/// added only when `unexpected_cfgs` didn't already exist — we never
/// override a user-chosen severity.
fn ensure_check_cfg_rudzio_test(doc: &mut DocumentMut) {
    const CFG_ENTRY: &str = "cfg(rudzio_test)";
    let lints_was_absent = !doc.as_table().contains_key("lints");
    let lints = doc
        .as_table_mut()
        .entry("lints")
        .or_insert(Item::Table(Table::new()));
    let Some(lints_tbl) = lints.as_table_mut() else {
        return;
    };
    if lints_was_absent {
        // Avoid emitting a bare `[lints]` header before `[lints.rust]`.
        // toml_edit renders implicit parent tables without their own
        // header, which is what the user would normally write by hand.
        lints_tbl.set_implicit(true);
    }
    let rust = lints_tbl.entry("rust").or_insert(Item::Table(Table::new()));
    let Some(rust_tbl) = rust.as_table_mut() else {
        return;
    };
    let existed = rust_tbl.contains_key("unexpected_cfgs");
    let unexpected =
        rust_tbl
            .entry("unexpected_cfgs")
            .or_insert(Item::Value(toml_edit::Value::InlineTable({
                let mut table = InlineTable::new();
                let _lvl = table.insert("level", "warn".into());
                let mut arr = Array::new();
                arr.push(CFG_ENTRY);
                let _cc = table.insert("check-cfg", arr.into());
                table
            })));
    if !existed {
        return;
    }
    let Item::Value(toml_edit::Value::InlineTable(inline)) = unexpected else {
        return;
    };
    let check_cfg_item = inline
        .entry("check-cfg")
        .or_insert(toml_edit::Value::Array(Array::new()));
    if let toml_edit::Value::Array(arr) = check_cfg_item {
        let already = arr
            .iter()
            .any(|item| item.as_str().is_some_and(|text| text == CFG_ENTRY));
        if !already {
            arr.push(CFG_ENTRY);
        }
    }
}

/// Ensure a `[[test]]` entry covering `entry` exists, with `harness =
/// false` set. Match against `name` (most common — synthesised
/// entries use the file stem) or `path` (for crates that already have
/// a custom `[[test]] path = "..."` layout pointing at the same file
/// with a different `name`); leave other fields untouched. If no
/// match is found, append a minimal `name + path + harness` entry.
fn ensure_test_entry(doc: &mut DocumentMut, entry: &IntegrationTestEntry) {
    let tests_item = doc
        .as_table_mut()
        .entry("test")
        .or_insert(Item::ArrayOfTables(ArrayOfTables::new()));
    let Some(arr) = tests_item.as_array_of_tables_mut() else {
        return;
    };
    for existing in arr.iter_mut() {
        let name_match = existing
            .get("name")
            .and_then(Item::as_str)
            .is_some_and(|text| text == entry.name);
        let path_match = existing
            .get("path")
            .and_then(Item::as_str)
            .is_some_and(|text| text == entry.path);
        if name_match || path_match {
            let harness_is_false = existing
                .get("harness")
                .and_then(Item::as_bool)
                .is_some_and(|flag| !flag);
            if !harness_is_false {
                let _prev = existing.insert("harness", value(false));
            }
            return;
        }
    }
    let mut tbl = Table::new();
    let _prev_name = tbl.insert("name", value(entry.name.clone()));
    let _prev_path = tbl.insert("path", value(entry.path.clone()));
    let _prev_harness = tbl.insert("harness", value(false));
    arr.push(tbl);
}

/// Add `anyhow` to `[dev-dependencies]` if it isn't already declared.
/// Prefers `{ workspace = true }` when the workspace pins anyhow,
/// otherwise hard-codes `"1.0"`.
fn set_anyhow_dependency(doc: &mut DocumentMut, workspace_pins_anyhow: bool) {
    if dep_already_present(doc, "anyhow") {
        return;
    }
    let entry = if workspace_pins_anyhow {
        let mut tbl = InlineTable::new();
        let _w = tbl.insert("workspace", true.into());
        Item::Value(tbl.into())
    } else {
        value("1.0")
    };
    let dev_deps = doc
        .as_table_mut()
        .entry("dev-dependencies")
        .or_insert(Item::Table(Table::new()));
    let Some(dev_tbl) = dev_deps.as_table_mut() else {
        return;
    };
    let _prev = dev_tbl.insert("anyhow", entry);
}

/// Set `[package] autotests = false` to suppress libtest's auto-found
/// integration test pass — every `tests/*.rs` file is now wired
/// explicitly through `[[test]]` entries with `harness = false`.
fn set_autotests_false(doc: &mut DocumentMut) {
    let package = doc
        .as_table_mut()
        .entry("package")
        .or_insert(Item::Table(Table::new()));
    let Some(pkg) = package.as_table_mut() else {
        return;
    };
    let _prev = pkg.insert("autotests", value(false));
}

/// Ensure `[[bin]] name = "<name>"` has `test = false`. If an entry
/// already exists for that name, amend it in place; otherwise append
/// a minimal `name + test` entry. Cargo merges these with
/// auto-discovered bins (keyed by name), so we don't need to specify
/// `path`.
fn set_bin_test_false(doc: &mut DocumentMut, bin_name: &str) {
    let bins_item = doc
        .as_table_mut()
        .entry("bin")
        .or_insert(Item::ArrayOfTables(ArrayOfTables::new()));
    let Some(arr) = bins_item.as_array_of_tables_mut() else {
        return;
    };
    for existing in arr.iter_mut() {
        let name_match = existing
            .get("name")
            .and_then(Item::as_str)
            .is_some_and(|text| text == bin_name);
        if name_match {
            let already_false = existing
                .get("test")
                .and_then(Item::as_value)
                .and_then(toml_edit::Value::as_bool)
                .is_some_and(|flag| !flag);
            if !already_false {
                let _prev = existing.insert("test", value(false));
            }
            return;
        }
    }
    let mut tbl = Table::new();
    let _prev_name = tbl.insert("name", value(bin_name.to_owned()));
    let _prev_test = tbl.insert("test", value(false));
    arr.push(tbl);
}

/// Set `[lib] harness = false` so the lib's test target runs
/// through the user's own `fn main` (i.e. `#[rudzio::main]`) rather
/// than libtest. If the user already set `harness = true`
/// explicitly we leave it — maybe they want libtest alongside.
/// Otherwise we flip it (or create the `[lib]` table if missing).
fn set_lib_harness_false(doc: &mut DocumentMut) {
    let lib = doc
        .as_table_mut()
        .entry("lib")
        .or_insert(Item::Table(Table::new()));
    let Some(lib_tbl) = lib.as_table_mut() else {
        return;
    };
    // Preserve an explicit `harness = true` override (user opted
    // into libtest on purpose — e.g. running rudzio out of a
    // separate binary via tests/main.rs aggregation).
    let user_opted_in = lib_tbl
        .get("harness")
        .and_then(Item::as_value)
        .and_then(toml_edit::Value::as_bool)
        .is_some_and(|flag| flag);
    if user_opted_in {
        return;
    }
    let _prev = lib_tbl.insert("harness", value(false));
}

/// `[lib] test = false` suppresses cargo's default libtest "unit
/// tests" pass on the lib. Post-migration the lib has no stock
/// `#[test]` fns — they've been rewritten into `#[rudzio::test]`
/// and run via `#[rudzio::main]` — so the libtest pass is empty
/// noise. Respects an explicit `test = true` override.
fn set_lib_test_false(doc: &mut DocumentMut) {
    let lib = doc
        .as_table_mut()
        .entry("lib")
        .or_insert(Item::Table(Table::new()));
    let Some(lib_tbl) = lib.as_table_mut() else {
        return;
    };
    let user_opted_in = lib_tbl
        .get("test")
        .and_then(Item::as_value)
        .and_then(toml_edit::Value::as_bool)
        .is_some_and(|flag| flag);
    if user_opted_in {
        return;
    }
    let _prev = lib_tbl.insert("test", value(false));
}

/// Add `rudzio` to `[dev-dependencies]` with the right `features = [
/// "common", "<runtime>" ]` list. Skips if the dep is already
/// declared (preserves manually-tuned versions / paths). Falls back
/// to hard-coding `version = "0.1"` when the workspace doesn't pin
/// rudzio itself.
fn set_rudzio_dependency(
    doc: &mut DocumentMut,
    runtimes: &BTreeSet<RuntimeChoice>,
    workspace_pins_rudzio: bool,
) {
    if dep_already_present(doc, "rudzio") {
        return;
    }
    let features = {
        let mut arr = Array::new();
        arr.push("common");
        let mut feat_set: BTreeSet<&'static str> = BTreeSet::new();
        for runtime in runtimes {
            let _inserted = feat_set.insert(runtime.cargo_feature());
        }
        if feat_set.is_empty() {
            let _inserted = feat_set.insert(RuntimeChoice::TokioMt.cargo_feature());
        }
        for feat in feat_set {
            arr.push(feat);
        }
        arr
    };

    let mut table = InlineTable::new();
    if workspace_pins_rudzio {
        let _w = table.insert("workspace", true.into());
    } else {
        let _v = table.insert("version", "0.1".into());
    }
    let _f = table.insert("features", toml_edit::Value::from(features));

    // Library crates use rudzio at test-time only; the right home
    // is `[dev-dependencies]`. Falls back to `[dependencies]` only
    // for crates that don't have a [dev-dependencies] section
    // already (very rare — most do once any test fixture or
    // tempfile is involved).
    let dev_deps = doc
        .as_table_mut()
        .entry("dev-dependencies")
        .or_insert(Item::Table(Table::new()));
    let Some(dev_tbl) = dev_deps.as_table_mut() else {
        return;
    };
    let _prev = dev_tbl.insert("rudzio", Item::Value(table.into()));
}