alef-cli 0.7.1

CLI for the alef polyglot binding generator
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use alef_core::config::{AlefConfig, Language};
use anyhow::Context as _;
use rayon::prelude::*;
use std::path::Path;
use tracing::{debug, info};

use crate::registry;

use super::helpers::{check_precondition, run_before, run_command, run_command_captured};

/// Which lint phases to execute.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LintPhase {
    Format,
    Check,
    Typecheck,
}

/// Filter languages through precondition and before hooks for lint/fmt.
///
/// Returns the subset of languages whose precondition passed (or was absent).
/// Runs before hooks for each passing language. Fails if any before hook fails.
fn prepare_lint_languages(config: &AlefConfig, languages: &[Language]) -> anyhow::Result<Vec<Language>> {
    let mut ready = Vec::with_capacity(languages.len());
    for &lang in languages {
        let lang_lint = config.lint_config_for_language(lang);
        if !check_precondition(lang, lang_lint.precondition.as_deref()) {
            continue;
        }
        run_before(lang, lang_lint.before.as_ref())?;
        ready.push(lang);
    }
    Ok(ready)
}

/// Run a single lint phase across all languages in parallel.
fn run_phase(config: &AlefConfig, languages: &[Language], phase: LintPhase) -> anyhow::Result<()> {
    let tasks: Vec<(&Language, String)> = languages
        .iter()
        .filter_map(|lang| {
            let lang_lint = config.lint_config_for_language(*lang);
            let cmds = match phase {
                LintPhase::Format => lang_lint.format,
                LintPhase::Check => lang_lint.check,
                LintPhase::Typecheck => lang_lint.typecheck,
            };
            cmds.map(|cmd_list| {
                cmd_list
                    .commands()
                    .into_iter()
                    .map(|c| (lang, c.to_string()))
                    .collect::<Vec<_>>()
            })
        })
        .flatten()
        .collect();

    let results: Vec<anyhow::Result<(String, String, String)>> = tasks
        .par_iter()
        .map(|(_, cmd)| {
            let (stdout, stderr) = run_command_captured(cmd)?;
            Ok((cmd.clone(), stdout, stderr))
        })
        .collect();

    let mut first_error: Option<anyhow::Error> = None;
    for result in results {
        match result {
            Ok((cmd, stdout, stderr)) => {
                if !stdout.is_empty() {
                    info!("[{cmd}] stdout:\n{stdout}");
                }
                if !stderr.is_empty() {
                    info!("[{cmd}] stderr:\n{stderr}");
                }
            }
            Err(e) => {
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
    }
    if let Some(e) = first_error {
        return Err(e);
    }

    Ok(())
}

/// Run all configured lint/format commands on generated output.
///
/// Executes in two waves for correctness:
/// 1. Format (all languages in parallel) — normalizes code first
/// 2. Check + Typecheck (all languages in parallel) — validates normalized code
pub fn lint(config: &AlefConfig, languages: &[Language]) -> anyhow::Result<()> {
    let ready = prepare_lint_languages(config, languages)?;
    // Wave 1: format all languages in parallel
    run_phase(config, &ready, LintPhase::Format)?;
    // Wave 2: check + typecheck all languages in parallel
    run_phase(config, &ready, LintPhase::Check)?;
    run_phase(config, &ready, LintPhase::Typecheck)?;
    Ok(())
}

/// Run only format commands on generated output.
pub fn fmt(config: &AlefConfig, languages: &[Language]) -> anyhow::Result<()> {
    let ready = prepare_lint_languages(config, languages)?;
    run_phase(config, &ready, LintPhase::Format)
}

/// Update dependencies for each language.
///
/// When `latest` is true, runs the aggressive `upgrade` commands (including
/// incompatible/major version bumps). Otherwise runs the safe `update` commands.
pub fn update(config: &AlefConfig, languages: &[Language], latest: bool) -> anyhow::Result<()> {
    let results: Vec<anyhow::Result<Vec<(String, String, String)>>> = languages
        .par_iter()
        .map(|lang| {
            let update_cfg = config.update_config_for_language(*lang);
            if !check_precondition(*lang, update_cfg.precondition.as_deref()) {
                return Ok(Vec::new());
            }
            run_before(*lang, update_cfg.before.as_ref())?;
            let cmds = if latest {
                update_cfg.upgrade.as_ref()
            } else {
                update_cfg.update.as_ref()
            };
            let mut outputs = Vec::new();
            if let Some(cmd_list) = cmds {
                for cmd in cmd_list.commands() {
                    let (stdout, stderr) = run_command_captured(cmd)?;
                    outputs.push((cmd.to_string(), stdout, stderr));
                }
            }
            Ok(outputs)
        })
        .collect();

    let mut first_error: Option<anyhow::Error> = None;
    for result in results {
        match result {
            Ok(outputs) => {
                for (cmd, stdout, stderr) in outputs {
                    if !stdout.is_empty() {
                        info!("[{cmd}] stdout:\n{stdout}");
                    }
                    if !stderr.is_empty() {
                        info!("[{cmd}] stderr:\n{stderr}");
                    }
                }
            }
            Err(e) => {
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
    }
    if let Some(e) = first_error {
        return Err(e);
    }

    Ok(())
}

/// Run configured test commands for each language.
///
/// When `coverage` is true, runs coverage commands instead of regular test commands.
/// When `e2e` is true, also runs e2e test commands.
pub fn test(config: &AlefConfig, languages: &[Language], e2e: bool, coverage: bool) -> anyhow::Result<()> {
    let results: Vec<anyhow::Result<Vec<(String, String, String)>>> = languages
        .par_iter()
        .map(|lang| {
            let lang_test = config.test_config_for_language(*lang);
            if !check_precondition(*lang, lang_test.precondition.as_deref()) {
                return Ok(Vec::new());
            }
            run_before(*lang, lang_test.before.as_ref())?;
            let mut outputs = Vec::new();

            // Use coverage commands when --coverage flag is set, fall back to regular test
            let test_cmds = if coverage {
                lang_test.coverage.as_ref().or(lang_test.command.as_ref())
            } else {
                lang_test.command.as_ref()
            };

            if let Some(cmd_list) = test_cmds {
                for cmd in cmd_list.commands() {
                    let (stdout, stderr) = run_command_captured(cmd)?;
                    outputs.push((cmd.to_string(), stdout, stderr));
                }
            }
            if e2e {
                if let Some(e2e_cmd_list) = &lang_test.e2e {
                    for cmd in e2e_cmd_list.commands() {
                        let (stdout, stderr) = run_command_captured(cmd)?;
                        outputs.push((cmd.to_string(), stdout, stderr));
                    }
                }
            }

            Ok(outputs)
        })
        .collect();

    let mut first_error: Option<anyhow::Error> = None;
    for result in results {
        match result {
            Ok(outputs) => {
                for (cmd, stdout, stderr) in outputs {
                    if !stdout.is_empty() {
                        info!("[{cmd}] stdout:\n{stdout}");
                    }
                    if !stderr.is_empty() {
                        info!("[{cmd}] stderr:\n{stderr}");
                    }
                }
            }
            Err(e) => {
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
    }
    if let Some(e) = first_error {
        return Err(e);
    }

    Ok(())
}

/// Install dependencies for each language.
pub fn setup(config: &AlefConfig, languages: &[Language]) -> anyhow::Result<()> {
    let results: Vec<anyhow::Result<Vec<(String, String, String)>>> = languages
        .par_iter()
        .map(|lang| {
            let setup_cfg = config.setup_config_for_language(*lang);
            if !check_precondition(*lang, setup_cfg.precondition.as_deref()) {
                return Ok(Vec::new());
            }
            run_before(*lang, setup_cfg.before.as_ref())?;
            let mut outputs = Vec::new();
            if let Some(cmd_list) = &setup_cfg.install {
                for cmd in cmd_list.commands() {
                    let (stdout, stderr) = run_command_captured(cmd)?;
                    outputs.push((cmd.to_string(), stdout, stderr));
                }
            }
            Ok(outputs)
        })
        .collect();

    let mut first_error: Option<anyhow::Error> = None;
    for result in results {
        match result {
            Ok(outputs) => {
                for (cmd, stdout, stderr) in outputs {
                    if !stdout.is_empty() {
                        info!("[{cmd}] stdout:\n{stdout}");
                    }
                    if !stderr.is_empty() {
                        info!("[{cmd}] stderr:\n{stderr}");
                    }
                }
            }
            Err(e) => {
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
    }
    if let Some(e) = first_error {
        return Err(e);
    }

    Ok(())
}

/// Clean build artifacts for each language.
pub fn clean(config: &AlefConfig, languages: &[Language]) -> anyhow::Result<()> {
    let results: Vec<anyhow::Result<Vec<(String, String, String)>>> = languages
        .par_iter()
        .map(|lang| {
            let clean_cfg = config.clean_config_for_language(*lang);
            if !check_precondition(*lang, clean_cfg.precondition.as_deref()) {
                return Ok(Vec::new());
            }
            run_before(*lang, clean_cfg.before.as_ref())?;
            let mut outputs = Vec::new();
            if let Some(cmd_list) = &clean_cfg.clean {
                for cmd in cmd_list.commands() {
                    let (stdout, stderr) = run_command_captured(cmd)?;
                    outputs.push((cmd.to_string(), stdout, stderr));
                }
            }
            Ok(outputs)
        })
        .collect();

    let mut first_error: Option<anyhow::Error> = None;
    for result in results {
        match result {
            Ok(outputs) => {
                for (cmd, stdout, stderr) in outputs {
                    if !stdout.is_empty() {
                        info!("[{cmd}] stdout:\n{stdout}");
                    }
                    if !stderr.is_empty() {
                        info!("[{cmd}] stderr:\n{stderr}");
                    }
                }
            }
            Err(e) => {
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
    }
    if let Some(e) = first_error {
        return Err(e);
    }

    Ok(())
}

/// Build language bindings using configured build commands.
///
/// Uses configurable per-language build commands from `[build_commands.<lang>]`
/// in alef.toml, falling back to sensible defaults. Resolves build order
/// (FFI-dependent languages build after FFI).
pub fn build(config: &AlefConfig, languages: &[Language], release: bool) -> anyhow::Result<()> {
    let crate_name = &config.crate_config.name;
    let base_dir = std::env::current_dir()?;

    // Split into FFI-independent and FFI-dependent languages
    let mut independent = Vec::new();
    let mut ffi_dependent = Vec::new();
    let mut need_ffi = false;

    // Rust is handled via configurable build commands, not the registry
    let mut rust_langs: Vec<Language> = Vec::new();

    for &lang in languages {
        let build_cmd_cfg = config.build_command_config_for_language(lang);
        if !check_precondition(lang, build_cmd_cfg.precondition.as_deref()) {
            continue;
        }
        if lang == Language::Rust {
            rust_langs.push(lang);
            continue;
        }
        let backend = registry::get_backend(lang);
        if let Some(bc) = backend.build_config() {
            if bc.depends_on_ffi {
                ffi_dependent.push((lang, bc));
                need_ffi = true;
            } else {
                independent.push((lang, bc));
            }
        } else {
            info!("No build config for {lang}, skipping");
        }
    }

    // Build Rust first (other bindings may depend on it)
    for &lang in &rust_langs {
        let build_cmd_cfg = config.build_command_config_for_language(lang);
        run_before(lang, build_cmd_cfg.before.as_ref())?;
        let cmds = if release {
            build_cmd_cfg.build_release.as_ref()
        } else {
            build_cmd_cfg.build.as_ref()
        };
        if let Some(cmd_list) = cmds {
            for cmd in cmd_list.commands() {
                info!("Building {lang}: {cmd}");
                run_command(cmd).with_context(|| format!("failed to build {lang}"))?;
            }
        }
    }

    // Build FFI first if needed by dependent languages
    if need_ffi
        && !independent
            .iter()
            .any(|(_, bc)| bc.tool == "cargo" && bc.crate_suffix == "-ffi")
    {
        // Resolve FFI crate name from output path
        let ffi_crate = output_path_for(Language::Ffi, config)
            .map(resolve_crate_dir)
            .and_then(|p| p.file_name())
            .and_then(|n| n.to_str())
            .unwrap_or_else(|| {
                // Fallback: construct from crate name
                Box::leak(format!("{crate_name}-ffi").into_boxed_str())
            });
        info!("Building FFI crate: {ffi_crate}");
        let mut cmd = format!("cargo build -p {ffi_crate}");
        if release {
            cmd.push_str(" --release");
        }
        run_command(&cmd).context("failed to build FFI crate")?;
    }

    // Run before hooks for independent languages (sequentially — they may have side effects)
    for (lang, _) in &independent {
        let build_cmd_cfg = config.build_command_config_for_language(*lang);
        run_before(*lang, build_cmd_cfg.before.as_ref())?;
    }

    // Build independent languages in parallel
    let build_results: Vec<anyhow::Result<(String, String)>> = independent
        .par_iter()
        .map(|(lang, bc)| {
            info!("Building {lang} ({})...", bc.tool);
            let build_cmd = build_command_for(*lang, bc, config, release);
            run_command_captured(&build_cmd).with_context(|| format!("failed to build language bindings for {lang}"))
        })
        .collect();

    for ((lang, bc), result) in independent.iter().zip(build_results) {
        let (stdout, stderr) = result?;
        if !stdout.is_empty() {
            info!("[{lang} build] {stdout}");
        }
        if !stderr.is_empty() {
            debug!("[{lang} build] {stderr}");
        }
        run_post_build(*lang, bc, config, &base_dir)
            .with_context(|| format!("failed to run post-build steps for {lang}"))?;
    }

    // Run before hooks for FFI-dependent languages
    for (lang, _) in &ffi_dependent {
        let build_cmd_cfg = config.build_command_config_for_language(*lang);
        run_before(*lang, build_cmd_cfg.before.as_ref())?;
    }

    // Build FFI-dependent languages in parallel
    let build_results: Vec<anyhow::Result<(String, String)>> = ffi_dependent
        .par_iter()
        .map(|(lang, bc)| {
            info!("Building {lang} ({})...", bc.tool);
            let build_cmd = build_command_for(*lang, bc, config, release);
            run_command_captured(&build_cmd).with_context(|| format!("failed to build language bindings for {lang}"))
        })
        .collect();

    for ((lang, bc), result) in ffi_dependent.iter().zip(build_results) {
        let (stdout, stderr) = result?;
        if !stdout.is_empty() {
            info!("[{lang} build] {stdout}");
        }
        if !stderr.is_empty() {
            debug!("[{lang} build] {stderr}");
        }
        run_post_build(*lang, bc, config, &base_dir)
            .with_context(|| format!("failed to run post-build steps for {lang}"))?;
    }

    Ok(())
}

/// Resolve the crate directory from the output config path.
/// Output paths like `crates/html-to-markdown-node/src/` → `crates/html-to-markdown-node`.
fn resolve_crate_dir(output_path: &Path) -> &Path {
    // If path ends in src/ or src, go up one level
    if output_path.file_name().is_some_and(|n| n == "src") {
        output_path.parent().unwrap_or(output_path)
    } else {
        output_path
    }
}

/// Get the output path for a language from config.
fn output_path_for(lang: Language, config: &AlefConfig) -> Option<&Path> {
    match lang {
        Language::Python => config.output.python.as_deref(),
        Language::Node => config.output.node.as_deref(),
        Language::Ruby => config.output.ruby.as_deref(),
        Language::Php => config.output.php.as_deref(),
        Language::Ffi => config.output.ffi.as_deref(),
        Language::Go => config.output.go.as_deref(),
        Language::Java => config.output.java.as_deref(),
        Language::Csharp => config.output.csharp.as_deref(),
        Language::Wasm => config.output.wasm.as_deref(),
        Language::Elixir => config.output.elixir.as_deref(),
        Language::R => config.output.r.as_deref(),
        // Rust is the core language — no separate output path
        Language::Rust => None,
    }
}

/// Generate the shell command to build a specific language.
fn build_command_for(
    lang: Language,
    bc: &alef_core::backend::BuildConfig,
    config: &AlefConfig,
    release: bool,
) -> String {
    let release_flag = if release { " --release" } else { "" };

    // Resolve the crate directory from the output path
    let crate_dir = output_path_for(lang, config)
        .map(resolve_crate_dir)
        .and_then(|p| p.to_str())
        .unwrap_or("");

    match bc.tool {
        "maturin" => {
            format!("maturin develop --manifest-path {crate_dir}/Cargo.toml{release_flag}")
        }
        "napi" => {
            // NAPI outputs .node + .d.ts to the crate directory
            format!("napi build --platform --manifest-path {crate_dir}/Cargo.toml -o {crate_dir}{release_flag}")
        }
        "wasm-pack" => {
            let profile = if release { "--release" } else { "--dev" };
            format!("wasm-pack build {crate_dir} {profile} --target bundler")
        }
        "cargo" => {
            // Check for a standalone crate directory (e.g., Ruby's native/ subdir)
            // that is excluded from the workspace and must be built via --manifest-path.
            let native_dir = Path::new(crate_dir).join("native");
            let native_manifest = native_dir.join("Cargo.toml");
            if native_manifest.exists() {
                let dir = native_dir.display();
                format!("cd {dir} && cargo build{release_flag}")
            } else {
                // Extract crate name from directory name for -p flag
                let crate_name = Path::new(crate_dir)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(crate_dir);
                format!("cargo build -p {crate_name}{release_flag}")
            }
        }
        "mix" => "mix compile".to_string(),
        "mvn" => {
            let dir = config
                .output
                .java
                .as_ref()
                .and_then(|p| p.to_str())
                .unwrap_or("packages/java");
            format!("cd {dir} && mvn package -DskipTests -q")
        }
        "dotnet" => {
            let dir = config
                .output
                .csharp
                .as_ref()
                .and_then(|p| p.to_str())
                .unwrap_or("packages/csharp");
            // Find the directory containing the .csproj (may be in a subdirectory)
            let build_dir = {
                let dir_path = std::path::Path::new(dir);
                // Check if .csproj exists directly in dir
                let has_direct = dir_path
                    .read_dir()
                    .ok()
                    .map(|entries| {
                        entries
                            .filter_map(|e| e.ok())
                            .any(|e| e.path().extension().is_some_and(|ext| ext == "csproj"))
                    })
                    .unwrap_or(false);
                if has_direct {
                    dir.to_string()
                } else {
                    // Search one level of subdirectories
                    dir_path
                        .read_dir()
                        .ok()
                        .and_then(|entries| {
                            entries
                                .filter_map(|e| e.ok())
                                .find(|e| {
                                    e.path().is_dir()
                                        && e.path().read_dir().ok().is_some_and(|sub| {
                                            sub.filter_map(|s| s.ok())
                                                .any(|s| s.path().extension().is_some_and(|ext| ext == "csproj"))
                                        })
                                })
                                .map(|e| e.path().to_string_lossy().to_string())
                        })
                        .unwrap_or_else(|| dir.to_string())
                }
            };
            let dotnet_config = if release { "Release" } else { "Debug" };
            format!("cd {build_dir} && dotnet build --configuration {dotnet_config} -q")
        }
        "go" => {
            let dir = config
                .output
                .go
                .as_ref()
                .and_then(|p| p.to_str())
                .unwrap_or("packages/go");
            format!("cd {dir} && go build ./...")
        }
        other => format!("echo 'Unknown build tool: {other}'"),
    }
}

/// Run post-build processing steps (e.g., patching .d.ts files).
fn run_post_build(
    lang: Language,
    bc: &alef_core::backend::BuildConfig,
    config: &AlefConfig,
    base_dir: &Path,
) -> anyhow::Result<()> {
    use alef_core::backend::PostBuildStep;

    // Resolve the crate directory from the output path
    let crate_dir = output_path_for(lang, config)
        .map(resolve_crate_dir)
        .unwrap_or(Path::new(""));

    for step in &bc.post_build {
        match step {
            PostBuildStep::PatchFile { path, find, replace } => {
                let file_path = base_dir.join(crate_dir).join(path);
                if file_path.exists() {
                    let content = std::fs::read_to_string(&file_path)
                        .with_context(|| format!("failed to read post-build patch target {}", file_path.display()))?;
                    let patched = content.replace(find, replace);
                    if patched != content {
                        std::fs::write(&file_path, &patched)
                            .with_context(|| format!("failed to write patched file {}", file_path.display()))?;
                        info!("Patched {}: replaced '{}' → '{}'", file_path.display(), find, replace);
                    }
                } else {
                    debug!("Post-build patch target not found: {}", file_path.display());
                }
            }
        }
    }

    Ok(())
}