xcargo 0.1.0

Cross-compilation, zero friction - Rust cross-compilation tool with automatic toolchain management
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
//! xcargo CLI entry point

use anyhow::Result;
use clap::{Parser, Subcommand};
use inquire::{MultiSelect, Select, Confirm};
use xcargo::build::{Builder, BuildOptions};
use xcargo::config::Config;
use xcargo::output::{helpers, tips};
use xcargo::target::Target;
use xcargo::toolchain::ToolchainManager;
use std::path::Path;

/// xcargo - Cross-compilation, zero friction 🎯
#[derive(Parser)]
#[command(name = "xcargo")]
#[command(author, version, about, long_about = None)]
#[command(after_help = "TIP: Run 'xcargo build --target <triple>' to cross-compile")]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Build for target platform(s)
    Build {
        /// Target triple (e.g., x86_64-pc-windows-gnu)
        #[arg(short, long)]
        target: Option<String>,

        /// Build for all configured targets
        #[arg(long, conflicts_with = "target")]
        all: bool,

        /// Build in release mode
        #[arg(short, long)]
        release: bool,

        /// Toolchain to use (e.g., stable, nightly)
        #[arg(long)]
        toolchain: Option<String>,

        /// Additional cargo arguments
        #[arg(last = true)]
        cargo_args: Vec<String>,
    },

    /// Manage targets
    Target {
        #[command(subcommand)]
        action: TargetAction,
    },

    /// Initialize xcargo for a project
    Init {
        /// Interactive setup wizard
        #[arg(short, long)]
        interactive: bool,
    },

    /// Display configuration
    Config {
        /// Show default config
        #[arg(long)]
        default: bool,
    },

    /// Show version information
    Version,
}

#[derive(Subcommand)]
enum TargetAction {
    /// Add a target
    Add {
        /// Target name or triple
        target: String,

        /// Toolchain to add target to
        #[arg(long, default_value = "stable")]
        toolchain: String,
    },

    /// List targets
    List {
        /// Show only installed targets
        #[arg(long)]
        installed: bool,

        /// Toolchain to list targets for
        #[arg(long)]
        toolchain: Option<String>,
    },

    /// Show target information
    Info {
        /// Target triple
        target: String,
    },
}

/// Run basic non-interactive setup
fn run_basic_setup() -> Result<()> {
    helpers::section("Initialize xcargo");

    if Path::new("xcargo.toml").exists() {
        helpers::warning("xcargo.toml already exists");
        let overwrite = Confirm::new("Overwrite existing configuration?")
            .with_default(false)
            .prompt()?;

        if !overwrite {
            helpers::info("Setup cancelled");
            return Ok(());
        }
    }

    let host = Target::detect_host()?;
    let mut config = Config::default();
    config.targets.default = vec![host.triple.clone()];

    config.save("xcargo.toml")?;

    helpers::success("Created xcargo.toml with default configuration");
    helpers::tip(format!("Default target: {}", host.triple));
    helpers::hint("Use 'xcargo init --interactive' for guided setup");

    Ok(())
}

/// Run interactive TUI setup wizard
fn run_interactive_setup() -> Result<()> {
    use xcargo::output::colors;

    println!("\n{}{}✨ xcargo Interactive Setup{}", colors::BOLD, colors::CYAN, colors::RESET);
    println!("{}Let's configure cross-compilation for your project!{}\n", colors::DIM, colors::RESET);

    // Check for existing config
    if Path::new("xcargo.toml").exists() {
        helpers::warning("xcargo.toml already exists");
        let overwrite = Confirm::new("Overwrite existing configuration?")
            .with_default(false)
            .prompt()?;

        if !overwrite {
            helpers::info("Setup cancelled");
            return Ok(());
        }
    }

    // Detect host
    let host = Target::detect_host()?;
    helpers::success(format!("Detected host platform: {}", host.triple));
    println!();

    // Select target platforms
    let target_options = vec![
        ("Linux x86_64", "x86_64-unknown-linux-gnu"),
        ("Linux x86_64 (musl)", "x86_64-unknown-linux-musl"),
        ("Linux ARM64", "aarch64-unknown-linux-gnu"),
        ("Windows x86_64 (GNU)", "x86_64-pc-windows-gnu"),
        ("Windows x86_64 (MSVC)", "x86_64-pc-windows-msvc"),
        ("macOS x86_64", "x86_64-apple-darwin"),
        ("macOS ARM64 (M1/M2)", "aarch64-apple-darwin"),
        ("WebAssembly", "wasm32-unknown-unknown"),
    ];

    let selected_names = MultiSelect::new(
        "Which targets do you want to build for?",
        target_options.iter().map(|(name, _)| *name).collect()
    )
    .with_help_message("Use ↑↓ to navigate, Space to select, Enter to confirm")
    .prompt()?;

    let selected_targets: Vec<String> = selected_names
        .iter()
        .filter_map(|&selected_name| {
            target_options.iter()
                .find(|(name, _)| name == &selected_name)
                .map(|(_, triple)| triple.to_string())
        })
        .collect();

    if selected_targets.is_empty() {
        helpers::warning("No targets selected, using host target");
    }

    println!();

    // Parallel builds
    let parallel = Confirm::new("Enable parallel builds?")
        .with_default(true)
        .with_help_message("Build multiple targets concurrently for faster builds")
        .prompt()?;

    // Build caching
    let cache = Confirm::new("Enable build caching?")
        .with_default(true)
        .with_help_message("Cache build artifacts to speed up subsequent builds")
        .prompt()?;

    // Container strategy
    let container_options = vec![
        "Auto (use containers only when necessary)",
        "Always use containers",
        "Never use containers",
    ];

    let container_choice = Select::new(
        "Container build strategy:",
        container_options
    )
    .with_help_message("Containers ensure reproducible builds")
    .prompt()?;

    let use_when = match container_choice {
        "Auto (use containers only when necessary)" => "target.os != host.os",
        "Always use containers" => "always",
        "Never use containers" => "never",
        _ => "target.os != host.os",
    };

    println!();
    helpers::progress("Creating configuration...");

    // Build configuration
    let mut config = Config::default();
    let host_triple = host.triple.clone();
    config.targets.default = if selected_targets.is_empty() {
        vec![host_triple.clone()]
    } else {
        selected_targets.clone()
    };
    config.build.parallel = parallel;
    config.build.cache = cache;
    config.container.use_when = use_when.to_string();

    // Save configuration
    config.save("xcargo.toml")?;

    println!();
    helpers::success("✨ Configuration created successfully!");
    println!();

    // Summary
    helpers::section("Configuration Summary");
    println!("Targets: {}", selected_targets.join(", "));
    println!("Parallel builds: {}", if parallel { "enabled" } else { "disabled" });
    println!("Build cache: {}", if cache { "enabled" } else { "disabled" });
    println!("Container strategy: {}", use_when);
    println!();

    // Next steps
    helpers::section("Next Steps");
    helpers::tip("Run 'xcargo build' to build for your host platform");
    helpers::tip("Run 'xcargo build --all' to build for all configured targets");
    helpers::tip("Run 'xcargo target add <triple>' to add more targets");
    println!();

    // Offer to install targets
    let install_now = Confirm::new("Install selected targets now?")
        .with_default(true)
        .prompt()?;

    if install_now && !selected_targets.is_empty() {
        println!();
        helpers::progress("Installing targets...");
        let manager = ToolchainManager::new()?;

        for target in &selected_targets {
            if target != &host_triple {
                match manager.ensure_target("stable", target) {
                    Ok(()) => helpers::success(format!("Installed {}", target)),
                    Err(e) => helpers::warning(format!("Failed to install {}: {}", target, e)),
                }
            }
        }

        println!();
        helpers::success("Setup complete! You're ready to cross-compile 🚀");
    } else {
        helpers::success("Setup complete! Install targets later with 'xcargo target add <triple>'");
    }

    Ok(())
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Build {
            target,
            all,
            release,
            toolchain,
            cargo_args,
        } => {
            let builder = Builder::new()?;

            let options = BuildOptions {
                target: target.clone(),
                release,
                cargo_args,
                toolchain,
                verbose: cli.verbose,
            };

            if all {
                // Build for all configured targets
                let config = Config::discover()?.map(|(c, _)| c).unwrap_or_default();

                if config.targets.default.is_empty() {
                    helpers::error("No default targets configured");
                    helpers::hint("Add targets to xcargo.toml: [targets] default = [\"x86_64-unknown-linux-gnu\"]");
                    helpers::tip(tips::CONFIG_FILE);
                    std::process::exit(1);
                }

                builder.build_all(&config.targets.default, &options)?;
            } else {
                builder.build(&options)?;
            }
        }

        Commands::Target { action } => match action {
            TargetAction::Add { target, toolchain } => {
                helpers::section("Add Target");

                let manager = ToolchainManager::new()?;
                let target_triple = Target::resolve_alias(&target)?;

                helpers::progress(format!(
                    "Adding target {} to toolchain {}...",
                    target_triple, toolchain
                ));

                manager.install_target(&toolchain, &target_triple)?;

                helpers::success(format!("Target {} added successfully", target_triple));
                helpers::tip(format!(
                    "Use 'xcargo build --target {}' to build for this target",
                    target_triple
                ));
            }

            TargetAction::List { installed, toolchain } => {
                helpers::section("Available Targets");

                if installed {
                    let manager = ToolchainManager::new()?;
                    let tc = toolchain.unwrap_or_else(|| "stable".to_string());

                    helpers::info(format!("Installed targets for toolchain '{}':", tc));
                    println!();

                    match manager.list_targets(&tc) {
                        Ok(targets) => {
                            if targets.is_empty() {
                                println!("  No targets installed");
                            } else {
                                for target in targets {
                                    println!("  • {}", target);
                                }
                            }
                        }
                        Err(e) => {
                            helpers::error(format!("Failed to list targets: {}", e));
                            std::process::exit(1);
                        }
                    }
                } else {
                    println!("Common cross-compilation targets:\n");

                    println!("Linux:");
                    println!("  • x86_64-unknown-linux-gnu   (Linux x86_64)");
                    println!("  • x86_64-unknown-linux-musl  (Linux x86_64, statically linked)");
                    println!("  • aarch64-unknown-linux-gnu  (Linux ARM64)");
                    println!();

                    println!("Windows:");
                    println!("  • x86_64-pc-windows-gnu      (Windows x86_64, MinGW)");
                    println!("  • x86_64-pc-windows-msvc     (Windows x86_64, MSVC)");
                    println!();

                    println!("macOS:");
                    println!("  • x86_64-apple-darwin        (macOS x86_64)");
                    println!("  • aarch64-apple-darwin       (macOS ARM64, M1/M2)");
                    println!();

                    helpers::hint("Use 'xcargo target list --installed' to see installed targets");
                    helpers::tip("Use 'xcargo target add <triple>' to install a new target");
                }
            }

            TargetAction::Info { target } => {
                helpers::section("Target Information");

                let target_triple = Target::resolve_alias(&target)?;
                match Target::from_triple(&target_triple) {
                    Ok(target) => {
                        println!("Triple:       {}", target.triple);
                        println!("Architecture: {}", target.arch);
                        println!("OS:           {}", target.os);
                        println!("Environment:  {}", target.env.as_deref().unwrap_or("default"));
                        println!("Tier:         {:?}", target.tier);
                        println!();

                        let requirements = target.get_requirements();
                        if requirements.linker.is_some() || !requirements.tools.is_empty() || !requirements.system_libs.is_empty() {
                            helpers::info("Requirements:");
                            if let Some(linker) = requirements.linker {
                                println!("  Linker: {}", linker);
                            }
                            if !requirements.tools.is_empty() {
                                println!("  Tools: {}", requirements.tools.join(", "));
                            }
                            if !requirements.system_libs.is_empty() {
                                println!("  System libs: {}", requirements.system_libs.join(", "));
                            }
                            println!();
                        }

                        let host = Target::detect_host()?;
                        if target.can_cross_compile_from(&host) {
                            helpers::success("Can cross-compile from this host");
                        } else {
                            helpers::warning("May require container for cross-compilation");
                        }

                        println!();
                        helpers::tip(format!("Add this target: xcargo target add {}", target.triple));
                        helpers::tip(format!("Build for this target: xcargo build --target {}", target.triple));
                    }
                    Err(e) => {
                        helpers::error(format!("Invalid target: {}", e));
                        std::process::exit(1);
                    }
                }
            }
        },

        Commands::Init { interactive } => {
            if interactive {
                run_interactive_setup()?;
            } else {
                run_basic_setup()?;
            }
        }

        Commands::Config { default } => {
            helpers::section("Configuration");

            if default {
                let config = Config::default();
                match config.to_toml() {
                    Ok(toml) => {
                        println!("{}", toml);
                        println!();
                        helpers::tip("Save this to xcargo.toml to customize your build");
                    }
                    Err(e) => {
                        helpers::error(format!("Failed to generate config: {}", e));
                        std::process::exit(1);
                    }
                }
            } else {
                match Config::discover() {
                    Ok(Some((config, path))) => {
                        helpers::info(format!("Configuration from: {}", path.display()));
                        println!();
                        match config.to_toml() {
                            Ok(toml) => println!("{}", toml),
                            Err(e) => {
                                helpers::error(format!("Failed to serialize config: {}", e));
                                std::process::exit(1);
                            }
                        }
                    }
                    Ok(None) => {
                        helpers::info("No xcargo.toml found, using defaults");
                        println!();
                        let config = Config::default();
                        match config.to_toml() {
                            Ok(toml) => println!("{}", toml),
                            Err(e) => {
                                helpers::error(format!("Failed to generate config: {}", e));
                                std::process::exit(1);
                            }
                        }
                        println!();
                        helpers::tip(tips::CONFIG_FILE);
                    }
                    Err(e) => {
                        helpers::error(format!("Failed to load config: {}", e));
                        std::process::exit(1);
                    }
                }
            }
        }

        Commands::Version => {
            println!("xcargo {}", env!("CARGO_PKG_VERSION"));
            println!("Cross-compilation, zero friction 🎯");
            println!();
            println!("https://github.com/ibrahimcesar/xcargo");
        }
    }

    Ok(())
}