canic-cli 0.32.6

Operator CLI for Canic fleet backup and restore workflows
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use crate::{
    args::{
        local_network, parse_matches, print_help_or_version, string_option, string_values,
        value_arg,
    },
    scaffold, version_text,
};
use canic_host::{
    install_root::discover_current_canic_config_choices,
    release_set::{configured_fleet_name, configured_fleet_roles, workspace_root},
    table::WhitespaceTable,
};
use clap::{Arg, Command as ClapCommand};
use std::{
    ffi::OsString,
    fs,
    io::{self, BufRead, Write},
    path::{Path, PathBuf},
};
use thiserror::Error as ThisError;

const FLEET_HEADER: &str = "FLEET";
const NETWORK_HEADER: &str = "NETWORK";
const CONFIG_HEADER: &str = "CONFIG";
const CANISTERS_HEADER: &str = "CANISTERS";
const ROLE_PREVIEW_LIMIT: usize = 6;
const FLEET_HELP_AFTER: &str = "\
Examples:
  canic fleet list
  canic fleet create demo
  canic fleet delete demo";
const FLEET_LIST_HELP_AFTER: &str = "\
Examples:
  canic fleet list
  canic fleet list --network local

Commands that operate on one fleet take the fleet name as a positional argument.";
const FLEET_DELETE_HELP_AFTER: &str = "\
Examples:
  canic fleet delete demo

This removes the matching config-defined fleet directory after you type the
fleet name exactly.";

///
/// FleetCommandError
///

#[derive(Debug, ThisError)]
pub enum FleetCommandError {
    #[error("{0}")]
    Usage(String),

    #[error("missing fleet name")]
    MissingFleetName,

    #[error("multiple fleet names provided")]
    ConflictingFleetName,

    #[error("no Canic fleet configs found under fleets; run canic fleet create <name>")]
    NoConfigChoices,

    #[error("unknown fleet {0}; run canic fleet list to inspect config-defined fleets")]
    UnknownFleet(String),

    #[error(
        "multiple configs declare fleet {0}; use distinct [fleet].name values before selecting it"
    )]
    DuplicateFleet(String),

    #[error("fleet delete cancelled")]
    DeleteCancelled,

    #[error("refusing to delete fleet {fleet}; target {target} is not under fleets")]
    UnsafeDeleteTarget { fleet: String, target: String },

    #[error("fleet {0} config does not have a parent directory")]
    MissingFleetDirectory(String),

    #[error("fleet create: {0}")]
    Create(String),

    #[error(transparent)]
    Io(#[from] io::Error),

    #[error(transparent)]
    Host(#[from] Box<dyn std::error::Error>),
}

///
/// FleetOptions
///

#[derive(Clone, Debug, Eq, PartialEq)]
struct FleetOptions {
    network: String,
}

///
/// DeleteFleetOptions
///

#[derive(Clone, Debug, Eq, PartialEq)]
struct DeleteFleetOptions {
    fleet: String,
}

///
/// FleetListRow
///

#[derive(Clone, Debug, Eq, PartialEq)]
struct FleetListRow {
    fleet: String,
    network: String,
    config: String,
    canisters: String,
}

/// Run the fleet default command family.
pub fn run<I>(args: I) -> Result<(), FleetCommandError>
where
    I: IntoIterator<Item = OsString>,
{
    let args = args.into_iter().collect::<Vec<_>>();
    if print_help_or_version(&args, usage, version_text()) {
        return Ok(());
    }

    let mut args = args.into_iter();
    match args
        .next()
        .and_then(|arg| arg.into_string().ok())
        .as_deref()
    {
        None => {
            println!("{}", usage());
            Ok(())
        }
        Some("create") => run_create(args),
        Some("delete") => run_delete(args),
        Some("list") => run_list(args),
        _ => Err(FleetCommandError::Usage(usage())),
    }
}

// Run the config-defined fleet creation subcommand.
fn run_create<I>(args: I) -> Result<(), FleetCommandError>
where
    I: IntoIterator<Item = OsString>,
{
    let args = args.into_iter().collect::<Vec<_>>();
    if print_help_or_version(&args, create_usage, version_text()) {
        return Ok(());
    }

    scaffold::run_fleet_create(args).map_err(|err| FleetCommandError::Create(err.to_string()))
}

// Run the config-defined fleet listing subcommand.
fn run_list<I>(args: I) -> Result<(), FleetCommandError>
where
    I: IntoIterator<Item = OsString>,
{
    let args = args.into_iter().collect::<Vec<_>>();
    if print_help_or_version(&args, list_usage, version_text()) {
        return Ok(());
    }

    let options = FleetOptions::parse(args)?;
    let workspace_root = workspace_root()?;
    let choices = discover_current_canic_config_choices()?;
    if choices.is_empty() {
        return Err(FleetCommandError::NoConfigChoices);
    }
    println!(
        "{}",
        render_fleet_list(&workspace_root, &choices, &options.network)
    );
    Ok(())
}

// Run the destructive config-defined fleet deletion subcommand.
fn run_delete<I>(args: I) -> Result<(), FleetCommandError>
where
    I: IntoIterator<Item = OsString>,
{
    let args = args.into_iter().collect::<Vec<_>>();
    if print_help_or_version(&args, delete_usage, version_text()) {
        return Ok(());
    }

    let options = DeleteFleetOptions::parse(args)?;
    let workspace_root = workspace_root()?;
    let target = delete_target_dir(&workspace_root, &options.fleet)?;
    confirm_delete_fleet(&options.fleet, &target, io::stdin().lock(), io::stdout())?;
    fs::remove_dir_all(&target)?;

    println!("Deleted Canic fleet:");
    println!("  fleet: {}", options.fleet);
    println!(
        "  path:  {}",
        display_workspace_path(&workspace_root, &target)
    );
    Ok(())
}

impl FleetOptions {
    // Parse fleet listing options.
    fn parse<I>(args: I) -> Result<Self, FleetCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        let matches = parse_matches(fleet_list_command(), args)
            .map_err(|_| FleetCommandError::Usage(list_usage()))?;

        Ok(Self {
            network: string_option(&matches, "network").unwrap_or_else(local_network),
        })
    }
}

impl DeleteFleetOptions {
    // Parse fleet deletion options.
    fn parse<I>(args: I) -> Result<Self, FleetCommandError>
    where
        I: IntoIterator<Item = OsString>,
    {
        let matches = parse_matches(fleet_delete_command(), args)
            .map_err(|_| FleetCommandError::Usage(delete_usage()))?;
        let fleet_names = string_values(&matches, "fleet");
        let fleet = match fleet_names.as_slice() {
            [] => return Err(FleetCommandError::MissingFleetName),
            [fleet] => fleet.clone(),
            _ => return Err(FleetCommandError::ConflictingFleetName),
        };

        Ok(Self { fleet })
    }
}

// Resolve the directory that owns the selected fleet config.
fn delete_target_dir(workspace_root: &Path, fleet: &str) -> Result<PathBuf, FleetCommandError> {
    let choices = discover_current_canic_config_choices()?;
    delete_target_dir_from_choices(workspace_root, &choices, fleet)
}

// Resolve the target directory from pre-discovered config choices.
fn delete_target_dir_from_choices(
    workspace_root: &Path,
    choices: &[PathBuf],
    fleet: &str,
) -> Result<PathBuf, FleetCommandError> {
    let matches = choices
        .iter()
        .cloned()
        .filter_map(|path| match configured_fleet_name(&path) {
            Ok(name) if name == fleet => Some(path),
            Ok(_) | Err(_) => None,
        })
        .collect::<Vec<_>>();

    let config_path = match matches.as_slice() {
        [] => return Err(FleetCommandError::UnknownFleet(fleet.to_string())),
        [path] => path,
        _ => return Err(FleetCommandError::DuplicateFleet(fleet.to_string())),
    };
    let target = config_path
        .parent()
        .ok_or_else(|| FleetCommandError::MissingFleetDirectory(fleet.to_string()))?
        .to_path_buf();
    if !is_safe_delete_target(workspace_root, &target) {
        return Err(FleetCommandError::UnsafeDeleteTarget {
            fleet: fleet.to_string(),
            target: target.display().to_string(),
        });
    }

    Ok(target)
}

// Restrict destructive delete targets to one fleet directory, never the fleet root.
fn is_safe_delete_target(workspace_root: &Path, target: &Path) -> bool {
    let Ok(metadata) = fs::symlink_metadata(target) else {
        return false;
    };
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return false;
    }

    let Ok(root) = workspace_root.join("fleets").canonicalize() else {
        return false;
    };
    let Ok(target) = target.canonicalize() else {
        return false;
    };
    target != root && target.starts_with(root)
}

// Confirm destructive fleet directory deletion by requiring the exact fleet name.
fn confirm_delete_fleet<R, W>(
    fleet: &str,
    target: &Path,
    mut reader: R,
    mut writer: W,
) -> Result<(), FleetCommandError>
where
    R: BufRead,
    W: Write,
{
    writeln!(writer, "Delete Canic fleet?")?;
    writeln!(writer, "  fleet: {fleet}")?;
    writeln!(writer, "  target: {}", target.display())?;
    writeln!(writer, "This will permanently remove the fleet directory.")?;
    write!(writer, "Type the fleet name to confirm: ")?;
    writer.flush()?;

    let mut answer = String::new();
    reader.read_line(&mut answer)?;
    if answer.trim() == fleet {
        return Ok(());
    }

    Err(FleetCommandError::DeleteCancelled)
}

// Build the fleet command-family parser for help rendering.
fn fleet_command() -> ClapCommand {
    ClapCommand::new("fleet")
        .bin_name("canic fleet")
        .about("Manage Canic fleets")
        .disable_help_flag(true)
        .subcommand(ClapCommand::new("create").about("Create a minimal Canic fleet"))
        .subcommand(ClapCommand::new("list").about("List config-defined Canic fleets"))
        .subcommand(ClapCommand::new("delete").about("Delete a config-defined Canic fleet"))
        .after_help(FLEET_HELP_AFTER)
}

// Build the fleet list parser.
fn fleet_list_command() -> ClapCommand {
    ClapCommand::new("list")
        .bin_name("canic fleet list")
        .about("List config-defined Canic fleets")
        .disable_help_flag(true)
        .arg(
            value_arg("network")
                .long("network")
                .value_name("name")
                .help("Network to show in the fleet list"),
        )
        .after_help(FLEET_LIST_HELP_AFTER)
}

// Build the fleet delete parser.
fn fleet_delete_command() -> ClapCommand {
    ClapCommand::new("delete")
        .bin_name("canic fleet delete")
        .about("Delete a config-defined Canic fleet directory")
        .disable_help_flag(true)
        .arg(
            Arg::new("fleet")
                .num_args(0..=1)
                .value_name("name")
                .help("Config-defined fleet name to delete"),
        )
        .after_help(FLEET_DELETE_HELP_AFTER)
}

// Render config-defined fleets as a compact whitespace table.
fn render_fleet_list(workspace_root: &Path, choices: &[PathBuf], network: &str) -> String {
    let mut table = WhitespaceTable::new([
        FLEET_HEADER,
        NETWORK_HEADER,
        CONFIG_HEADER,
        CANISTERS_HEADER,
    ]);
    for row in fleet_list_rows(workspace_root, choices, network) {
        table.push_row([row.fleet, row.network, row.config, row.canisters]);
    }
    table.render()
}

// Build operator-facing rows for config-defined fleets.
fn fleet_list_rows(workspace_root: &Path, choices: &[PathBuf], network: &str) -> Vec<FleetListRow> {
    choices
        .iter()
        .map(|path| fleet_list_row(workspace_root, path, network))
        .collect()
}

// Build one operator-facing row for an installable config.
fn fleet_list_row(workspace_root: &Path, path: &Path, network: &str) -> FleetListRow {
    let fleet = configured_fleet_name(path).unwrap_or_else(|_| "invalid config".to_string());
    FleetListRow {
        network: network.to_string(),
        fleet,
        config: display_workspace_path(workspace_root, path),
        canisters: configured_fleet_roles(path).map_or_else(
            |_| "invalid config".to_string(),
            |roles| format_canister_summary(&roles),
        ),
    }
}

// Format the root-subnet canister count with a bounded role preview.
fn format_canister_summary(roles: &[String]) -> String {
    if roles.is_empty() {
        return "0".to_string();
    }

    let preview = roles
        .iter()
        .take(ROLE_PREVIEW_LIMIT)
        .map(String::as_str)
        .collect::<Vec<_>>()
        .join(", ");
    let suffix = if roles.len() > ROLE_PREVIEW_LIMIT {
        ", ..."
    } else {
        ""
    };

    format!("{} ({preview}{suffix})", roles.len())
}

// Render a workspace-relative path where possible for concise output.
fn display_workspace_path(workspace_root: &Path, path: &Path) -> String {
    path.strip_prefix(workspace_root)
        .unwrap_or(path)
        .display()
        .to_string()
}

// Return fleet command-family usage text.
fn usage() -> String {
    let mut command = fleet_command();
    command.render_help().to_string()
}

// Return fleet list usage text.
fn list_usage() -> String {
    let mut command = fleet_list_command();
    command.render_help().to_string()
}

// Return create fleet usage text.
fn create_usage() -> String {
    scaffold::fleet_create_usage()
}

// Return fleet delete usage text.
fn delete_usage() -> String {
    let mut command = fleet_delete_command();
    command.render_help().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::temp_dir;
    use std::fs;

    // Ensure fleet listing options accept network selection.
    #[test]
    fn parses_fleet_options() {
        let options = FleetOptions::parse([OsString::from("--network"), OsString::from("ic")])
            .expect("parse fleet options");

        assert_eq!(options.network, "ic");
    }

    // Ensure fleet delete options require exactly one fleet name.
    #[test]
    fn parses_delete_fleet_options() {
        let options =
            DeleteFleetOptions::parse([OsString::from("demo")]).expect("parse delete options");

        assert_eq!(options.fleet, "demo");
    }

    // Ensure fleet deletion requires the exact fleet name as confirmation.
    #[test]
    fn confirm_delete_fleet_requires_exact_name() {
        let target = Path::new("/tmp/canic/fleets/demo");
        let mut output = Vec::new();

        confirm_delete_fleet("demo", target, io::Cursor::new(b"demo\n"), &mut output)
            .expect("confirm delete");

        let output = String::from_utf8(output).expect("utf8 prompt");
        assert!(output.contains("Delete Canic fleet?"));
        assert!(output.contains("fleet: demo"));
        assert!(output.contains("Type the fleet name to confirm"));

        let err = confirm_delete_fleet("demo", target, io::Cursor::new(b"yes\n"), Vec::new())
            .expect_err("wrong confirmation should cancel");
        assert!(matches!(err, FleetCommandError::DeleteCancelled));
    }

    // Ensure delete resolves the fleet config parent, not an arbitrary path.
    #[test]
    fn delete_target_resolves_config_parent() {
        let root = temp_dir("canic-fleet-delete-target");
        let demo = write_fleet_config(&root, "demo");
        let staging = write_fleet_config(&root, "staging");
        let choices = vec![demo.join("canic.toml"), staging.join("canic.toml")];

        let target =
            delete_target_dir_from_choices(&root, &choices, "staging").expect("delete target");

        fs::remove_dir_all(&root).expect("remove temp root");
        assert_eq!(target, staging);
    }

    // Ensure fleet listing renders deterministic config-defined rows.
    #[test]
    fn renders_fleet_list_table() {
        let table = render_fleet_list_from_rows(vec![
            FleetListRow {
                fleet: "demo".to_string(),
                network: "local".to_string(),
                config: "fleets/demo/canic.toml".to_string(),
                canisters: "3 (root, app, user_hub)".to_string(),
            },
            FleetListRow {
                fleet: "staging".to_string(),
                network: "local".to_string(),
                config: "fleets/staging/canic.toml".to_string(),
                canisters: "2 (root, app)".to_string(),
            },
        ]);

        assert_eq!(
            table,
            format!(
                "{:<7}  {:<7}  {:<25}  {}\n{:<7}  {:<7}  {:<25}  {}\n{:<7}  {:<7}  {:<25}  {}",
                "FLEET",
                "NETWORK",
                "CONFIG",
                "CANISTERS",
                "demo",
                "local",
                "fleets/demo/canic.toml",
                "3 (root, app, user_hub)",
                "staging",
                "local",
                "fleets/staging/canic.toml",
                "2 (root, app)",
            )
        );
    }

    // Ensure fleet command help lists the command family without search.
    #[test]
    fn fleet_usage_lists_subcommands_and_examples() {
        let text = usage();

        assert!(text.contains("Manage Canic fleets"));
        assert!(text.contains("Usage: canic fleet"));
        assert!(text.contains("create"));
        assert!(text.contains("delete"));
        assert!(text.contains("list"));
        assert!(!text.contains("current"));
        assert!(!text.contains("use"));
        assert!(!text.contains("search"));
        assert!(text.contains("Examples:"));
    }

    // Ensure fleet create help explains creation.
    #[test]
    fn fleet_create_usage_lists_options_and_examples() {
        let text = create_usage();

        assert!(text.contains("Create a minimal Canic fleet"));
        assert!(text.contains("Usage: canic fleet create"));
        assert!(!text.contains("--network <name>"));
        assert!(text.contains("--yes"));
        assert!(text.contains("Examples:"));
    }

    // Ensure fleet list help explains network selection.
    #[test]
    fn fleet_list_usage_lists_options_and_examples() {
        let text = list_usage();

        assert!(text.contains("List config-defined Canic fleets"));
        assert!(text.contains("Usage: canic fleet list"));
        assert!(text.contains("--network <name>"));
        assert!(text.contains("Examples:"));
    }

    // Ensure fleet delete help explains the destructive confirmation.
    #[test]
    fn delete_usage_lists_confirmation() {
        let text = delete_usage();

        assert!(text.contains("Delete a config-defined Canic fleet directory"));
        assert!(text.contains("Usage: canic fleet delete"));
        assert!(text.contains("[name]"));
        assert!(text.contains("type the"));
    }

    // Render precomputed config rows for focused table tests.
    fn render_fleet_list_from_rows(rows: Vec<FleetListRow>) -> String {
        let mut table = WhitespaceTable::new([
            FLEET_HEADER,
            NETWORK_HEADER,
            CONFIG_HEADER,
            CANISTERS_HEADER,
        ]);
        for row in rows {
            table.push_row([row.fleet, row.network, row.config, row.canisters]);
        }
        table.render()
    }

    fn write_fleet_config(root: &Path, name: &str) -> PathBuf {
        let dir = root.join("fleets").join(name);
        fs::create_dir_all(dir.join("root")).expect("create root dir");
        fs::write(dir.join("root/Cargo.toml"), "").expect("write root manifest");
        fs::write(
            dir.join("canic.toml"),
            format!(
                r#"
[fleet]
name = "{name}"

[subnets.prime.canisters.root]
kind = "root"
"#
            ),
        )
        .expect("write canic config");
        dir
    }
}