alef 0.83.2

Opinionated polyglot binding generator for Rust libraries
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! Coverage for [`check_release_lock_freshness`], the release-gate counterpart to
//! `lock_freshness::check_generated_lock_freshness`.
//!
//! alef #1528: the diagnostic that module provides is correct and already caught real drift, but
//! only from inside `alef generate`/`alef all` -- and a drift whose cause lives in a hand-written
//! dependency alef never watches (the `tower-http` shape) never prompts a regen, so it never fired
//! before the affected consumer repos tagged and pushed. These tests exercise the same read-only
//! check reachable from `alef validate versions` instead, and prove it does NOT regress the one
//! case that must keep passing: a lock waiting on this release's own not-yet-published version.
//!
//! No cargo invocation anywhere: `check_release_lock_freshness` is pure file reads.

use super::*;
use crate::test_support::{git_add, git_init, write_file};
use tracing_test::traced_test;

const CANONICAL: &str = "1.2.1";
const OLD_VERSION: &str = "1.2.0";

/// The alef marker every generated manifest carries, so `collect_alef_headered_paths` finds it
/// exactly the way it finds a real generated `Cargo.toml`.
const ALEF_MARKER: &str = "# This file is auto-generated by alef — DO NOT EDIT.\n";

#[test]
fn relock_commands_enable_registry_access_only_for_the_fallback() {
    assert_eq!(relock_args(RelockMode::Offline), ["update", "--offline", "-w"]);
    assert_eq!(relock_args(RelockMode::Online), ["update", "-w"]);
}

#[test]
fn relock_does_not_contact_the_registry_when_the_offline_update_succeeds() {
    let mut modes = Vec::new();
    let outcome = attempt_relock_with(|mode| {
        modes.push(mode);
        Ok(CargoStatus::success())
    });

    assert_eq!(modes, vec![RelockMode::Offline]);
    assert!(matches!(outcome, Ok(RelockMode::Offline)));
}

#[test]
fn relock_retries_with_registry_access_when_the_offline_index_is_insufficient() {
    let mut modes = Vec::new();

    let outcome = attempt_relock_with(|mode| {
        modes.push(mode);
        Ok(match mode {
            RelockMode::Offline => CargoStatus::failed(Some(101)),
            RelockMode::Online => CargoStatus::success(),
        })
    });

    assert_eq!(modes, vec![RelockMode::Offline, RelockMode::Online]);
    assert!(
        matches!(outcome, Ok(RelockMode::Online)),
        "an online retry must recover when only the offline registry cache is stale: {outcome:?}"
    );
}

#[test]
fn relock_reports_both_resolver_failures_without_a_third_attempt() {
    let mut modes = Vec::new();

    let outcome = attempt_relock_with(|mode| {
        modes.push(mode);
        Ok(match mode {
            RelockMode::Offline => CargoStatus::failed(Some(101)),
            RelockMode::Online => CargoStatus::failed(Some(102)),
        })
    });

    assert_eq!(modes, vec![RelockMode::Offline, RelockMode::Online]);
    assert!(
        matches!(
            outcome,
            Err(RelockFailure::BothResolvers {
                offline_code: Some(101),
                online_code: Some(102),
            })
        ),
        "the diagnostic must retain each resolver's exit code: {outcome:?}"
    );
}

/// Root single-package crate depending on a stale third-party requirement -- mirrors
/// `lock_freshness_tests`'s own `sample-core`/`sample-json` fixture, the founding `tower-http`
/// incident's shape: the dependency that goes stale is not the crate under test's own version at
/// all, it lives one manifest away in a hand-written dependency the generated e2e crate reaches
/// only by `path`.
fn write_root_manifest_with_stale_dependency(root: &std::path::Path) {
    write_file(
        root,
        "Cargo.toml",
        "[package]\nname = \"sample-core\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n\
         sample-json = \"1.26\"\n",
    );
}

/// The alef-generated e2e crate, marked exactly like real generated output, depending on the
/// crate under test by path -- the indirection `relock_lockfiles_beside_changed_manifests` cannot
/// see through, since this manifest's own bytes never change when `sample-json` drifts.
fn write_generated_e2e_manifest(root: &std::path::Path) {
    write_file(
        root,
        "e2e/rust/Cargo.toml",
        &format!(
            "{ALEF_MARKER}[workspace]\n\n[package]\nname = \"sample-core-e2e-rust\"\nversion = \"0.1.0\"\n\
             edition = \"2024\"\n\n[dependencies]\nsample_core = {{ package = \"sample-core\", path = \"../..\" }}\n"
        ),
    );
}

fn write_stale_third_party_lock(root: &std::path::Path) {
    write_file(
        root,
        "e2e/rust/Cargo.lock",
        "version = 4\n\n\
         [[package]]\nname = \"sample-core-e2e-rust\"\nversion = \"0.1.0\"\n\n\
         [[package]]\nname = \"sample-core\"\nversion = \"0.1.0\"\n\n\
         [[package]]\nname = \"sample-json\"\nversion = \"1.25.0\"\n",
    );
}

/// The `test_apps/rust` shape every affected repo shared: an alef-generated, registry-mode
/// harness depending on the crate under test at exactly the canonical (about-to-release) version,
/// with a lock still pinning the previous release.
fn write_registry_mode_harness(root: &std::path::Path) {
    write_file(
        root,
        "Cargo.toml",
        &format!(
            "[workspace.package]\nversion = \"{CANONICAL}\"\n\n[workspace]\nresolver = \"2\"\n\
             members = [\"crates/sample\"]\n"
        ),
    );
    write_file(
        root,
        "crates/sample/Cargo.toml",
        "[package]\nname = \"sample\"\nversion.workspace = true\n",
    );
    write_file(root, "crates/sample/src/lib.rs", "");
    write_file(
        root,
        "test_apps/rust/Cargo.toml",
        &format!(
            "{ALEF_MARKER}[workspace]\n\n[package]\nname = \"sample-e2e-rust\"\nversion = \"{CANONICAL}\"\n\n\
             [dependencies]\nsample_alias = {{ package = \"sample\", version = \"{CANONICAL}\" }}\n"
        ),
    );
    write_file(root, "test_apps/rust/src/main.rs", "fn main() {}\n");
    write_file(
        root,
        "test_apps/rust/Cargo.lock",
        &format!(
            "version = 4\n\n[[package]]\nname = \"sample\"\nversion = \"{OLD_VERSION}\"\n\
             source = \"registry+https://example.invalid/index\"\n\n[[package]]\n\
             name = \"sample-e2e-rust\"\nversion = \"{CANONICAL}\"\n"
        ),
    );
}

/// The regression this module exists for: a stale lock whose cause is a hand-written dependency
/// alef never watches must fail the release gate, not merely get reported the next time someone
/// happens to run `alef generate`.
#[test]
fn check_release_lock_freshness_fails_on_a_drift_not_explained_by_a_pending_publish() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    git_init(root);
    write_root_manifest_with_stale_dependency(root);
    write_generated_e2e_manifest(root);
    write_stale_third_party_lock(root);
    git_add(root, &["Cargo.toml", "e2e/rust/Cargo.toml", "e2e/rust/Cargo.lock"]);

    let error =
        check_release_lock_freshness(root, "0.1.0").expect("a lock stale for an unrelated reason must fail the gate");
    let message = format!("{error:#}");

    assert!(
        message.contains("sample-json"),
        "message must name the dependency: {message}"
    );
    assert!(message.contains("1.25.0"), "message must name the stale pin: {message}");
    assert!(
        message.contains("cargo update"),
        "message must name the remedy: {message}"
    );
}

/// The control that must keep passing: a lock left disagreeing only because it pins this
/// release's own not-yet-published version must NOT fail the gate -- `alef validate versions`
/// already tolerates that row, and this check must defer to the exact same exemption rather than
/// re-litigating it with a stricter, independently-derived rule.
#[test]
fn check_release_lock_freshness_tolerates_a_lock_blocked_on_the_pending_release() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    git_init(root);
    write_registry_mode_harness(root);
    git_add(
        root,
        &[
            "Cargo.toml",
            "crates/sample/Cargo.toml",
            "crates/sample/src/lib.rs",
            "test_apps/rust/Cargo.toml",
            "test_apps/rust/Cargo.lock",
            "test_apps/rust/src/main.rs",
        ],
    );

    let outcome = check_release_lock_freshness(root, CANONICAL);

    assert!(
        outcome.is_none(),
        "a lock waiting on this release's own unpublished version must not fail the gate: {outcome:?}"
    );
}

/// The other control: a lock that resolves cleanly must report nothing at all.
#[test]
fn check_release_lock_freshness_passes_a_resolvable_lock() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    git_init(root);
    write_root_manifest_with_stale_dependency(root);
    write_generated_e2e_manifest(root);
    write_file(
        root,
        "e2e/rust/Cargo.lock",
        "version = 4\n\n\
         [[package]]\nname = \"sample-core-e2e-rust\"\nversion = \"0.1.0\"\n\n\
         [[package]]\nname = \"sample-core\"\nversion = \"0.1.0\"\n\n\
         [[package]]\nname = \"sample-json\"\nversion = \"1.26.0\"\n",
    );
    git_add(root, &["Cargo.toml", "e2e/rust/Cargo.toml", "e2e/rust/Cargo.lock"]);

    let outcome = check_release_lock_freshness(root, "0.1.0");

    assert!(
        outcome.is_none(),
        "a lock that resolves must be reported clean: {outcome:?}"
    );
}

#[test]
fn clean_dart_lock_does_not_invoke_a_resolver() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    write_file(
        root,
        "packages/dart/pubspec.yaml",
        "name: generated_binding\nversion: 0.1.0\nenvironment:\n  sdk: '>=3.0.0 <4.0.0'\n",
    );
    write_file(
        root,
        "e2e/dart/pubspec.yaml",
        "name: e2e_dart\nversion: 0.1.0\ndependencies:\n  generated_binding:\n    path: ../../packages/dart\n",
    );
    write_file(
        root,
        "e2e/dart/pubspec.lock",
        "packages:\n  generated_binding:\n    dependency: direct main\n    description:\n      path: ../../packages/dart\n      relative: true\n    source: path\n    version: \"0.1.0\"\n",
    );
    let files = [GeneratedFile {
        path: PathBuf::from("e2e/dart/pubspec.yaml"),
        content: std::fs::read_to_string(root.join("e2e/dart/pubspec.yaml")).expect("pubspec"),
        generated_header: true,
    }];
    let mut calls = 0;
    relock_dart_lockfiles_with(&files, root, &HashSet::new(), |_, _| {
        calls += 1;
        Ok(CargoStatus::success())
    });
    assert_eq!(
        calls, 0,
        "a byte-stable manifest with a satisfying lock must do no resolver work"
    );
}

#[test]
fn dart_lock_detects_a_stale_exact_pin_from_a_path_dependency() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    write_file(
        root,
        "packages/dart/pubspec.yaml",
        "name: generated_binding\nversion: 0.1.0\ndependencies:\n  flutter_rust_bridge: 2.13.0\n",
    );
    write_file(
        root,
        "e2e/dart/pubspec.yaml",
        "name: e2e_dart\nversion: 0.1.0\ndependencies:\n  generated_binding:\n    path: ../../packages/dart\n",
    );
    write_file(
        root,
        "e2e/dart/pubspec.lock",
        "packages:\n  generated_binding:\n    version: \"0.1.0\"\n  flutter_rust_bridge:\n    version: \"2.12.0\"\n",
    );
    assert!(
        dart_lock_has_stale_declared_pin(&root.join("e2e/dart")),
        "the unchanged e2e manifest must notice its path dependency's changed exact FRB pin"
    );
    write_file(
        root,
        "e2e/dart/pubspec.lock",
        "packages:\n  generated_binding:\n    version: \"0.1.0\"\n  flutter_rust_bridge:\n    version: \"2.13.0\"\n",
    );
    assert!(!dart_lock_has_stale_declared_pin(&root.join("e2e/dart")));
}

#[test]
fn dart_relock_retries_online_after_offline_resolution_failure() {
    let mut modes = Vec::new();
    let outcome = attempt_dart_relock_with(|mode| {
        modes.push(mode);
        Ok(match mode {
            DartRelockMode::Offline => CargoStatus::failed(Some(69)),
            DartRelockMode::Online => CargoStatus::success(),
        })
    });
    assert_eq!(outcome.expect("online fallback succeeds"), DartRelockMode::Online);
    assert_eq!(modes, vec![DartRelockMode::Offline, DartRelockMode::Online]);
}

/// The A6 regression, reproducing the tslp incident: `test_apps/dart/pubspec.yaml` pins
/// a downstream package as a plain (non-path) registry dependency at exactly the version
/// `packages/dart/pubspec.yaml` declares for itself this run -- not yet published to pub.dev.
/// Before this guard, `relock_dart_lockfiles_with` still invoked the resolver here, and both the
/// offline and online `dart pub get` attempts necessarily failed identically with "version
/// solving failed".
#[test]
fn dart_lock_blocked_on_publish_skips_a_pending_self_dependency_registry_pin() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    write_file(
        root,
        "packages/dart/pubspec.yaml",
        "name: sample_pending_pkg\nversion: 1.16.1\n",
    );
    write_file(
        root,
        "test_apps/dart/pubspec.yaml",
        "name: e2e_dart\nversion: 0.1.0\ndependencies:\n  sample_pending_pkg: 1.16.1\n",
    );
    write_file(
        root,
        "test_apps/dart/pubspec.lock",
        "packages:\n  sample_pending_pkg:\n    version: \"1.15.8\"\n",
    );
    let files = [
        GeneratedFile {
            path: PathBuf::from("packages/dart/pubspec.yaml"),
            content: std::fs::read_to_string(root.join("packages/dart/pubspec.yaml")).expect("pubspec"),
            generated_header: true,
        },
        GeneratedFile {
            path: PathBuf::from("test_apps/dart/pubspec.yaml"),
            content: std::fs::read_to_string(root.join("test_apps/dart/pubspec.yaml")).expect("pubspec"),
            generated_header: true,
        },
    ];
    let declared = declared_dart_package_versions(&files);

    assert!(
        dart_lock_blocked_on_publish(&root.join("test_apps/dart"), &declared),
        "a pending self-dependency registry pin must be recognized as blocked on publish"
    );

    let mut calls = 0;
    relock_dart_lockfiles_with(&files, root, &HashSet::new(), |_, _| {
        calls += 1;
        Ok(CargoStatus::success())
    });
    assert_eq!(
        calls, 0,
        "a lock blocked on this workspace's own pending release must not invoke dart pub get at \
         all -- both the offline and online attempts fail identically until the release publishes"
    );
}

/// The over-correction guard for A6: a `path:` dependency's own pin always equals its target's
/// declared version by construction (that IS what the path resolves to), so without excluding
/// `from_path` pins, EVERY path-mode e2e directory -- the common case
/// `relock_dart_lockfiles_beside_generated_manifests` exists for in the first place -- would be
/// misclassified as blocked on a registry publish that was never involved, and its purely local,
/// offline-resolvable staleness would never get relocked.
#[test]
fn dart_lock_blocked_on_publish_never_exempts_a_path_dependency_own_pin() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    write_file(
        root,
        "packages/dart/pubspec.yaml",
        "name: generated_binding\nversion: 0.2.0\n",
    );
    write_file(
        root,
        "e2e/dart/pubspec.yaml",
        "name: e2e_dart\nversion: 0.1.0\ndependencies:\n  generated_binding:\n    path: ../../packages/dart\n",
    );
    write_file(
        root,
        "e2e/dart/pubspec.lock",
        "packages:\n  generated_binding:\n    version: \"0.1.0\"\n",
    );
    let files = [
        GeneratedFile {
            path: PathBuf::from("packages/dart/pubspec.yaml"),
            content: std::fs::read_to_string(root.join("packages/dart/pubspec.yaml")).expect("pubspec"),
            generated_header: true,
        },
        GeneratedFile {
            path: PathBuf::from("e2e/dart/pubspec.yaml"),
            content: std::fs::read_to_string(root.join("e2e/dart/pubspec.yaml")).expect("pubspec"),
            generated_header: true,
        },
    ];
    let declared = declared_dart_package_versions(&files);

    assert!(
        !dart_lock_blocked_on_publish(&root.join("e2e/dart"), &declared),
        "a path dependency's own pin matches its target's declared version by construction, but it \
         resolves locally and must never be treated as blocked on a registry publish"
    );

    let mut calls = 0;
    relock_dart_lockfiles_with(&files, root, &HashSet::new(), |_, _| {
        calls += 1;
        Ok(CargoStatus::success())
    });
    assert_eq!(
        calls, 1,
        "a purely local, offline-resolvable path staleness must still get relocked"
    );
}

/// A second false-negative guard: an ordinary third-party drift whose name/version has nothing to
/// do with any package this run generated a `pubspec.yaml` for must still be treated as a
/// genuine, resolvable staleness -- the exemption must not blanket-suppress every stale pin just
/// because SOME package in the workspace happens to have a pending release.
#[test]
fn dart_lock_blocked_on_publish_still_relocks_an_unrelated_registry_drift() {
    let temp = tempfile::tempdir().expect("tempdir");
    let root = temp.path();
    write_file(
        root,
        "packages/dart/pubspec.yaml",
        "name: generated_binding\nversion: 0.1.0\n",
    );
    write_file(
        root,
        "test_apps/dart/pubspec.yaml",
        "name: e2e_dart\nversion: 0.1.0\ndependencies:\n  http: ^1.2.0\n",
    );
    write_file(
        root,
        "test_apps/dart/pubspec.lock",
        "packages:\n  http:\n    version: \"1.1.0\"\n",
    );
    let files = [GeneratedFile {
        path: PathBuf::from("packages/dart/pubspec.yaml"),
        content: std::fs::read_to_string(root.join("packages/dart/pubspec.yaml")).expect("pubspec"),
        generated_header: true,
    }];
    let declared = declared_dart_package_versions(&files);

    assert!(
        !dart_lock_blocked_on_publish(&root.join("test_apps/dart"), &declared),
        "an ordinary third-party drift unrelated to this workspace's own package must still be \
         treated as a genuine, resolvable staleness"
    );
}

/// A trivial, portable child process that prints `marker` to stdout and exits with `exit_code` --
/// enough to produce a real [`std::process::Output`] for [`log_dart_relock_output`] without
/// depending on `dart` being installed.
fn shell_output(exit_code: i32, marker: &str) -> std::process::Output {
    std::process::Command::new("sh")
        .arg("-c")
        .arg(format!("echo {marker}; exit {exit_code}"))
        .output()
        .expect("spawn sh")
}

/// The A6 stdio regression: `dart pub get`'s own stdout must be attributed into alef's log
/// through `tracing`, not silently inherited into alef's own raw stdout with no level prefix
/// (a real downstream incident: an unattributed "18 packages have newer versions..." notice
/// that read as alef's own output).
#[traced_test]
#[test]
fn dart_relock_output_is_attributed_on_success() {
    let output = shell_output(0, "dart-relock-success-marker");
    log_dart_relock_output(Path::new("e2e/dart"), DartRelockMode::Offline, &output);
    assert!(
        logs_contain("dart-relock-success-marker"),
        "dart pub get's own stdout must be attributed into alef's log, not silently inherited"
    );
}

/// Same as above for the failure path, where the existing warn-level handling already names the
/// directory and command -- the captured output must be attributed there too.
#[traced_test]
#[test]
fn dart_relock_output_is_attributed_on_failure() {
    let output = shell_output(1, "dart-relock-failure-marker");
    log_dart_relock_output(Path::new("e2e/dart"), DartRelockMode::Offline, &output);
    assert!(
        logs_contain("dart-relock-failure-marker"),
        "dart pub get's own stdout must be attributed into alef's log even on failure"
    );
}