rialoman 0.2.0

Rialo native toolchain manager
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
610
611
612
613
614
615
616
617
618
619
620
//! Clap-based CLI surface for rialoman.
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{fs, io, path::PathBuf};

use anyhow::{anyhow, bail, Context, Result};
use clap::{Parser, Subcommand};

use crate::{
    current::CurrentManager,
    manifest::Manifest,
    release::ReleaseService,
    remote::RemoteClient,
    spec::{Channel, InstallSpec, ReleaseId, VersionSpec},
    RialoDirs,
};

/// rialoman CLI entrypoint arguments.
#[derive(Parser, Debug)]
#[command(author, version, about = "Rialo release and toolchain manager", long_about = None)]
pub struct Cli {
    /// Override RIALO_HOME for this invocation.
    #[arg(long = "home", env = "RIALO_HOME", value_name = "PATH")]
    pub home_override: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Install a release (optionally set as default).
    Install {
        #[arg(value_name = "SPEC")]
        spec: InstallSpec,
        #[arg(long, help = "Install and make this release the current default")]
        default: bool,
        #[arg(long, help = "Skip installing the compatible Rust toolchain")]
        no_toolchain: bool,
    },
    /// Switch to an already-installed release.
    Use {
        #[arg(value_name = "SPEC")]
        spec: InstallSpec,
    },
    /// List installed releases.
    List,
    /// Uninstall a release.
    Uninstall {
        #[arg(value_name = "SPEC")]
        spec: InstallSpec,
        #[arg(long)]
        force: bool,
    },
    /// Show the currently selected release.
    Current,
    /// Print the path to a binary from the current release.
    Which {
        #[arg(value_name = "BINARY")]
        binary: String,
    },
    /// List remote channels (latest only).
    ListRemote,
    /// Manage Rust toolchains for building programs.
    #[command(subcommand)]
    Toolchain(ToolchainCommands),
}

#[derive(Subcommand, Debug)]
pub enum ToolchainCommands {
    /// Install a Rust toolchain
    Install {
        /// Toolchain name (use "rialo-rust" or "rust")
        name: String,
        /// Toolchain version (optional, uses default if not specified)
        #[arg(long)]
        version: Option<String>,
        /// Build from source instead of downloading prebuilt binaries
        #[arg(long)]
        from_source: bool,
    },
    /// List installed Rust toolchains
    List,
    /// Validate a Rust toolchain installation
    Validate {
        /// Toolchain name (use "rialo-rust" or "rust")
        name: String,
        /// Toolchain version (optional, uses default if not specified)
        #[arg(long)]
        version: Option<String>,
    },
    /// Uninstall a Rust toolchain
    Uninstall {
        /// Toolchain name (use "rialo-rust" or "rust")
        name: String,
        /// Toolchain version (optional, uses default if not specified)
        #[arg(long)]
        version: Option<String>,
    },
    /// Build Rialo Rust toolchain from source
    Build {
        /// Toolchain version (optional, uses default if not specified)
        #[arg(long)]
        version: Option<String>,
    },
    /// Upload a Rust toolchain to S3
    Upload {
        /// Toolchain name (use "rialo-rust" or "rust")
        name: String,
        /// Toolchain version (optional, uses default if not specified)
        #[arg(long)]
        version: Option<String>,
    },
    /// Build Rialo Rust toolchain from source and upload to S3
    BuildAndUpload {
        /// Toolchain version (optional, uses default if not specified)
        #[arg(long)]
        version: Option<String>,
    },
}

pub fn run(cli: Cli) -> Result<()> {
    let dirs = RialoDirs::new(cli.home_override.as_ref())?;

    // Ensure directory layout exists and migrate from old structure if needed.
    // This runs early so all commands work correctly with the current layout.
    dirs.ensure_layout()?;

    let remote = RemoteClient::new()?;
    let service = ReleaseService::new(dirs.clone(), remote);

    match cli.command {
        Commands::Install {
            spec,
            default,
            no_toolchain,
        } => {
            let id = service.install(&spec, default)?;
            println!("Installed {id}");

            if !no_toolchain {
                if let Some(tc_version) = service.load_manifest(&id)?.rust_toolchain_version() {
                    use rialo_build_lib::{RialoRustToolchain, Toolchain};

                    eprintln!("Installing Rust toolchain {}...", tc_version);
                    let toolchain = RialoRustToolchain::with_version(tc_version)?;
                    if let Err(e) = toolchain.install() {
                        eprintln!("⚠️  Failed to install Rust toolchain: {}", e);
                        eprintln!("   You can install it manually with:");
                        eprintln!(
                            "   rialoman toolchain install rialo-rust --version {}",
                            tc_version
                        );
                    }
                }
            }
        }
        Commands::Use { spec } => {
            // For now require explicit version (install resolves latest).
            let resolved = match spec.version {
                VersionSpec::Explicit(v) => v.clone(),
                VersionSpec::Latest => {
                    bail!("`use` requires an explicit version. Try running `rialoman install {}` first", spec.channel)
                }
            };
            let id = ReleaseId::new(spec.channel, resolved);
            service.use_existing(&id)?;
            println!("Now using {id}");
        }
        Commands::List => list_installed(&dirs)?,

        Commands::Uninstall { spec, force } => {
            let resolved = match spec.version {
                crate::spec::VersionSpec::Explicit(ref v) => v.clone(),
                crate::spec::VersionSpec::Latest => {
                    bail!("`uninstall` requires an explicit version; install it first")
                }
            };
            let id = ReleaseId::new(spec.channel, resolved);
            service.uninstall(&id, force)?;
            println!("Removed {id}");
        }
        Commands::Current => show_current(&dirs)?,
        Commands::Which { binary } => which_binary(&dirs, &binary)?,
        Commands::ListRemote => list_remote()?,
        Commands::Toolchain(toolchain_cmd) => handle_toolchain_command(toolchain_cmd)?,
    }

    Ok(())
}

fn list_installed(dirs: &RialoDirs) -> Result<()> {
    let current = CurrentManager::new(dirs.current_file().clone()).load()?;

    let releases = match std::fs::read_dir(dirs.releases()) {
        Ok(dir) => dir,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e.into()),
    };

    for entry in releases {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let channel = entry.file_name();
        let channel_name = channel.to_string_lossy();

        let is_known = Channel::KNOWN
            .iter()
            .any(|known| known.as_str() == channel_name.as_ref());
        if !is_known {
            eprintln!("warn: found unrecognized channel directory '{channel_name}'");
            continue;
        }

        let version_entries = std::fs::read_dir(entry.path())?;
        for version_entry in version_entries {
            let version_entry = version_entry?;
            if !version_entry.file_type()?.is_dir() {
                continue;
            }
            let version = version_entry.file_name();
            let version = version.to_string_lossy();
            let is_current = current
                .as_ref()
                .is_some_and(|cur| cur.channel == channel_name && cur.version == version);
            let marker = if is_current { " (current)" } else { "" };
            println!("{channel_name}@{version}{marker}");

            if is_current {
                if let Err(e) = print_toolchain_status(dirs, &channel_name, &version) {
                    eprintln!("  ⚠️  Could not read toolchain status: {}", e);
                }
            }
        }
    }
    Ok(())
}

fn show_current(dirs: &RialoDirs) -> Result<()> {
    let current = CurrentManager::new(dirs.current_file().clone()).load()?;
    match current {
        Some(c) => println!("{}@{}", c.channel, c.version),
        None => bail!("No active release"),
    }
    Ok(())
}

fn which_binary(dirs: &RialoDirs, binary: &str) -> Result<()> {
    let current = CurrentManager::new(dirs.current_file().clone()).load()?;
    let Some(cur) = current else {
        bail!("No active release");
    };

    let path = dirs
        .releases()
        .join(&cur.channel)
        .join(&cur.version)
        .join("bin")
        .join(binary);

    if path.exists() {
        println!("{}", path.display());
        Ok(())
    } else {
        bail!("binary `{binary}` not found in current release")
    }
}

fn list_remote() -> Result<()> {
    let remote = RemoteClient::new()?;
    for channel in crate::spec::Channel::KNOWN {
        let spec = InstallSpec {
            channel: *channel,
            version: VersionSpec::Latest,
        };

        if let Ok(manifest) = remote.fetch_manifest(&spec) {
            println!("{}@{}", manifest.channel, manifest.version);
        }
    }
    Ok(())
}

// ============================================================================
// Toolchain Management Functions
// ============================================================================

fn handle_toolchain_command(command: ToolchainCommands) -> Result<()> {
    match command {
        ToolchainCommands::Install {
            name,
            version,
            from_source,
        } => {
            install_rust_toolchain(&name, version.as_deref(), from_source)?;
        }
        ToolchainCommands::List => {
            list_rust_toolchains()?;
        }
        ToolchainCommands::Validate { name, version } => {
            validate_rust_toolchain(&name, version.as_deref())?;
        }
        ToolchainCommands::Uninstall { name, version } => {
            uninstall_rust_toolchain(&name, version.as_deref())?;
        }
        ToolchainCommands::Build { version } => {
            build_toolchain_from_source(version.as_deref())?;
        }
        ToolchainCommands::Upload { name, version } => {
            upload_toolchain(&name, version.as_deref())?;
        }
        ToolchainCommands::BuildAndUpload { version } => {
            build_and_upload_toolchain(version.as_deref())?;
        }
    }
    Ok(())
}

fn install_rust_toolchain(name: &str, version: Option<&str>, from_source: bool) -> Result<()> {
    use rialo_build_lib::{RialoRustToolchain, SourceBuildable, Toolchain};

    if !matches!(name, "rialo-rust" | "rust") {
        bail!("Unknown toolchain: {name}. Use 'rialo-rust' or 'rust' as the toolchain name",);
    }

    let manifest_version = get_current_toolchain_version().ok();

    // Warn if explicit version differs from what manifest specifies
    if let (Some(explicit), Some(expected)) = (version, manifest_version.as_ref()) {
        if explicit != expected {
            eprintln!("⚠️  Warning: Installing rialo-rust {explicit} but current release specifies {expected}");
            eprintln!("   This will change what `cargo +rialo` points to.");
            eprintln!("   To sync back to the release version, run:");
            eprintln!("   rialoman toolchain install rialo-rust");
        }
    }

    // Resolve: explicit > manifest > auto-detect
    let toolchain = match version.or(manifest_version.as_deref()) {
        Some(v) => RialoRustToolchain::with_version(v),
        None => RialoRustToolchain::new(),
    }?;

    if !from_source {
        toolchain.install()?;
    } else {
        println!("Building Rialo Rust toolchain from source...");
        println!("This will take 30-60 minutes depending on your system.");
        println!();

        let config = toolchain.get_source_config()?;
        toolchain.build_from_source(&config)?;
    }
    toolchain.validate()?;

    Ok(())
}

fn list_rust_toolchains() -> Result<()> {
    use rialo_build_lib::toolchain;

    let toolchains = toolchain::list_installed_toolchains()?;

    if toolchains.is_empty() {
        println!("No Rust toolchains installed.");
        println!(
            "Install a toolchain with: rialoman toolchain install rialo-rust --version <VERSION>"
        );
        return Ok(());
    }

    println!("Installed Rust toolchains:\n");

    let rialo_rust_versions: Vec<_> = toolchains
        .into_iter()
        .filter_map(|(name, version)| (name == "rialo-rust").then_some(version))
        .collect();

    // Show rialo-rust toolchains
    if !rialo_rust_versions.is_empty() {
        println!("rialo-rust:");
        for version in rialo_rust_versions {
            println!("  {version}");
        }
    }

    Ok(())
}

fn validate_rust_toolchain(name: &str, version: Option<&str>) -> Result<()> {
    use rialo_build_lib::{RialoRustToolchain, Toolchain};

    match name {
        "rialo-rust" | "rust" => {
            let toolchain = if let Some(v) = version {
                RialoRustToolchain::with_version(v)?
            } else {
                RialoRustToolchain::new()?
            };
            toolchain.validate()?;
        }
        _ => {
            bail!(
                "Unknown toolchain: {}. Use 'rialo-rust' or 'rust' as the toolchain name",
                name
            );
        }
    }
    Ok(())
}

fn uninstall_rust_toolchain(name: &str, version: Option<&str>) -> Result<()> {
    use rialo_build_lib::RialoRustToolchain;

    match name {
        "rialo-rust" | "rust" => {
            let toolchain = if let Some(v) = version {
                RialoRustToolchain::with_version(v)?
            } else {
                RialoRustToolchain::new()?
            };
            toolchain.uninstall()?;
        }
        _ => {
            bail!(
                "Unknown toolchain: {}. Use 'rialo-rust' or 'rust' as the toolchain name",
                name
            );
        }
    }
    Ok(())
}

fn build_toolchain_from_source(version: Option<&str>) -> Result<()> {
    use rialo_build_lib::{RialoRustToolchain, SourceBuildable, Toolchain};

    println!("Building Rialo Rust toolchain from source...");

    let toolchain = if let Some(v) = version {
        RialoRustToolchain::with_version(v)?
    } else {
        RialoRustToolchain::new()?
    };

    println!("This will take 30-60 minutes depending on your system.");
    println!();

    let config = toolchain.get_source_config()?;
    toolchain.build_from_source(&config)?;
    toolchain.validate()?;

    Ok(())
}

fn upload_toolchain(name: &str, version: Option<&str>) -> Result<()> {
    use rialo_build_lib::{RialoRustToolchain, Toolchain};

    validate_toolchain_name(name)?;

    if !check_aws_credentials() {
        bail!(
            "AWS credentials not found. Please set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY \
             environment variables, or configure AWS credentials via AWS CLI or config files."
        );
    }

    println!("Uploading toolchain to S3...");
    println!(
        "Bucket: {}",
        std::env::var("RIALO_TOOLCHAIN_S3_BUCKET")
            .unwrap_or_else(|_| "rialo-artifacts".to_string())
    );
    println!();

    match name {
        "rialo-rust" | "rust" => {
            let toolchain = if let Some(v) = version {
                RialoRustToolchain::with_version(v)?
            } else {
                RialoRustToolchain::new()?
            };

            if !toolchain.is_installed()? {
                bail!(
                    "Rialo Rust toolchain is not installed. Install it first with: \
                     rialoman toolchain install rialo-rust"
                );
            }

            toolchain.upload_to_s3()?;
        }
        _ => unreachable!("Toolchain name already validated"),
    }

    println!();
    println!("✅ Upload complete");
    Ok(())
}

fn build_and_upload_toolchain(version: Option<&str>) -> Result<()> {
    use rialo_build_lib::{RialoRustToolchain, SourceBuildable, Toolchain};

    if !check_aws_credentials() {
        bail!(
            "AWS credentials required for upload. Please set AWS_ACCESS_KEY_ID and \
             AWS_SECRET_ACCESS_KEY environment variables, or configure AWS credentials \
             via AWS CLI or config files."
        );
    }

    println!("Building Rialo Rust toolchain from source and uploading to S3...");
    println!(
        "Bucket: {}",
        std::env::var("RIALO_TOOLCHAIN_S3_BUCKET")
            .unwrap_or_else(|_| "rialo-artifacts".to_string())
    );
    println!();
    println!("This will take 30-60 minutes depending on your system.");
    println!();

    let toolchain = if let Some(v) = version {
        RialoRustToolchain::with_version(v)?
    } else {
        RialoRustToolchain::new()?
    };

    let config = toolchain.get_source_config()?;
    toolchain.build_from_source(&config)?;
    toolchain.validate()?;

    println!();
    println!("Build completed successfully. Now uploading to S3...");
    println!();

    toolchain.upload_to_s3()?;

    println!();
    println!("✅ Build and upload complete");
    Ok(())
}

fn validate_toolchain_name(name: &str) -> Result<()> {
    match name {
        "rialo-rust" | "rust" => Ok(()),
        _ => bail!(
            "Unknown toolchain: {}. Use 'rialo-rust' or 'rust' as the toolchain name",
            name
        ),
    }
}

fn check_aws_credentials() -> bool {
    std::env::var("AWS_ACCESS_KEY_ID").is_ok() && std::env::var("AWS_SECRET_ACCESS_KEY").is_ok()
}

/// Get toolchain version from current release manifest.
fn get_current_toolchain_version() -> Result<String> {
    let dirs = RialoDirs::new(None)?;
    let current = CurrentManager::new(dirs.current_file().clone())
        .load()?
        .ok_or_else(|| {
            anyhow!("No active release. Use --version to specify a toolchain version.")
        })?;

    let manifest_path = dirs
        .releases()
        .join(current.channel.as_str())
        .join(&current.version)
        .join("manifest.json");

    let manifest: Manifest = serde_json::from_str(
        &fs::read_to_string(&manifest_path)
            .with_context(|| format!("failed to read manifest at {}", manifest_path.display()))?,
    )
    .context("failed to parse manifest")?;

    manifest
        .rust_toolchain_version()
        .map(String::from)
        .ok_or_else(|| {
            anyhow!(
                "Release {}@{} does not specify a toolchain. Use --version to specify one.",
                current.channel,
                current.version
            )
        })
}

/// Print toolchain status for a release (if manifest specifies one).
fn print_toolchain_status(dirs: &RialoDirs, channel: &str, version: &str) -> Result<()> {
    use rialo_build_lib::toolchain::list_installed_toolchains;

    let manifest_path = dirs
        .releases()
        .join(channel)
        .join(version)
        .join("manifest.json");
    let contents = fs::read_to_string(&manifest_path)
        .with_context(|| format!("failed to read manifest at {}", manifest_path.display()))?;
    let manifest: Manifest = serde_json::from_str(&contents).context("failed to parse manifest")?;

    let Some(tc_version) = manifest.rust_toolchain_version() else {
        return Ok(());
    };

    let installed = list_installed_toolchains()
        .map(|tc| tc.iter().any(|(n, v)| n == "rialo-rust" && v == tc_version))
        .unwrap_or(false);

    let (icon, suffix) = if installed {
        ("", "")
    } else {
        ("", " (not installed)")
    };
    println!("  {} rialo-rust {}{}", icon, tc_version, suffix);
    Ok(())
}