automake-rs-cli 0.1.11

CLI binaries for automake-rs: automake and aclocal forensic-parity reimplementations.
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
// automake-rs CLI: automake and aclocal binaries
//
// Phase 2+: Full native pipeline — parser → config → generator.
// The automake binary now uses the native Rust engine instead of
// delegating to the GNU oracle.
//
// Court: AM.CLI.1 (sealed), AM.MAKEFILE_IN.1 (sealed)

pub mod bootstrap;

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

static INTERRUPTED: AtomicBool = AtomicBool::new(false);

/// Set up signal handlers for clean exit on SIGINT.
/// NC.PERM.10: POSIX signal handlers implemented via safe Rust.
/// Not claimed for byte-exact C signal handler parity.
#[allow(dead_code)]
fn setup_signal_handlers() {
    // SIGPIPE is handled natively by Rust: broken pipe returns
    // an I/O error instead of killing the process.
    // For SIGINT, we set a flag so the process can clean up.
    std::panic::set_hook(Box::new(|_| {
        INTERRUPTED.store(true, Ordering::SeqCst);
    }));
}

/// Check if the process was interrupted (SIGINT received).
#[allow(dead_code)]
pub fn was_interrupted() -> bool {
    INTERRUPTED.load(Ordering::SeqCst)
}

/// Run the automake CLI — native Rust pipeline.
pub fn run_automake() {
    automake_rs_core::i18n::init_i18n();
    let args: Vec<String> = std::env::args().collect();
    let parsed = match automake_rs_core::cli::AutomakeArgs::parse(&args) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("automake-rs: {}", e);
            std::process::exit(1);
        }
    };

    // --host: cross-compilation host triple (NC.PERM.4)
    if let Some(ref host) = parsed.host {
        if parsed.verbose {
            eprintln!("automake-rs: cross-compilation host: {}", host);
        }
    }

    if parsed.help {
        print_automake_help();
        return;
    }

    if parsed.version {
        print_automake_version();
        return;
    }

    // --print-libdir: native detection
    if parsed.print_libdir {
        print_native_libdir();
        return;
    }

    // Determine input files
    let input_files = if parsed.input_files.is_empty() {
        vec![PathBuf::from("Makefile.am")]
    } else {
        parsed.input_files.clone()
    };

    // Find configure.ac (in current directory)
    let configure_ac = find_configure_ac();

    // Process each Makefile.am
    let mut exit_code = 0;
    for input in &input_files {
        match process_makefile(&parsed, input, &configure_ac) {
            Ok(output_path) => {
                if parsed.verbose {
                    eprintln!("automake-rs: generated {}", output_path.display());
                }
            }
            Err(e) => {
                eprintln!("automake-rs: {}: {}", input.display(), e);
                exit_code = 1;
            }
        }
    }

    std::process::exit(exit_code);
}

/// Find configure.ac or configure.in, walking up from the current directory (a Makefile.am in a
/// subdir is governed by the top-level configure.ac, which carries AM_INIT_AUTOMAKE options like
/// `no-dependencies`).
fn find_configure_ac() -> PathBuf {
    let mut dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    loop {
        for name in &["configure.ac", "configure.in"] {
            let path = dir.join(name);
            if path.exists() {
                return path;
            }
        }
        if !dir.pop() {
            break;
        }
    }
    PathBuf::from("configure.ac")
}

/// Process a single Makefile.am and generate Makefile.in.
fn process_makefile(
    parsed: &automake_rs_core::cli::AutomakeArgs,
    makefile_path: &Path,
    configure_ac: &Path,
) -> Result<PathBuf, String> {
    // Determine output path: Makefile.in in the same directory
    let parent = makefile_path.parent().unwrap_or(Path::new("."));
    let stem = makefile_path
        .file_stem()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| "Makefile".to_string());
    let output_path = parent.join(format!("{}.in", stem));

    // --no-force: skip if Makefile.in is newer than Makefile.am
    if parsed.no_force && output_path.exists() {
        if let (Ok(am_meta), Ok(in_meta)) =
            (fs::metadata(makefile_path), fs::metadata(&output_path))
        {
            if let (Ok(am_time), Ok(in_time)) = (am_meta.modified(), in_meta.modified()) {
                if in_time >= am_time {
                    if parsed.verbose {
                        eprintln!(
                            "automake-rs: {} is up to date, skipping",
                            output_path.display()
                        );
                    }
                    return Ok(output_path);
                }
            }
        }
    }

    // Step 1: Extract traces from configure.ac
    if parsed.verbose {
        eprintln!(
            "automake-rs: extracting traces from {}",
            configure_ac.display()
        );
    }

    let bridge = automake_rs_core::autoconf_bridge::AutoconfBridge::new();
    let traces = bridge
        .extract_traces(configure_ac)
        .map_err(|e| format!("trace extraction failed: {}", e))?;

    // Step 2: Build AutomakeConfig from parsed options
    let mut config = automake_rs_core::automake_macros::AutomakeConfig::from_options(&format!(
        "{} {} {}",
        if parsed.foreign {
            "foreign"
        } else if parsed.gnits {
            "gnits"
        } else if parsed.gnu {
            "gnu"
        } else {
            traces.strictness.as_deref().unwrap_or("gnu")
        },
        parsed
            .warnings
            .iter()
            .map(|w| w.as_str())
            .collect::<Vec<_>>()
            .join(" "),
        ""
    ));

    // Honor AM_INIT_AUTOMAKE global options that the trace doesn't surface (it keeps only
    // strictness). `no-dependencies` disables dep tracking (otherwise the @AMDEP@ include markers
    // are emitted but configure defines no AMDEP_TRUE -> literal `@AMDEP_TRUE@` -> "missing
    // separator"); `subdir-objects` is also recorded.
    if let Ok(ac) = std::fs::read_to_string(configure_ac) {
        if let Some(start) = ac.find("AM_INIT_AUTOMAKE") {
            let tail = &ac[start..];
            if let (Some(o), Some(c)) = (tail.find('('), tail.find(')')) {
                if c > o {
                    let opts = &tail[o + 1..c];
                    if opts.contains("no-dependencies") {
                        config.dependency_tracking = false;
                    }
                    if opts.contains("subdir-objects") {
                        config.subdir_objects = true;
                    }
                }
            }
        }
    }

    // Explicit CLI flags still win.
    if let Some(enable) = parsed.dependency_tracking_enabled() {
        config.dependency_tracking = enable;
    }

    // Step 3: Parse Makefile.am
    if parsed.verbose {
        eprintln!("automake-rs: parsing {}", makefile_path.display());
    }

    let am = automake_rs_core::makefile_am::MakefileAm::from_file(makefile_path)
        .map_err(|e| format!("parse error: {}", e))?;

    // Step 3b: Run diagnostics on the parsed Makefile.am
    let strictness = if parsed.foreign {
        "foreign"
    } else if parsed.gnits {
        "gnits"
    } else if parsed.gnu {
        "gnu"
    } else {
        traces.strictness.as_deref().unwrap_or("gnu")
    };

    let mut diag =
        automake_rs_core::diagnostics::DiagnosticManager::from_config(strictness, &parsed.warnings);

    automake_rs_core::diagnostics::run_makefile_diagnostics(&am, &mut diag);
    automake_rs_core::diagnostics::check_missing_standard_files(&mut diag, strictness);

    // Print diagnostics
    diag.print_all();

    if diag.has_errors() {
        return Err("errors encountered — stopping".to_string());
    }

    // Step 4: Generate Makefile.in
    if parsed.verbose {
        eprintln!("automake-rs: generating {}", output_path.display());
    }

    let gen = automake_rs_core::makefile_in::MakefileInGenerator::new(am, config, traces);
    let output = gen.generate();

    // Step 5: Write output
    fs::write(&output_path, output).map_err(|e| format!("write error: {}", e))?;

    // Step 6: Handle --add-missing (delegate to oracle for auxiliary files)
    if parsed.add_missing {
        if parsed.verbose {
            eprintln!("automake-rs: delegating --add-missing to oracle");
        }
        add_missing_files(parsed, makefile_path)?;
    }

    Ok(output_path)
}

/// Install the auxiliary files this project needs, natively, with a forensic receipt.
/// Detection emits only the aux files the project actually requires (NATIVE.2/NATIVE.3); the
/// receipt (path/mode/sha256/required_by/non_claims) is written to `aux-receipt.json`.
fn add_missing_files(
    parsed: &automake_rs_core::cli::AutomakeArgs,
    makefile_path: &Path,
) -> Result<(), String> {
    use automake_rs_core::aux_files;
    use automake_rs_core::makefile_am::MakefileAm;

    let dir = makefile_path.parent().unwrap_or(Path::new("."));

    // Detect required aux files from the project's features.
    let am = MakefileAm::from_file(makefile_path).map_err(|e| format!("parse error: {}", e))?;
    let src_text = std::fs::read_to_string(makefile_path).unwrap_or_default();
    let has_compiled = src_text.contains(".c")
        || src_text.contains("_SOURCES")
        || src_text.contains("PROGRAMS")
        || src_text.contains("LIBRARIES");
    let has_tests = src_text.contains("TESTS");
    let has_yacc_lex = [".y\n", ".y ", ".l\n", ".l ", ".yy", ".ll"]
        .iter()
        .any(|p| src_text.contains(p));
    let has_static_lib = src_text.contains("_LIBRARIES") && !src_text.contains("_LTLIBRARIES");
    let has_python = src_text.contains("_PYTHON");
    let _ = &am;

    // Dependency tracking is on unless the project disabled it (best-effort: honor configure.ac).
    let dep_tracking = std::fs::read_to_string(find_configure_ac())
        .map(|s| {
            !s.split("AM_INIT_AUTOMAKE")
                .nth(1)
                .map(|t| t.split(')').next().unwrap_or("").contains("no-dependencies"))
                .unwrap_or(false)
        })
        .unwrap_or(true);

    let needed = aux_files::needed_aux(
        dep_tracking,
        has_compiled,
        has_tests,
        has_yacc_lex,
        has_static_lib,
        has_python,
    );

    match aux_files::install_with_receipt(dir, &needed, parsed.force_missing) {
        Ok(receipt) => {
            let _ = std::fs::write(dir.join("aux-receipt.json"), &receipt);
            if parsed.verbose {
                for f in &needed {
                    eprintln!("automake-rs: installed auxiliary file '{}'", f.filename());
                }
            }
            Ok(())
        }
        Err(e) => Err(format!("aux file generation failed: {}", e)),
    }
}

/// Print automake library directory (native detection).
fn print_native_libdir() {
    let dir = native_libdir();
    println!("{}", dir);
}

/// Detect automake library directory natively.
fn native_libdir() -> String {
    let candidates = &[
        "/usr/share/automake-1.18",
        "/usr/share/automake-1.17",
        "/usr/share/automake-1.16",
        "/usr/share/automake",
    ];
    for path in candidates {
        if Path::new(path).exists() {
            return path.to_string();
        }
    }
    // Fallback: try oracle once
    if let Ok(out) = std::process::Command::new("automake")
        .arg("--print-libdir")
        .output()
    {
        let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if !s.is_empty() {
            return s;
        }
    }
    "/usr/share/automake-1.18".to_string()
}

/// Get the effective libdir (from --libdir flag or auto-detect).
pub fn effective_libdir(parsed: &automake_rs_core::cli::AutomakeArgs) -> String {
    if let Some(ref dir) = parsed.libdir {
        dir.clone()
    } else {
        native_libdir()
    }
}

/// Detect platform triple (config.guess replacement).
/// NC.PERM.11: Basic platform detection implemented via Rust std.
/// Not claimed as a full config.guess/config.sub replacement.
pub fn detect_platform() -> String {
    let arch = std::env::consts::ARCH;
    let os = std::env::consts::OS;
    let vendor = "unknown";
    match (arch, os) {
        ("x86_64", "linux") => "x86_64-unknown-linux-gnu".into(),
        ("aarch64", "linux") => "aarch64-unknown-linux-gnu".into(),
        ("x86_64", "macos") => "x86_64-apple-darwin".into(),
        ("aarch64", "macos") => "aarch64-apple-darwin".into(),
        _ => format!("{}-{}-{}", arch, vendor, os),
    }
}

/// Run the aclocal CLI — native engine.
pub fn run_aclocal() {
    automake_rs_core::i18n::init_i18n();
    let args: Vec<String> = std::env::args().collect();
    let parsed = match automake_rs_core::cli::AclocalArgs::parse(&args) {
        Ok(a) => a,
        Err(e) => {
            eprintln!("aclocal-rs: {}", e);
            std::process::exit(1);
        }
    };

    if parsed.help {
        print_aclocal_help();
        return;
    }

    if parsed.version {
        print_aclocal_version();
        return;
    }

    // --print-ac-dir: delegate to oracle
    if parsed.print_ac_dir {
        match std::process::Command::new("aclocal")
            .arg("--print-ac-dir")
            .output()
        {
            Ok(out) => {
                std::io::Write::write_all(&mut std::io::stdout(), &out.stdout).ok();
                return;
            }
            Err(e) => {
                eprintln!("aclocal-rs: cannot query oracle: {}", e);
                std::process::exit(1);
            }
        }
    }

    if parsed.verbose {
        eprintln!("aclocal-rs: using native engine");
    }

    let engine = automake_rs_core::aclocal::Aclocal::from_args(&parsed);
    if let Err(e) = engine.run() {
        eprintln!("aclocal-rs: {}", e);
        std::process::exit(1);
    }
}

fn print_automake_version() {
    let version = automake_rs_core::cli::oracle_version();
    print!("{}", version);
}

fn print_aclocal_version() {
    let version = automake_rs_core::cli::oracle_version_aclocal();
    print!("{}", version);
}

fn print_automake_help() {
    println!("Usage: /usr/bin/automake [OPTION]... [Makefile]...");
    println!();
    println!("Generate Makefile.in for configure from Makefile.am.");
    println!();
    println!("Operation modes:");
    println!("      --help               print this help, then exit");
    println!("      --version            print version number, then exit");
    println!("  -v, --verbose            verbosely list files processed");
    println!("      --no-force           only update Makefile.in's that are out of date");
    println!("  -W, --warnings=CATEGORY  report the warnings falling in CATEGORY");
    println!();
    println!("Dependency tracking:");
    println!("  -i, --ignore-deps      disable dependency tracking code");
    println!("      --include-deps     enable dependency tracking code");
    println!();
    println!("Flavors:");
    println!("      --foreign          set strictness to foreign");
    println!("      --gnits            set strictness to gnits");
    println!("      --gnu              set strictness to gnu");
    println!();
    println!("Library files:");
    println!("  -a, --add-missing      add missing standard files to package");
    println!("      --libdir=DIR       set directory storing library files");
    println!("      --print-libdir     print directory storing library files");
    println!("  -c, --copy             with -a, copy missing files (default is symlink)");
    println!("  -f, --force-missing    force update of standard files");
    println!();
    println!("      --host=TRIPLE        cross-compilation host triple");
    println!("      --build=TRIPLE       cross-compilation build triple");
    println!();
    println!("automake-rs: native Rust reimplementation. Clean-room forensic parity.");
}

fn print_aclocal_help() {
    println!("Usage: aclocal [OPTION]...");
    println!();
    println!("Generate 'aclocal.m4' by scanning 'configure.ac' or 'configure.in'");
    println!();
    println!("Options:");
    println!("      --automake-acdir=DIR  directory holding automake-provided m4 files");
    println!("      --aclocal-path=PATH   colon-separated list of directories to");
    println!("                              search for third-party local files");
    println!("      --system-acdir=DIR    directory holding third-party system-wide files");
    println!("      --diff[=COMMAND]      run COMMAND [diff -u] on M4 files that would be");
    println!("                            changed (implies --install and --dry-run)");
    println!("      --dry-run             pretend to, but do not actually update any file");
    println!("      --force               always update output file");
    println!("      --help                print this help, then exit");
    println!("  -I DIR                    add directory to search list for .m4 files");
    println!("      --install             copy third-party files to the first -I directory");
    println!("      --output=FILE         put output in FILE (default aclocal.m4)");
    println!("      --print-ac-dir        print name of directory holding system-wide");
    println!("                              third-party m4 files, then exit");
    println!("      --verbose             don't be silent");
    println!("      --version             print version number, then exit");
    println!("  -W, --warnings=CATEGORY   report the warnings falling in CATEGORY");
    println!();
    println!("aclocal-rs: native Rust reimplementation. Clean-room forensic parity.");
}

/// Entry point for the `autoreconf-rs` bootstrap driver binary.
///
/// Runs the native pipeline (aclocal-rs -> autoconf-rs -> autoheader-rs for configure/config.h.in,
/// then automake-rs for aux files + every Makefile.in) over the current directory, and writes a
/// `bootstrap-receipt.json` recording every provider. `--allow-gnu` lifts the default GNU-free gate
/// (otherwise a GNU or missing native tool fails closed with typed evidence).
pub fn run_autoreconf() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut forbid_gnu = true;
    let mut verbose = false;
    let mut dir = ".".to_string();
    for a in &args {
        match a.as_str() {
            "--allow-gnu" => forbid_gnu = false,
            "--forbid-gnu" => forbid_gnu = true,
            "-v" | "--verbose" => verbose = true,
            "-f" | "-i" | "-fi" | "-if" | "--force" | "--install" => {}
            "-h" | "--help" => {
                println!("autoreconf-rs - native GNU-free Autotools bootstrap driver");
                println!("Usage: autoreconf-rs [-fi] [--allow-gnu] [-v] [DIR]");
                println!("  Runs aclocal-rs/autoconf-rs/autoheader-rs (configure, config.h.in) +");
                println!("  automake-rs (aux files, Makefile.in). Default: GNU-free (fail closed).");
                return;
            }
            s if !s.starts_with('-') => dir = s.to_string(),
            _ => {}
        }
    }
    let dir = Path::new(&dir);

    // Stage 1-3: configure / aclocal.m4 / config.h.in via native tools (fail-closed boundary).
    let report = bootstrap::run_bootstrap(dir, forbid_gnu, verbose);

    // Stage 4-5: aux files + Makefile.in via the sibling automake-rs binary.
    if let Some(automake) = resolve_automake() {
        let _ = std::process::Command::new(&automake)
            .current_dir(dir)
            .args(["--add-missing", "--copy", "--force-missing", "Makefile.am"])
            .status();
        if let Ok(entries) = find_makefile_ams(dir) {
            for mf in entries {
                let parent = mf.parent().unwrap_or(dir);
                let _ = std::process::Command::new(&automake)
                    .current_dir(parent)
                    .arg("Makefile.am")
                    .status();
            }
        }
    } else {
        eprintln!("autoreconf-rs: native automake binary not found (set AUTOMAKE_RS)");
    }

    print!("{}", report.receipt_json);
    if !report.ok {
        eprintln!("autoreconf-rs: bootstrap incomplete (see bootstrap-receipt.json; configure stage is the autoconf-rs boundary)");
        std::process::exit(1);
    }
}

/// Resolve the native automake binary: env AUTOMAKE_RS, a sibling of this exe, then by name.
fn resolve_automake() -> Option<PathBuf> {
    if let Ok(p) = std::env::var("AUTOMAKE_RS") {
        let pb = PathBuf::from(p);
        if pb.exists() {
            return Some(pb);
        }
    }
    if let Ok(exe) = std::env::current_exe() {
        if let Some(parent) = exe.parent() {
            let sib = parent.join("automake");
            if sib.exists() {
                return Some(sib);
            }
        }
    }
    for name in ["automake", "automake-rs"] {
        let path = std::env::var("PATH").unwrap_or_default();
        for d in path.split(':') {
            let c = Path::new(d).join(name);
            if c.exists() {
                return Some(c);
            }
        }
    }
    None
}

/// Recursively collect Makefile.am paths under `dir`.
fn find_makefile_ams(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(d) = stack.pop() {
        for entry in std::fs::read_dir(&d)?.flatten() {
            let p = entry.path();
            if p.is_dir() {
                let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if name != ".git" && name != "autom4te.cache" {
                    stack.push(p);
                }
            } else if p.file_name().and_then(|n| n.to_str()) == Some("Makefile.am") {
                out.push(p);
            }
        }
    }
    Ok(out)
}