cargo-buckal 0.1.3

Seamlessly build Cargo projects with Buck2.
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use std::collections::HashMap;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::{io, process::Command, str::FromStr};

use anyhow::{Result, bail};
use cargo_metadata::camino::Utf8PathBuf;
use cargo_metadata::{MetadataCommand, PackageId};
use cargo_platform::Cfg;
use cargo_util_schemas::core::{PackageIdSpec, SourceKind};
use colored::Colorize;
use inquire::Select;

use crate::buck2::Buck2Command;
use crate::cache::BuckalCache;
use crate::{RUST_CRATES_ROOT, RUST_GIT_ROOT};

#[macro_export]
macro_rules! buckal_log {
    ($action:expr, $msg:expr) => {{
        let colored = match $action {
            "Adding" => ::colored::Colorize::green($action),
            "Creating" => ::colored::Colorize::green($action),
            "Flushing" => ::colored::Colorize::green($action),
            "Removing" => ::colored::Colorize::yellow($action),
            "Fetching" => ::colored::Colorize::cyan($action),
            "Login" => ::colored::Colorize::green($action),
            "Logout" => ::colored::Colorize::green($action),
            "Push" => ::colored::Colorize::cyan($action),
            "Uploading" => ::colored::Colorize::green($action),
            _ => ::colored::Colorize::blue($action),
        };
        println!("{:>12} {}", ::colored::Colorize::bold(colored), $msg);
    }};
}

#[macro_export]
macro_rules! buckal_error {
    ($msg:expr) => {{
        let error_prefix = ::colored::Colorize::red("error:");
        eprintln!("{} {}", ::colored::Colorize::bold(error_prefix), $msg);
    }};

    ($fmt:expr, $($arg:tt)*) => {{
        let error_prefix = ::colored::Colorize::red("error:");
        eprintln!(
            "{} {}",
            ::colored::Colorize::bold(error_prefix),
            format_args!($fmt, $($arg)*)
        );
    }};
}

#[macro_export]
macro_rules! buckal_note {
    ($msg:expr) => {{
        let note_prefix = ::colored::Colorize::cyan("note:");
        eprintln!("{} {}", ::colored::Colorize::bold(note_prefix), $msg);
    }};

    ($fmt:expr, $($arg:tt)*) => {{
        let note_prefix = ::colored::Colorize::cyan("note:");
        eprintln!(
            "{} {}",
            ::colored::Colorize::bold(note_prefix),
            format_args!($fmt, $($arg)*)
        );
    }};
}

#[macro_export]
macro_rules! buckal_warn {
    ($msg:expr) => {{
        let warn_prefix = ::colored::Colorize::yellow("warn:");
        eprintln!("{} {}", ::colored::Colorize::bold(warn_prefix), $msg);
    }};

    ($fmt:expr, $($arg:tt)*) => {{
        let warn_prefix = ::colored::Colorize::yellow("warn:");
        eprintln!(
            "{} {}",
            ::colored::Colorize::bold(warn_prefix),
            format_args!($fmt, $($arg)*)
        );
    }};
}

pub fn check_buck2_installed() -> bool {
    Buck2Command::new()
        .arg("--help")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

pub fn prompt_buck2_installation() -> io::Result<bool> {
    println!();
    println!(
        "{} {}",
        "⚠️".yellow(),
        "Buck2 is not installed or not found in PATH.".yellow()
    );
    println!(
        "{} {}",
        "🔧".blue(),
        "Buck2 is required to use cargo buckal.".blue()
    );
    println!();

    let options = vec![
        "🚀 Install automatically (recommended)",
        "📖 Exit and show manual installation guide",
    ];

    let ans = Select::new("How would you like to install Buck2?", options)
        .prompt()
        .map_err(|e| io::Error::other(format!("Selection error: {}", e)))?;

    match ans {
        "🚀 Install automatically (recommended)" => {
            println!();
            println!(
                "{} {}",
                "🚀".green(),
                "Installing Buck2 automatically...".green()
            );

            if let Err(e) = install_buck2_automatically() {
                println!("{} {}: {}", "".red(), "Installation failed".red(), e);
                println!();
                show_manual_installation();
                return Ok(false);
            }

            println!(
                "{} {}",
                "".green(),
                "Buck2 installation completed!".green()
            );
            println!("{} {}", "🔍".blue(), "Verifying installation...".blue());

            // Check if installation was successful
            if check_buck2_installed() {
                println!("{} {}", "🎉".green(), "Buck2 is now available!".green());
                Ok(true)
            } else {
                println!(
                    "{} {}",
                    "⚠️".yellow(),
                    "Buck2 installation completed but not found in PATH.".yellow()
                );
                println!(
                    "{} {}",
                    "💡".bright_blue(),
                    "You may need to restart your terminal or source your shell profile."
                        .bright_blue()
                );
                Ok(false)
            }
        }
        "📖 Exit and show manual installation guide" => {
            show_manual_installation();
            Ok(false)
        }
        _ => Ok(false),
    }
}

fn install_buck2_automatically() -> io::Result<()> {
    println!("{} {}", "📦".cyan(), "Installing Rust nightly...".cyan());
    let status = Command::new("rustup")
        .args(["install", "nightly-2025-06-20"])
        .status()?;

    if !status.success() {
        return Err(io::Error::other("Failed to install Rust nightly"));
    }

    println!(
        "{} {}",
        "📦".cyan(),
        "Installing Buck2 from GitHub...".cyan()
    );
    let status = Command::new("cargo")
        .args([
            "+nightly-2025-06-20",
            "install",
            "--git",
            "https://github.com/facebook/buck2.git",
            "buck2",
        ])
        .status()?;

    if !status.success() {
        return Err(io::Error::other("Failed to install Buck2"));
    }

    Ok(())
}

fn show_manual_installation() {
    println!();
    println!(
        "{} {}",
        "📖".green(),
        "Manual Buck2 Installation Guide".green().bold()
    );
    println!();

    println!(
        "{}",
        "Choose one of the following installation methods:".bright_magenta()
    );
    println!();

    // Method 1: Cargo install
    println!(
        "{}",
        "Method 1: Install via Cargo (Recommended)".cyan().bold()
    );
    println!("{}", "1. Install Rust nightly (prerequisite)".cyan());
    println!("   {}", "rustup install nightly-2025-06-20".bright_white());
    println!();
    println!("{}", "2. Install Buck2 from GitHub".cyan());
    println!(
        "   {}",
        "cargo +nightly-2025-06-20 install --git https://github.com/facebook/buck2.git buck2"
            .bright_white()
    );
    println!();
    println!("{}", "3. Add to your PATH (if not already)".cyan());
    println!(
        "   {}",
        "# Add to your shell profile (~/.bashrc, ~/.zshrc, etc.)".bright_black()
    );
    println!("   {}", "Linux/macOS:".bright_black());
    println!("   {}", "export PATH=$HOME/.cargo/bin:$PATH".bright_white());
    println!("   {}", "Windows PowerShell:".bright_black());
    println!(
        "   {}",
        "$Env:PATH += \";$HOME\\.cargo\\bin\"".bright_white()
    );
    println!();

    println!("{}", "".repeat(60).bright_black());
    println!();

    // Method 2: Direct download
    println!("{}", "Method 2: Download Pre-built Binary".yellow().bold());
    println!("{}", "1. Download from GitHub releases".yellow());
    println!(
        "   {}",
        "https://github.com/facebook/buck2/releases/tag/latest"
            .bright_white()
            .underline()
    );
    println!();
    println!("{}", "2. Extract and place in your PATH".yellow());
    println!(
        "   {}",
        "# Extract the downloaded file and move to a directory in your PATH".bright_black()
    );
    println!(
        "   {}",
        "# For example: /usr/local/bin (Linux/macOS) or C:\\bin (Windows)".bright_black()
    );
    println!();

    println!("{}", "".repeat(60).bright_black());
    println!();

    // Verification
    println!("{} {}", "".green(), "Verify Installation".green().bold());
    println!("   {}", "buck2 --help".bright_white());
    println!();

    println!(
        "{} {}",
        "💡".bright_blue(),
        "Note: After installation, restart your terminal or source your shell profile."
            .bright_blue()
    );
    println!();

    println!(
        "{} {}",
        "📚".bright_cyan(),
        "For detailed instructions and troubleshooting, refer to:".bright_cyan()
    );
    println!(
        "   {}",
        "https://buck2.build/docs/getting_started/install/"
            .cyan()
            .underline()
    );
    println!();

    println!(
        "{} {}",
        "🔄".yellow(),
        "Once Buck2 is installed, run your cargo buckal command again.".yellow()
    );
    println!();
}

pub fn ensure_buck2_installed() -> io::Result<()> {
    if !check_buck2_installed() {
        let installed = prompt_buck2_installation()?;
        if !installed {
            return Err(io::Error::other(
                "Buck2 is required but not installed. Please install Buck2 and try again.",
            ));
        }
    }
    Ok(())
}

/// Get the root directory of the Buck2 project by running `buck2 root --kind project`.
pub fn get_buck2_root() -> Result<Utf8PathBuf> {
    static BUCK2_PROJECT_ROOT: OnceLock<Utf8PathBuf> = OnceLock::new();

    if let Some(path) = BUCK2_PROJECT_ROOT.get() {
        return Ok(path.clone());
    }

    let output = Buck2Command::root().arg("--kind").arg("project").output()?;
    if output.status.success() {
        let path_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
        let path = Utf8PathBuf::from(path_str);
        let _ = BUCK2_PROJECT_ROOT.set(path.clone());
        Ok(path)
    } else {
        bail!(String::from_utf8_lossy(&output.stderr).to_string())
    }
}

pub fn find_buck2_project_root(start: &Path) -> Option<PathBuf> {
    start
        .ancestors()
        .find(|candidate| candidate.join(".buckconfig").is_file())
        .map(Path::to_path_buf)
}

/// Check if a platform target exists using buck2 uquery
pub fn platform_exists(platform_target: &str) -> bool {
    let output = crate::buck2::Buck2Command::uquery()
        .arg(platform_target)
        .output();

    match output {
        Ok(o) => o.status.success(),
        Err(_) => false,
    }
}

/// Check if the current directory is a valid Buck2 package.
pub fn check_buck2_package() -> Result<()> {
    let cwd = std::env::current_dir()?;
    let buck_file = cwd.join("BUCK");
    if !buck_file.exists() {
        bail!(
            "could not find `BUCK` in `{}`. Are you in a Buck2 package?",
            cwd.display(),
        );
    }
    Ok(())
}

/// Check if the current directory is inside a Buck2 project.
pub fn is_inside_buck2_project() -> Result<()> {
    let cwd = std::env::current_dir()?;
    if find_buck2_project_root(&cwd).is_some() {
        Ok(())
    } else {
        bail!("Not inside a Buck2 project.");
    }
}

pub fn get_target() -> String {
    let output = Command::new("rustc")
        .arg("-Vv")
        .output()
        .expect("rustc failed to run");
    let stdout = String::from_utf8(output.stdout).unwrap();
    for line in stdout.lines() {
        if let Some(line) = line.strip_prefix("host: ") {
            return String::from(line);
        }
    }
    panic!("Failed to find host: {stdout}");
}

/// Check if a target triple is valid for rustc
pub fn is_valid_rustc_target(triple: &str) -> bool {
    let output = Command::new("rustc")
        .arg("--print")
        .arg("target-list")
        .output();

    match output {
        Ok(o) if o.status.success() => {
            let stdout = String::from_utf8_lossy(&o.stdout);
            stdout.lines().any(|line| line.trim() == triple)
        }
        _ => false,
    }
}

/// Validate a target triple: check if it's valid for rustc and if the corresponding
/// Buck2 platform exists
pub fn validate_target_triple(triple: &str) -> Result<String> {
    // Check if it's a valid rustc target
    if !is_valid_rustc_target(triple) {
        bail!(
            "invalid target triple '{}': not a valid rustc target. \
             Run 'rustc --print target-list' to see available targets.",
            triple
        );
    }

    // Check if the corresponding Buck2 platform exists
    let platform = format!("//platforms:{}", triple);
    if !platform_exists(&platform) {
        bail!(
            "platform '{}' does not exist in Buck2. \
             Ensure the platform is defined in //platforms/BUCK.",
            platform
        );
    }

    Ok(platform)
}

pub fn get_cfgs() -> Vec<Cfg> {
    let output = Command::new("rustc")
        .arg("--print=cfg")
        .output()
        .expect("rustc failed to run");
    let stdout = String::from_utf8(output.stdout).unwrap();
    stdout
        .lines()
        .map(|line| Cfg::from_str(line).unwrap())
        .collect()
}

pub fn get_cache_path() -> Result<Utf8PathBuf> {
    Ok(get_buck2_root()?.join("buckal.snap"))
}

/// Get the relative vendor path for a given package
///
/// This function determines the vendor path based on the package source:
/// - For registry packages, it returns `third-party/rust/crates/<package>/<version>`
/// - For git packages, it returns `third-party/rust/git/<package>/<version>`
pub fn get_vendor_path_relative(package_id: &PackageId) -> Result<String> {
    let package_id_spec = PackageIdSpec::parse(&package_id.repr)?;
    match package_id_spec
        .kind()
        .expect("failed to extract package source kind")
    {
        SourceKind::Registry => Ok(format!(
            "{RUST_CRATES_ROOT}/{}/{}",
            package_id_spec.name(),
            package_id_spec
                .version()
                .expect("failed to extract package version")
        )),
        SourceKind::Git(_) => Ok(format!(
            "{RUST_GIT_ROOT}/{}/{}",
            package_id_spec.name(),
            package_id_spec
                .version()
                .expect("failed to extract package version")
        )),
        _ => bail!(
            "unsupported source kind for package '{}'",
            package_id_spec.name()
        ),
    }
}

/// Get the vendor directory for a given package
pub fn get_vendor_dir(package_id: &PackageId) -> Result<Utf8PathBuf> {
    Ok(get_buck2_root()?.join(get_vendor_path_relative(package_id)?))
}

/// Retrieve the last saved BuckalCache from the cache file, or create a new one if the cache file does not exist.
pub fn get_last_cache() -> BuckalCache {
    if let Ok(last_cache) = BuckalCache::load() {
        last_cache
    } else {
        let cargo_metadata = MetadataCommand::new().exec().unwrap_or_exit();
        let resolve = cargo_metadata.resolve.unwrap();
        let nodes_map = resolve
            .nodes
            .into_iter()
            .map(|n| (n.id.to_owned(), n))
            .collect::<HashMap<_, _>>();
        BuckalCache::new(&nodes_map, &cargo_metadata.workspace_root)
    }
}

pub fn section(title: &str) {
    let content = format!("---- {} ----", title);
    let width = 60;

    if content.len() >= width {
        println!("{}", content);
        return;
    }

    let total_padding = width - content.len();
    let left_padding = total_padding / 2;
    let right_padding = total_padding - left_padding;

    let left_pad = "-".repeat(left_padding);
    let right_pad = "-".repeat(right_padding);

    println!("{}{}{}", left_pad, content, right_pad);
}

/// Quick check if rustc is available before spawning multiple threads.
pub fn check_rustc_installed() -> bool {
    Command::new("rustc")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

pub fn ensure_rustc_installed() -> io::Result<()> {
    if !check_rustc_installed() {
        return Err(io::Error::other(
            "rustc is required but not installed. Please install Rust and try again.",
        ));
    }
    Ok(())
}

pub fn ensure_prerequisites() -> io::Result<()> {
    ensure_rustc_installed()?;
    ensure_buck2_installed()?;
    Ok(())
}

pub fn append_buck_out_to_gitignore(root: &Path) -> io::Result<()> {
    let mut git_ignore = OpenOptions::new()
        .create(true)
        .append(true)
        .open(root.join(".gitignore"))?;
    writeln!(git_ignore, "/buck-out")?;
    Ok(())
}

pub trait UnwrapOrExit<T> {
    fn unwrap_or_exit(self) -> T;
    fn unwrap_or_exit_ctx(self, context: impl std::fmt::Display) -> T;
}

impl<T, E: std::fmt::Display> UnwrapOrExit<T> for Result<T, E> {
    fn unwrap_or_exit(self) -> T {
        match self {
            Ok(value) => value,
            Err(error) => {
                buckal_error!(error);
                std::process::exit(1);
            }
        }
    }

    fn unwrap_or_exit_ctx(self, context: impl std::fmt::Display) -> T {
        match self {
            Ok(value) => value,
            Err(error) => {
                buckal_error!("{}:\n{}", context, error);
                std::process::exit(1);
            }
        }
    }
}

/// Get the file path from a URL on Unix platforms (straightforward)
#[cfg(unix)]
pub fn get_url_path(url: &url::Url) -> String {
    url.path().to_owned()
}

/// Get the file path from a URL on non-Unix platforms, handling drive letters and backslashes
///
/// On Windows, Cargo may produce file URLs that look like `file:///C:/path/to/file`, which includes a leading slash before the drive letter. We need to trim that leading slash and convert forward slashes to backslashes to get a valid Windows path.
#[cfg(not(unix))]
pub fn get_url_path(url: &url::Url) -> String {
    let path = url.path();
    if path.starts_with('/') && path.chars().nth(2) == Some(':') {
        path[1..].replace('/', "\\").to_owned()
    } else {
        path.to_owned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_is_valid_rustc_target_valid_targets() {
        // These are common, always-available targets
        assert!(is_valid_rustc_target("x86_64-unknown-linux-gnu"));
        assert!(is_valid_rustc_target("aarch64-unknown-linux-gnu"));
        assert!(is_valid_rustc_target("x86_64-apple-darwin"));
        assert!(is_valid_rustc_target("x86_64-pc-windows-msvc"));
    }

    #[test]
    fn test_is_valid_rustc_target_invalid_targets() {
        assert!(!is_valid_rustc_target("invalid-target-triple"));
        assert!(!is_valid_rustc_target("not-a-real-target"));
        assert!(!is_valid_rustc_target(""));
        assert!(!is_valid_rustc_target("x86_64"));
        assert!(!is_valid_rustc_target("linux"));
    }

    #[test]
    fn test_validate_target_triple_invalid_rustc_target() {
        let result = validate_target_triple("invalid-target-triple");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("not a valid rustc target"));
        assert!(err.to_string().contains("invalid-target-triple"));
    }

    #[test]
    fn test_validate_target_triple_returns_platform_path() {
        // This test may fail if running outside a Buck2 project
        // In CI, we'll test the full flow with a real project
        let result = validate_target_triple("x86_64-unknown-linux-gnu");
        // The result will be Ok if platform exists, Err otherwise
        // We just verify the format when successful
        if let Ok(platform) = result {
            assert_eq!(platform, "//platforms:x86_64-unknown-linux-gnu");
        }
    }

    #[test]
    fn test_find_buck2_project_root_finds_ancestor_buckconfig() {
        let root = TempDir::new().expect("failed to create temp dir");
        let nested = root.path().join("crates").join("demo");
        std::fs::create_dir_all(&nested).expect("failed to create nested directories");
        std::fs::write(root.path().join(".buckconfig"), "[project]\nignore=.git\n")
            .expect("failed to write .buckconfig");

        let found = find_buck2_project_root(&nested);
        assert_eq!(found.as_deref(), Some(root.path()));
    }

    #[test]
    fn test_find_buck2_project_root_returns_none_without_buckconfig() {
        let root = TempDir::new().expect("failed to create temp dir");
        let nested = root.path().join("crates").join("demo");
        std::fs::create_dir_all(&nested).expect("failed to create nested directories");

        let found = find_buck2_project_root(&nested);
        assert!(found.is_none());
    }

    #[test]
    fn test_append_buck_out_to_gitignore_creates_file_when_missing() {
        let root = TempDir::new().expect("failed to create temp dir");

        append_buck_out_to_gitignore(root.path()).expect("expected .gitignore to be created");

        let gitignore = std::fs::read_to_string(root.path().join(".gitignore"))
            .expect("failed to read .gitignore");
        assert!(gitignore.contains("/buck-out"));
    }
}