mecha10-cli 0.1.47

Mecha10 CLI tool
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
//! Build command handler
//!
//! Orchestrates project building using cargo with target-specific features.
//! Supports both native builds (cargo) and Docker-based cross-compilation.

use crate::commands::{BuildCommand, BuildTargetArgs, TargetArch, VersionBump};
use crate::context::CliContext;
use crate::paths;
use crate::templates::RustTemplates;
use anyhow::{Context, Result};
use std::path::Path;
use std::process::Command;

/// Build target type
#[derive(Debug, Clone, Copy)]
pub enum BuildTarget {
    /// Robot nodes (edge/on-robot)
    Robot,
    /// Remote nodes (cloud/remote server)
    Remote,
}

impl BuildTarget {
    /// Get the cargo feature flags for this target
    fn features(&self) -> &'static str {
        match self {
            // Robot target includes gpio for hardware access
            BuildTarget::Robot => "target-robot,gpio",
            BuildTarget::Remote => "target-remote",
        }
    }

    /// Get display name for this target
    fn display_name(&self) -> &'static str {
        match self {
            BuildTarget::Robot => "Robot",
            BuildTarget::Remote => "Remote",
        }
    }

    /// Get description for this target
    fn description(&self) -> &'static str {
        match self {
            BuildTarget::Robot => "edge/on-robot nodes",
            BuildTarget::Remote => "cloud/remote server nodes",
        }
    }

    /// Get string representation for metadata
    fn as_str(&self) -> &'static str {
        match self {
            BuildTarget::Robot => "robot",
            BuildTarget::Remote => "remote",
        }
    }
}

/// Handle the build command
pub async fn handle_build(ctx: &mut CliContext, command: &BuildCommand) -> Result<()> {
    match command {
        BuildCommand::Robot(args) => build_target(ctx, BuildTarget::Robot, args).await,
        BuildCommand::Remote(args) => build_target(ctx, BuildTarget::Remote, args).await,
    }
}

/// Build for a specific target
async fn build_target(ctx: &mut CliContext, target: BuildTarget, args: &BuildTargetArgs) -> Result<()> {
    println!();
    println!("🔨 Building Mecha10 Project - {} Target", target.display_name());
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!();

    // Verify we're in a project
    if !ctx.is_project_initialized() {
        println!("⚠️  Not in a Mecha10 project directory");
        println!();
        return Err(anyhow::anyhow!("Not in a Mecha10 project"));
    }

    // Detect project to ensure it's valid
    let project = ctx.project()?;
    let project_name = project.name()?;

    // Set default_mode in mecha10.json (production unless --dev flag)
    let default_mode = if args.dev { "dev" } else { "production" };
    update_default_mode(ctx, default_mode).await?;
    println!("Environment: {}", default_mode);

    // Handle version update if requested
    let version = if let Some(bump) = &args.bump {
        let new_version = update_version(ctx, Some(*bump), None).await?;
        println!("Version: {} (bumped)", new_version);
        Some(new_version)
    } else if let Some(version) = &args.version {
        let new_version = update_version(ctx, None, Some(version.clone())).await?;
        println!("Version: {} (set)", new_version);
        Some(new_version)
    } else {
        // Read current version for display
        let config = ctx.load_project_config().await?;
        println!("Version: {}", config.version);
        None
    };

    println!("Project: {}", project_name);
    println!("Target:  {} ({})", target.display_name(), target.description());
    println!();

    // Regenerate main.rs from current CLI template
    // This ensures projects created with older CLI versions get the latest fixes
    regenerate_main_rs(ctx, &project_name).await?;

    // Route to Docker or cargo build
    let result = if args.docker {
        build_with_docker(ctx, target, args, &project_name).await
    } else {
        build_with_cargo(ctx, target, args).await
    };

    // Show version in success message if it was updated
    if let Some(v) = version {
        if result.is_ok() {
            println!("📦 Built version: {}", v);
            println!();
        }
    }

    result
}

/// Build using native cargo
async fn build_with_cargo(ctx: &CliContext, target: BuildTarget, args: &BuildTargetArgs) -> Result<()> {
    println!("Feature: --features {}", target.features());

    if args.release {
        println!("Mode:    Release (optimized)");
    } else {
        println!("Mode:    Debug");
    }

    if let Some(arch) = &args.target {
        println!("Arch:    {} (cross-compilation)", arch);
    } else {
        println!("Arch:    Host architecture");
    }
    println!();

    // Build using cargo
    println!("Running cargo build...");
    println!();

    let mut cmd = Command::new("cargo");
    cmd.arg("build")
        .arg("--no-default-features")
        .arg("--features")
        .arg(target.features())
        .current_dir(&ctx.working_dir);

    if args.release {
        cmd.arg("--release");
    }

    if let Some(target_arch) = &args.target {
        cmd.arg("--target").arg(target_arch);
    }

    let status = cmd.status()?;

    println!();

    if status.success() {
        println!("✅ Build completed successfully");
        println!();

        // Show output location
        let build_profile = if args.release { "release" } else { "debug" };
        let target_dir = paths::target_path_with_triple(args.target.as_deref(), build_profile);

        println!("Binaries location: {}", target_dir);
        println!();
    } else {
        println!("❌ Build failed");
        println!();
        return Err(anyhow::anyhow!("Build failed"));
    }

    Ok(())
}

/// Build using Docker for cross-compilation
async fn build_with_docker(
    ctx: &CliContext,
    target: BuildTarget,
    args: &BuildTargetArgs,
    project_name: &str,
) -> Result<()> {
    let arch = args.arch;

    println!("Build:   Docker cross-compilation");
    println!("Arch:    {} ({})", arch.build_arg(), arch.docker_platform());
    println!("Mode:    Release (Docker builds are always optimized)");
    println!();

    // Check for robot-builder.Dockerfile
    let dockerfile_path = ctx.working_dir.join(paths::docker::DOCKERFILE_ROBOT_BUILDER);
    if !dockerfile_path.exists() {
        println!("⚠️  robot-builder.Dockerfile not found");
        println!();
        println!("This file should have been created by `mecha10 init`.");
        println!("You can create it manually or re-initialize your project.");
        println!();
        return Err(anyhow::anyhow!(
            "Missing docker/robot-builder.Dockerfile. Run `mecha10 init` to create it."
        ));
    }

    // Create dist directory
    let dist_dir = ctx.working_dir.join("dist");
    tokio::fs::create_dir_all(&dist_dir).await?;

    // Ensure Cargo.lock exists (required by Docker build)
    let cargo_lock_path = ctx.working_dir.join("Cargo.lock");
    if !cargo_lock_path.exists() {
        println!("Generating Cargo.lock...");
        let status = Command::new("cargo")
            .arg("generate-lockfile")
            .current_dir(&ctx.working_dir)
            .status()
            .context("Failed to run cargo generate-lockfile")?;
        if !status.success() {
            return Err(anyhow::anyhow!("Failed to generate Cargo.lock"));
        }
        println!("✅ Cargo.lock generated");
        println!();
    }

    // Generate image tag
    let image_tag = format!("{}-builder-{}", project_name, arch.build_arg());

    // Step 1: Build Docker image
    println!("Step 1/3: Building Docker image...");
    println!();

    let build_status = build_docker_image(ctx, &dockerfile_path, &image_tag, arch)?;
    if !build_status.success() {
        println!();
        println!("❌ Docker build failed");
        return Err(anyhow::anyhow!("Docker build failed"));
    }

    println!();
    println!("✅ Docker image built: {}", image_tag);
    println!();

    // Step 2: Extract binary from container
    println!("Step 2/3: Extracting binary...");
    println!();

    extract_binary_from_image(&image_tag, &dist_dir, project_name)?;

    println!("✅ Binary extracted to dist/");
    println!();

    // Step 3: Copy mecha10.json
    println!("Step 3/3: Copying configuration...");
    println!();

    extract_config_from_image(&image_tag, &dist_dir)?;

    // Add build metadata to dist/mecha10.json for upload auto-detection
    add_build_metadata(&dist_dir, target, arch)?;

    println!("✅ Configuration extracted to dist/");
    println!();

    // Summary
    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    println!("✅ Build completed successfully!");
    println!();
    println!("Output files:");
    println!("  dist/{}", project_name);
    println!("  dist/mecha10.json");
    if dist_dir.join("configs").exists() {
        println!("  dist/configs/");
    }
    println!();
    println!("Target: Linux {} ({})", arch.build_arg(), arch.docker_platform());
    println!();

    Ok(())
}

/// Build Docker image with the specified architecture
fn build_docker_image(
    ctx: &CliContext,
    dockerfile_path: &Path,
    image_tag: &str,
    arch: TargetArch,
) -> Result<std::process::ExitStatus> {
    let mut cmd = Command::new("docker");
    cmd.arg("build")
        .arg("-f")
        .arg(dockerfile_path)
        .arg("--build-arg")
        .arg(format!("TARGET_ARCH={}", arch.build_arg()))
        .arg("--platform")
        .arg(arch.docker_platform())
        .arg("-t")
        .arg(image_tag)
        .arg(".")
        .current_dir(&ctx.working_dir);

    cmd.status().context("Failed to run docker build")
}

/// Extract binary from Docker image
fn extract_binary_from_image(image_tag: &str, dist_dir: &Path, project_name: &str) -> Result<()> {
    let container_name = format!("{}-extract", image_tag);

    // Create container
    let create_status = Command::new("docker")
        .args(["create", "--name", &container_name, image_tag])
        .status()
        .context("Failed to create extraction container")?;

    if !create_status.success() {
        return Err(anyhow::anyhow!("Failed to create extraction container"));
    }

    // Copy binary
    let binary_result = Command::new("docker")
        .args([
            "cp",
            &format!("{}:/output/{}", container_name, project_name),
            dist_dir.join(project_name).to_str().unwrap(),
        ])
        .status();

    // Cleanup container (always, even if copy fails)
    let _ = Command::new("docker").args(["rm", &container_name]).status();

    let copy_status = binary_result.context("Failed to copy binary from container")?;
    if !copy_status.success() {
        return Err(anyhow::anyhow!("Failed to copy binary from container"));
    }

    // Make binary executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let binary_path = dist_dir.join(project_name);
        let mut perms = std::fs::metadata(&binary_path)?.permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&binary_path, perms)?;
    }

    Ok(())
}

/// Extract mecha10.json and configs/ from Docker image
fn extract_config_from_image(image_tag: &str, dist_dir: &Path) -> Result<()> {
    let container_name = format!("{}-extract-config", image_tag);

    // Create container
    let create_status = Command::new("docker")
        .args(["create", "--name", &container_name, image_tag])
        .status()
        .context("Failed to create extraction container")?;

    if !create_status.success() {
        return Err(anyhow::anyhow!("Failed to create extraction container"));
    }

    // Copy mecha10.json
    let config_result = Command::new("docker")
        .args([
            "cp",
            &format!("{}:/output/mecha10.json", container_name),
            dist_dir.join("mecha10.json").to_str().unwrap(),
        ])
        .status();

    // Copy configs/ directory (optional - may not exist in all projects)
    let configs_result = Command::new("docker")
        .args([
            "cp",
            &format!("{}:/output/configs", container_name),
            dist_dir.to_str().unwrap(),
        ])
        .status();

    // Cleanup container
    let _ = Command::new("docker").args(["rm", &container_name]).status();

    let copy_status = config_result.context("Failed to copy config from container")?;
    if !copy_status.success() {
        return Err(anyhow::anyhow!("Failed to copy mecha10.json from container"));
    }

    // configs/ is optional - don't fail if it doesn't exist
    if let Ok(status) = configs_result {
        if status.success() {
            println!("  Extracted configs/ directory");
        }
    }

    Ok(())
}

/// Update default_mode in mecha10.json
///
/// Sets the lifecycle.default_mode field which determines which environment
/// configuration is used at runtime (dev or production).
async fn update_default_mode(ctx: &CliContext, mode: &str) -> Result<()> {
    let config_path = ctx.working_dir.join(paths::PROJECT_CONFIG);

    // Read current config
    let config_content = tokio::fs::read_to_string(&config_path)
        .await
        .context("Failed to read mecha10.json")?;

    let mut config: serde_json::Value =
        serde_json::from_str(&config_content).context("Failed to parse mecha10.json")?;

    // Get current mode for comparison (clone to owned String to avoid borrow issues)
    let current_mode = config["lifecycle"]["default_mode"]
        .as_str()
        .unwrap_or("dev")
        .to_string();

    // Only update if different
    if current_mode != mode {
        config["lifecycle"]["default_mode"] = serde_json::json!(mode);

        // Write back
        let updated_content = serde_json::to_string_pretty(&config)?;
        tokio::fs::write(&config_path, updated_content)
            .await
            .context("Failed to write mecha10.json")?;

        println!("📝 Updated default_mode: {}{}", current_mode, mode);
    }

    Ok(())
}

/// Update version in mecha10.json
///
/// Either bumps the version (patch, minor, major) or sets a specific version.
async fn update_version(ctx: &CliContext, bump: Option<VersionBump>, set_version: Option<String>) -> Result<String> {
    let config_path = ctx.working_dir.join(paths::PROJECT_CONFIG);

    // Read current config
    let config_content = tokio::fs::read_to_string(&config_path)
        .await
        .context("Failed to read mecha10.json")?;

    let mut config: serde_json::Value =
        serde_json::from_str(&config_content).context("Failed to parse mecha10.json")?;

    let current_version = config["version"].as_str().unwrap_or("0.1.0").to_string();

    // Calculate new version
    let new_version = if let Some(bump_type) = bump {
        bump_semver(&current_version, bump_type)?
    } else if let Some(version) = set_version {
        // Validate version format
        validate_semver(&version)?;
        version
    } else {
        return Ok(current_version);
    };

    // Update config
    config["version"] = serde_json::json!(new_version);

    // Write back
    let updated_content = serde_json::to_string_pretty(&config)?;
    tokio::fs::write(&config_path, updated_content)
        .await
        .context("Failed to write mecha10.json")?;

    println!("📝 Updated mecha10.json: {}{}", current_version, new_version);

    Ok(new_version)
}

/// Bump a semver version string
fn bump_semver(version: &str, bump: VersionBump) -> Result<String> {
    let parts: Vec<&str> = version.split('.').collect();

    if parts.len() < 3 {
        return Err(anyhow::anyhow!(
            "Invalid version format '{}'. Expected semver (e.g., 1.2.3)",
            version
        ));
    }

    let major: u32 = parts[0].parse().context("Invalid major version number")?;
    let minor: u32 = parts[1].parse().context("Invalid minor version number")?;
    let patch: u32 = parts[2]
        .split('-') // Handle pre-release versions like 1.2.3-beta
        .next()
        .unwrap_or("0")
        .parse()
        .context("Invalid patch version number")?;

    let (new_major, new_minor, new_patch) = match bump {
        VersionBump::Major => (major + 1, 0, 0),
        VersionBump::Minor => (major, minor + 1, 0),
        VersionBump::Patch => (major, minor, patch + 1),
    };

    Ok(format!("{}.{}.{}", new_major, new_minor, new_patch))
}

/// Validate a semver version string
fn validate_semver(version: &str) -> Result<()> {
    let parts: Vec<&str> = version.split('.').collect();

    if parts.len() < 3 {
        return Err(anyhow::anyhow!(
            "Invalid version format '{}'. Expected semver (e.g., 1.2.3)",
            version
        ));
    }

    // Validate each part is a number (allow pre-release suffix on patch)
    parts[0].parse::<u32>().context("Invalid major version number")?;
    parts[1].parse::<u32>().context("Invalid minor version number")?;
    parts[2]
        .split('-')
        .next()
        .unwrap_or("0")
        .parse::<u32>()
        .context("Invalid patch version number")?;

    Ok(())
}

/// Regenerate main.rs from current CLI template
///
/// This ensures projects created with older CLI versions get the latest
/// template fixes (e.g., lifetime fixes, API changes).
async fn regenerate_main_rs(ctx: &CliContext, project_name: &str) -> Result<()> {
    let main_rs_path = ctx.working_dir.join(paths::rust::MAIN_RS);

    // Only regenerate if main.rs exists (don't create for non-standard projects)
    if !main_rs_path.exists() {
        return Ok(());
    }

    println!("Updating src/main.rs from current template...");

    let rust_templates = RustTemplates::new();
    rust_templates
        .create_main_rs(&ctx.working_dir, project_name)
        .await
        .context("Failed to regenerate main.rs")?;

    println!("✅ src/main.rs updated");
    println!();

    Ok(())
}

/// Add build metadata to dist/mecha10.json
///
/// Adds build_target and build_arch fields for upload auto-detection.
fn add_build_metadata(dist_dir: &Path, target: BuildTarget, arch: TargetArch) -> Result<()> {
    let config_path = dist_dir.join("mecha10.json");

    // Read current config
    let config_content = std::fs::read_to_string(&config_path).context("Failed to read dist/mecha10.json")?;

    let mut config: serde_json::Value =
        serde_json::from_str(&config_content).context("Failed to parse dist/mecha10.json")?;

    // Add build metadata
    config["build_target"] = serde_json::json!(target.as_str());
    config["build_arch"] = serde_json::json!(arch.build_arg());

    // Write back
    let updated_content = serde_json::to_string_pretty(&config)?;
    std::fs::write(&config_path, updated_content).context("Failed to write dist/mecha10.json")?;

    Ok(())
}