cargo-truce 0.34.0

Build tool for truce audio plugins
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! `cargo truce validate` — drive auval (AU v2/v3), pluginval (VST3), and
//! clap-validator (CLAP) against the project's installed bundles, with
//! shadow-install collision detection.

use crate::install_scope::InstallScope;
use crate::{PluginDef, Res, dirs, load_config, tag_warn, tmp_dir};
#[cfg(target_os = "macos")]
use crate::{deployment_target, project_root};
use std::fs;
use std::path::Path;
#[cfg(target_os = "macos")]
use std::path::PathBuf;
use std::process::Command;

/// Print a one-line warning when the same plugin is installed under
/// both user and system scope. Both copies are valid bundles; the
/// host picks one at scan time and shadows the other, which is a
/// frequent cause of "DAW loads my old build" support questions.
fn warn_on_scope_collision(format: &str, user_path: &Path, system_path: &Path) {
    if user_path.exists() && system_path.exists() {
        eprintln!("    {} {format} installed in both scopes:", tag_warn());
        eprintln!("        • user:   {}", user_path.display());
        eprintln!("        • system: {}", system_path.display());
        eprintln!(
            "        Hosts pick one at scan time; remove the stale copy with \
             `cargo truce uninstall --user` or `--system`."
        );
    }
}

/// Read a single leaf value from a plist via `plutil -extract … raw`.
/// Returns `None` if the key path doesn't exist or the value isn't a scalar.
#[cfg(target_os = "macos")]
fn plist_extract(plist: &Path, key_path: &str) -> Option<String> {
    let out = Command::new("plutil")
        .args(["-extract", key_path, "raw", "-o", "-", plist.to_str()?])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if s.is_empty() { None } else { Some(s) }
}

/// Find every AU bundle on disk that declares the given component code.
/// Walks the standard AU install directories and reads each candidate's
/// Info.plist. Used by `cmd_validate` to surface stale-install collisions
/// (the underlying cause of cryptic auval errors like
/// `FATAL ERROR: Initialize: result: -10875` when an old `Truce Gain.app`
/// shadows the current `Truce Gain v3.app`).
#[cfg(target_os = "macos")]
fn find_au_collisions(au_type: &str, subtype: &str, manufacturer: &str) -> Vec<PathBuf> {
    let mut hits = Vec::new();
    let home = dirs::home_dir().unwrap_or_default();

    // AU v3: Application bundles ship the appex inside Contents/PlugIns.
    // Walk both /Applications and ~/Applications (per-user install).
    for apps_dir in [PathBuf::from("/Applications"), home.join("Applications")] {
        let Ok(apps) = fs::read_dir(&apps_dir) else {
            continue;
        };
        for app in apps.flatten() {
            let plugins_dir = app.path().join("Contents/PlugIns");
            let Ok(appexes) = fs::read_dir(&plugins_dir) else {
                continue;
            };
            for appex in appexes.flatten() {
                let plist = appex.path().join("Contents/Info.plist");
                if matches_au_v3_descriptor(&plist, au_type, subtype, manufacturer) {
                    hits.push(appex.path());
                }
            }
        }
    }

    // AU v2: .component bundles in the standard system & user paths.
    for dir in [
        PathBuf::from("/Library/Audio/Plug-Ins/Components"),
        home.join("Library/Audio/Plug-Ins/Components"),
    ] {
        let Ok(comps) = fs::read_dir(&dir) else {
            continue;
        };
        for comp in comps.flatten() {
            let plist = comp.path().join("Contents/Info.plist");
            if matches_au_v2_descriptor(&plist, au_type, subtype, manufacturer) {
                hits.push(comp.path());
            }
        }
    }

    hits
}

#[cfg(target_os = "macos")]
fn matches_au_v3_descriptor(
    plist: &Path,
    au_type: &str,
    subtype: &str,
    manufacturer: &str,
) -> bool {
    if !plist.is_file() {
        return false;
    }
    let prefix = "NSExtension.NSExtensionAttributes.AudioComponents.0";
    plist_extract(plist, &format!("{prefix}.subtype")).as_deref() == Some(subtype)
        && plist_extract(plist, &format!("{prefix}.type")).as_deref() == Some(au_type)
        && plist_extract(plist, &format!("{prefix}.manufacturer")).as_deref() == Some(manufacturer)
}

#[cfg(target_os = "macos")]
fn matches_au_v2_descriptor(
    plist: &Path,
    au_type: &str,
    subtype: &str,
    manufacturer: &str,
) -> bool {
    if !plist.is_file() {
        return false;
    }
    plist_extract(plist, "AudioComponents.0.subtype").as_deref() == Some(subtype)
        && plist_extract(plist, "AudioComponents.0.type").as_deref() == Some(au_type)
        && plist_extract(plist, "AudioComponents.0.manufacturer").as_deref() == Some(manufacturer)
}

/// Print a warning if more than one bundle declares the AU component
/// `(au_type, subtype, manufacturer)`. macOS picks one at load time; the other
/// gets shadowed and produces opaque auval failures.
#[cfg(target_os = "macos")]
fn warn_on_au_collision(au_type: &str, subtype: &str, manufacturer: &str, expected: &Path) {
    let hits = find_au_collisions(au_type, subtype, manufacturer);
    if hits.len() <= 1 {
        return;
    }
    eprintln!(
        "    {} collision: {} other bundle(s) also claim {}/{}/{}",
        tag_warn(),
        hits.len() - 1,
        au_type,
        subtype,
        manufacturer,
    );
    for h in &hits {
        let marker = if h.starts_with(expected) || expected.starts_with(h) {
            "← expected"
        } else {
            "← stale, remove this"
        };
        eprintln!("{} {}", h.display(), marker);
    }
    eprintln!("        macOS will pick one at load time; the rest are shadowed.");
}

#[allow(clippy::too_many_lines)]
pub(crate) fn cmd_validate(args: &[String]) -> Res {
    let config = load_config()?;

    let mut run_auval = false;
    let mut run_auval_v3 = false;
    let mut run_pluginval = false;
    let mut run_clap = false;
    let mut run_vst2 = false;
    let mut plugin_filter: Option<String> = None;

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--auval" => run_auval = true,
            "--auval3" => run_auval_v3 = true,
            "--pluginval" => run_pluginval = true,
            "--clap" => run_clap = true,
            "--vst2" => run_vst2 = true,
            "--all" => {
                run_auval = true;
                run_auval_v3 = true;
                run_pluginval = true;
                run_clap = true;
                run_vst2 = true;
            }
            "-p" => {
                i += 1;
                plugin_filter = Some(
                    args.get(i)
                        .cloned()
                        .ok_or("-p requires a plugin crate name")?,
                );
            }
            "--help" | "-h" => {
                print_help();
                return Ok(());
            }
            other => return Err(format!("Unknown flag: {other}").into()),
        }
        i += 1;
    }
    if !run_auval && !run_auval_v3 && !run_pluginval && !run_clap && !run_vst2 {
        run_auval = true;
        run_auval_v3 = true;
        run_pluginval = true;
        run_clap = true;
        run_vst2 = true;
    }

    let plugins: Vec<&PluginDef> = super::pick_plugins(&config, plugin_filter.as_deref())?;

    let mut failures = 0;

    // --- auval (macOS only, AU v2) ---
    if run_auval {
        eprintln!("=== auval (AU v2) ===\n");
        if Command::new("auval").arg("-h").output().is_ok() {
            for p in &plugins {
                #[cfg(target_os = "macos")]
                {
                    let user_path = InstallScope::User
                        .au_v2_dir()
                        .join(format!("{}.component", p.name));
                    let system_path = InstallScope::System
                        .au_v2_dir()
                        .join(format!("{}.component", p.name));
                    warn_on_scope_collision("AU v2", &user_path, &system_path);
                }
                eprint!(
                    "  {} ({} {} {}) ... ",
                    p.name,
                    p.resolved_au_type(),
                    p.resolved_fourcc(),
                    config.vendor.au_manufacturer
                );
                let output = Command::new("auval")
                    .args([
                        "-v",
                        p.resolved_au_type(),
                        p.resolved_fourcc(),
                        &config.vendor.au_manufacturer,
                    ])
                    .output()?;
                let stdout = String::from_utf8_lossy(&output.stdout);
                if stdout.contains("VALIDATION SUCCEEDED") {
                    eprintln!("PASS");
                } else {
                    eprintln!("FAIL");
                    #[cfg(target_os = "macos")]
                    {
                        let expected = PathBuf::from(format!(
                            "/Library/Audio/Plug-Ins/Components/{}.component",
                            p.name
                        ));
                        warn_on_au_collision(
                            p.resolved_au_type(),
                            p.resolved_fourcc(),
                            &config.vendor.au_manufacturer,
                            &expected,
                        );
                    }
                    failures += 1;
                }
            }
        } else {
            eprintln!("  auval not found (macOS only)");
        }
    }

    // --- auval (AU v3 appex) ---
    if run_auval_v3 {
        eprintln!("\n=== auval (AU v3) ===\n");
        if Command::new("auval").arg("-h").output().is_ok() {
            for p in &plugins {
                let sub = p.au3_sub();
                eprint!(
                    "  {} ({} {} {}) ... ",
                    p.name,
                    p.resolved_au_type(),
                    sub,
                    config.vendor.au_manufacturer
                );
                let output = Command::new("auval")
                    .args([
                        "-v",
                        p.resolved_au_type(),
                        sub,
                        &config.vendor.au_manufacturer,
                    ])
                    .output()?;
                let stdout = String::from_utf8_lossy(&output.stdout);
                if stdout.contains("VALIDATION SUCCEEDED") {
                    eprintln!("PASS");
                } else {
                    eprintln!("FAIL");
                    #[cfg(target_os = "macos")]
                    {
                        let expected = PathBuf::from(format!(
                            "/Applications/{}.app/Contents/PlugIns/AUExt.appex",
                            p.au3_app_name()
                        ));
                        warn_on_au_collision(
                            p.resolved_au_type(),
                            sub,
                            &config.vendor.au_manufacturer,
                            &expected,
                        );
                    }
                    failures += 1;
                }
            }
        } else {
            eprintln!("  auval not found (macOS only)");
        }
    }

    // --- pluginval (VST3) ---
    if run_pluginval {
        eprintln!("\n=== pluginval (VST3) ===\n");
        let pluginval = find_pluginval();
        if let Some(pv) = pluginval {
            for p in &plugins {
                let user_path = InstallScope::User
                    .vst3_dir()
                    .join(format!("{}.vst3", p.name));
                let system_path = InstallScope::System
                    .vst3_dir()
                    .join(format!("{}.vst3", p.name));
                // Validate the system bundle when it's there (the
                // historical default), else fall through to user.
                let validate_path = if system_path.exists() {
                    system_path.clone()
                } else if user_path.exists() {
                    user_path.clone()
                } else {
                    eprintln!("  {} ... SKIP (not installed)", p.name);
                    continue;
                };
                eprint!("  {} ... ", p.name);
                let output = Command::new(&pv)
                    .args([
                        "--validate",
                        validate_path.to_str().unwrap(),
                        "--strictness-level",
                        "5",
                    ])
                    .output()?;
                let stdout = String::from_utf8_lossy(&output.stdout);
                if stdout.contains("SUCCESS") || output.status.success() {
                    eprintln!("PASS");
                } else {
                    eprintln!("FAIL");
                    failures += 1;
                }
                warn_on_scope_collision("VST3", &user_path, &system_path);
            }
        } else {
            eprintln!("  pluginval not found. Install from https://github.com/Tracktion/pluginval");
        }
    }

    // --- clap-validator (CLAP) ---
    if run_clap {
        eprintln!("\n=== clap-validator (CLAP) ===\n");
        let clap_validator = find_clap_validator();
        if let Some(cv) = clap_validator {
            // Project-local scratch. `cargo clean` sweeps it, and it
            // stays off the system `/tmp` so nothing outside the repo
            // gets touched.
            let scratch = tmp_dir().join("clap-validate");
            let _ = fs::create_dir_all(&scratch);

            for p in &plugins {
                let clap_name = format!("{}.clap", p.name);
                let user_path = InstallScope::User.clap_dir().join(&clap_name);
                let system_path = InstallScope::System.clap_dir().join(&clap_name);
                // Prefer the user-scope bundle (today's default); fall
                // through to system-scope if the user installed there.
                let installed = if user_path.exists() {
                    user_path.clone()
                } else {
                    system_path.clone()
                };

                if !installed.exists() {
                    eprintln!("  {} ... SKIP (not installed)", p.name);
                    continue;
                }

                // clap-validator requires bundle format (Plugin.clap/Contents/MacOS/Plugin).
                // If the installed file is a bare dylib, create a temporary bundle.
                let validate_path = if installed.join("Contents/MacOS").is_dir() {
                    installed.clone()
                } else {
                    let bundle = scratch.join(&clap_name);
                    let macos = bundle.join("Contents/MacOS");
                    let _ = fs::create_dir_all(&macos);
                    let bin_name = clap_name.trim_end_matches(".clap");
                    let _ = fs::copy(&installed, macos.join(bin_name));
                    bundle
                };

                eprint!("  {} ... ", p.name);
                let output = Command::new(&cv)
                    .args(["validate", &validate_path.to_string_lossy()])
                    .output()?;

                let stdout = String::from_utf8_lossy(&output.stdout);
                let stderr = String::from_utf8_lossy(&output.stderr);
                let combined = format!("{stdout}{stderr}");

                if output.status.success() && !combined.contains("FAILED") {
                    // Count passed/failed from output
                    let passed = combined.matches("passed").count();
                    eprintln!("PASS ({passed} tests)");
                } else {
                    eprintln!("FAIL");
                    if !stdout.is_empty() {
                        eprintln!("{stdout}");
                    }
                    if !stderr.is_empty() {
                        eprintln!("{stderr}");
                    }
                    failures += 1;
                }
                warn_on_scope_collision("CLAP", &user_path, &system_path);
            }

            let _ = fs::remove_dir_all(&scratch);
        } else {
            eprintln!("  clap-validator not found.");
            eprintln!(
                "  Install: cargo install --git https://github.com/free-audio/clap-validator"
            );
            eprintln!("  Or set CLAP_VALIDATOR=/path/to/clap-validator");
        }
    }

    // --- VST2 binary smoke (no industry validator; this is ours) ---
    if run_vst2 {
        eprintln!("=== VST2 binary smoke ===\n");
        #[cfg(target_os = "macos")]
        {
            failures += validate_vst2_macos(&plugins);
        }
        #[cfg(not(target_os = "macos"))]
        {
            eprintln!("  Skipping: VST2 binary smoke is currently macOS-only.");
            let _ = &plugins;
        }
    }

    eprintln!();
    if failures > 0 {
        Err(format!("{failures} validation(s) failed").into())
    } else {
        eprintln!("All validations passed.");
        Ok(())
    }
}

fn print_help() {
    eprintln!(
        "\
Usage: cargo truce validate [--auval] [--auval3] [--pluginval] [--clap] [--vst2]
                            [--all] [-p <crate>]

Run validation tools on installed plugins. With no flag, runs every
available validator.

Options:
  --auval          AU v2 validation via auval (macOS).
  --auval3         AU v3 validation via auval (macOS).
  --pluginval      VST3 validation via pluginval.
  --clap           CLAP validation via clap-validator.
  --vst2           VST2 dlopen + AEffect smoke (macOS).
  --all            Run every available validator (default).
  -p <crate>       Validate only the plugin with this cargo crate name.
  -h, --help       Show this message"
    );
}

/// Build each plugin as a VST2 dylib, dlopen it via the C smoke binary
/// at `crates/truce-vst2/validate/binary_smoke.c`, and verify
/// `VSTPluginMain` returns a well-formed `AEffect`. macOS-only because
/// the smoke binary uses `dlfcn.h` and we hardcode `.dylib` here.
/// Returns the failure count.
#[cfg(target_os = "macos")]
fn validate_vst2_macos(plugins: &[&PluginDef]) -> usize {
    let root = project_root();
    let test_src = root.join("crates/truce-vst2/validate/binary_smoke.c");
    if !test_src.exists() {
        eprintln!(
            "  Skipping: smoke source missing at {}.",
            test_src.display()
        );
        return 0;
    }

    let test_bin = crate::target_dir(&root).join("vst2_binary_smoke");
    let cc_status = match Command::new("cc")
        .args(["-o", test_bin.to_str().unwrap(), test_src.to_str().unwrap()])
        .status()
    {
        Ok(s) => s,
        Err(e) => {
            eprintln!("  Skipping: failed to invoke cc: {e}");
            return 0;
        }
    };
    if !cc_status.success() {
        eprintln!("  Skipping: cc failed to build the smoke binary.");
        return 0;
    }

    let mut failures = 0;
    for p in plugins {
        // Cross-scope collision check first — visible regardless of
        // whether the smoke binary builds. Two installed `.vst` bundles
        // are valid on disk but only one will be loaded by any given
        // host scan.
        let user_path = InstallScope::User
            .vst2_dir()
            .join(format!("{}.vst", p.name));
        let system_path = InstallScope::System
            .vst2_dir()
            .join(format!("{}.vst", p.name));
        warn_on_scope_collision("VST2", &user_path, &system_path);

        eprint!("  {} ... ", p.name);
        let build = Command::new("cargo")
            .args([
                "build",
                "--release",
                "-p",
                &p.crate_name,
                "--no-default-features",
                "--features",
                "vst2",
            ])
            .env("MACOSX_DEPLOYMENT_TARGET", deployment_target())
            .output();
        let build = match build {
            Ok(o) => o,
            Err(e) => {
                eprintln!("BUILD ERROR ({e})");
                failures += 1;
                continue;
            }
        };
        if !build.status.success() {
            eprintln!("BUILD FAILED");
            eprint!("{}", String::from_utf8_lossy(&build.stderr));
            failures += 1;
            continue;
        }

        let dylib = crate::target_dir(&root).join(format!("release/lib{}.dylib", p.dylib_stem()));
        // AU type tag is the same code path that drives plugin-kind
        // detection elsewhere: `aumu` → synth, `aumi` → MIDI/note
        // effect, anything else → audio effect.
        let kind_flag: Option<&str> = match p.resolved_au_type() {
            "aumu" => Some("--synth"),
            "aumi" => Some("--midi-effect"),
            _ => None,
        };
        let mut cmd = Command::new(test_bin.to_str().unwrap());
        cmd.arg(dylib.to_str().unwrap());
        if let Some(flag) = kind_flag {
            cmd.arg(flag);
        }
        match cmd.output() {
            Ok(out) => {
                let stdout = String::from_utf8_lossy(&out.stdout);
                if out.status.success() {
                    if let Some(line) = stdout.lines().last() {
                        eprintln!("{line}");
                    } else {
                        eprintln!("PASS");
                    }
                } else {
                    eprintln!("FAIL");
                    eprint!("{stdout}");
                    failures += 1;
                }
            }
            Err(e) => {
                eprintln!("INVOKE ERROR ({e})");
                failures += 1;
            }
        }
    }
    failures
}

fn find_pluginval() -> Option<String> {
    // Check common locations
    let candidates = [
        "/Applications/pluginval.app/Contents/MacOS/pluginval",
        "/usr/local/bin/pluginval",
    ];
    for c in candidates {
        if Path::new(c).exists() {
            return Some(c.to_string());
        }
    }
    // Check PATH
    if Command::new("pluginval").arg("--help").output().is_ok() {
        return Some("pluginval".to_string());
    }
    None
}

fn find_clap_validator() -> Option<String> {
    // Check env var override
    if let Ok(path) = std::env::var("CLAP_VALIDATOR")
        && Path::new(&path).exists()
    {
        return Some(path);
    }
    // Check PATH
    if Command::new("clap-validator")
        .arg("--version")
        .output()
        .is_ok()
    {
        return Some("clap-validator".to_string());
    }
    // Check cargo install location
    if let Some(home) = dirs::home_dir() {
        let cargo_bin = home.join(".cargo/bin/clap-validator");
        if cargo_bin.exists() {
            return Some(cargo_bin.to_string_lossy().into());
        }
    }
    None
}