mod args;
mod backup;
mod build;
mod fleets;
mod install;
mod list;
mod manifest;
mod medic;
mod network;
mod output;
mod restore;
mod scaffold;
mod snapshot;
mod status;
#[cfg(test)]
mod test_support;
use crate::args::first_arg_is_version;
use clap::{Arg, ArgAction, Command};
use std::ffi::OsString;
use thiserror::Error as ThisError;
const VERSION_TEXT: &str = concat!("canic ", env!("CARGO_PKG_VERSION"));
const TOP_LEVEL_HELP_TEMPLATE: &str = "{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{before-help}Options:\n{options}{after-help}\n";
const COLOR_RESET: &str = "\x1b[0m";
const COLOR_HEADING: &str = "\x1b[1m";
const COLOR_GROUP: &str = "\x1b[38;5;245m";
const COLOR_COMMAND: &str = "\x1b[38;5;109m";
const COLOR_TIP: &str = "\x1b[38;5;245m";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CommandScope {
Defaults,
FleetContext,
WorkspaceFiles,
}
impl CommandScope {
const fn heading(self) -> &'static str {
match self {
Self::Defaults => "Default context commands",
Self::FleetContext => "Current network + fleet commands",
Self::WorkspaceFiles => "Workspace and file commands",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct CommandSpec {
name: &'static str,
about: &'static str,
scope: CommandScope,
}
const COMMAND_SPECS: &[CommandSpec] = &[
CommandSpec {
name: "status",
about: "Show current Canic defaults",
scope: CommandScope::Defaults,
},
CommandSpec {
name: "network",
about: "Show or select the current default network",
scope: CommandScope::Defaults,
},
CommandSpec {
name: "fleet",
about: "Show, list, select, or delete Canic fleets",
scope: CommandScope::Defaults,
},
CommandSpec {
name: "scaffold",
about: "Create a minimal Canic fleet scaffold",
scope: CommandScope::Defaults,
},
CommandSpec {
name: "install",
about: "Install and bootstrap a Canic fleet",
scope: CommandScope::FleetContext,
},
CommandSpec {
name: "list",
about: "Show registry canisters as a tree table",
scope: CommandScope::FleetContext,
},
CommandSpec {
name: "medic",
about: "Diagnose local Canic fleet setup",
scope: CommandScope::FleetContext,
},
CommandSpec {
name: "snapshot",
about: "Capture and download canister snapshots",
scope: CommandScope::FleetContext,
},
CommandSpec {
name: "build",
about: "Build one Canic canister artifact",
scope: CommandScope::WorkspaceFiles,
},
CommandSpec {
name: "backup",
about: "Verify backup directories and journal status",
scope: CommandScope::WorkspaceFiles,
},
CommandSpec {
name: "manifest",
about: "Validate fleet backup manifests",
scope: CommandScope::WorkspaceFiles,
},
CommandSpec {
name: "restore",
about: "Plan or run snapshot restores",
scope: CommandScope::WorkspaceFiles,
},
];
#[derive(Debug, ThisError)]
pub enum CliError {
#[error("{0}")]
Usage(String),
#[error("backup: {0}")]
Backup(String),
#[error("build: {0}")]
Build(String),
#[error("install: {0}")]
Install(String),
#[error("fleet: {0}")]
Fleets(String),
#[error("list: {0}")]
List(String),
#[error("manifest: {0}")]
Manifest(String),
#[error("medic: {0}")]
Medic(String),
#[error("network: {0}")]
Network(String),
#[error("snapshot: {0}")]
Snapshot(String),
#[error("status: {0}")]
Status(String),
#[error("restore: {0}")]
Restore(String),
#[error("scaffold: {0}")]
Scaffold(String),
}
impl From<backup::BackupCommandError> for CliError {
fn from(err: backup::BackupCommandError) -> Self {
Self::Backup(err.to_string())
}
}
impl From<build::BuildCommandError> for CliError {
fn from(err: build::BuildCommandError) -> Self {
Self::Build(err.to_string())
}
}
impl From<install::InstallCommandError> for CliError {
fn from(err: install::InstallCommandError) -> Self {
Self::Install(err.to_string())
}
}
impl From<fleets::FleetCommandError> for CliError {
fn from(err: fleets::FleetCommandError) -> Self {
Self::Fleets(err.to_string())
}
}
impl From<list::ListCommandError> for CliError {
fn from(err: list::ListCommandError) -> Self {
Self::List(err.to_string())
}
}
impl From<manifest::ManifestCommandError> for CliError {
fn from(err: manifest::ManifestCommandError) -> Self {
Self::Manifest(err.to_string())
}
}
impl From<medic::MedicCommandError> for CliError {
fn from(err: medic::MedicCommandError) -> Self {
Self::Medic(err.to_string())
}
}
impl From<network::NetworkCommandError> for CliError {
fn from(err: network::NetworkCommandError) -> Self {
Self::Network(err.to_string())
}
}
impl From<snapshot::SnapshotCommandError> for CliError {
fn from(err: snapshot::SnapshotCommandError) -> Self {
Self::Snapshot(err.to_string())
}
}
impl From<status::StatusCommandError> for CliError {
fn from(err: status::StatusCommandError) -> Self {
Self::Status(err.to_string())
}
}
impl From<restore::RestoreCommandError> for CliError {
fn from(err: restore::RestoreCommandError) -> Self {
Self::Restore(err.to_string())
}
}
impl From<scaffold::ScaffoldCommandError> for CliError {
fn from(err: scaffold::ScaffoldCommandError) -> Self {
Self::Scaffold(err.to_string())
}
}
pub fn run_from_env() -> Result<(), CliError> {
run(std::env::args_os().skip(1))
}
pub fn run<I>(args: I) -> Result<(), CliError>
where
I: IntoIterator<Item = OsString>,
{
let args = args.into_iter().collect::<Vec<_>>();
if first_arg_is_version(&args) {
println!("{}", version_text());
return Ok(());
}
let mut args = args.into_iter();
let Some(command) = args.next().and_then(|arg| arg.into_string().ok()) else {
return Err(CliError::Usage(usage()));
};
match command.as_str() {
"backup" => backup::run(args).map_err(CliError::from),
"build" => build::run(args).map_err(CliError::from),
"fleet" => fleets::run(args).map_err(CliError::from),
"install" => install::run(args).map_err(CliError::from),
"list" => list::run(args).map_err(CliError::from),
"manifest" => manifest::run(args).map_err(CliError::from),
"medic" => medic::run(args).map_err(CliError::from),
"network" => network::run(args).map_err(CliError::from),
"scaffold" => scaffold::run(args).map_err(CliError::from),
"snapshot" => snapshot::run(args).map_err(CliError::from),
"status" => status::run(args).map_err(CliError::from),
"restore" => restore::run(args).map_err(CliError::from),
"help" | "--help" | "-h" => {
println!("{}", usage());
Ok(())
}
_ => Err(CliError::Usage(usage())),
}
}
#[must_use]
pub fn top_level_command() -> Command {
let command = Command::new("canic")
.version(env!("CARGO_PKG_VERSION"))
.about("Operator CLI for Canic install, backup, and restore workflows")
.disable_version_flag(true)
.arg(
Arg::new("version")
.short('V')
.long("version")
.action(ArgAction::SetTrue)
.help("Print version"),
)
.subcommand_help_heading("Commands")
.help_template(TOP_LEVEL_HELP_TEMPLATE)
.before_help(grouped_command_section(COMMAND_SPECS).join("\n"))
.after_help("Run `canic <command> help` for command-specific help.");
COMMAND_SPECS.iter().fold(command, |command, spec| {
command.subcommand(Command::new(spec.name).about(spec.about))
})
}
#[must_use]
pub const fn version_text() -> &'static str {
VERSION_TEXT
}
fn usage() -> String {
let mut lines = vec![
color(
COLOR_HEADING,
&format!("Canic Operator CLI v{}", env!("CARGO_PKG_VERSION")),
),
String::new(),
"Usage: canic [OPTIONS] <COMMAND>".to_string(),
String::new(),
color(COLOR_HEADING, "Commands:"),
];
lines.extend(grouped_command_section(COMMAND_SPECS));
lines.extend([
String::new(),
color(COLOR_HEADING, "Options:"),
" -V, --version Print version".to_string(),
" -h, --help Print help".to_string(),
String::new(),
format!(
"{}Tip:{} Run {} for command-specific help.",
COLOR_TIP,
COLOR_RESET,
color(COLOR_COMMAND, "`canic <command> help`")
),
]);
lines.join("\n")
}
fn grouped_command_section(specs: &[CommandSpec]) -> Vec<String> {
let mut lines = Vec::new();
let scopes = [
CommandScope::Defaults,
CommandScope::FleetContext,
CommandScope::WorkspaceFiles,
];
for (index, scope) in scopes.into_iter().enumerate() {
lines.push(format!(" {}", color(COLOR_GROUP, scope.heading())));
for spec in specs.iter().filter(|spec| spec.scope == scope) {
let command = format!("{:<12}", spec.name);
lines.push(format!(
" {} {}",
color(COLOR_COMMAND, &command),
spec.about
));
}
if index + 1 < scopes.len() {
lines.push(String::new());
}
}
lines
}
fn color(code: &str, text: &str) -> String {
format!("{code}{text}{COLOR_RESET}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn usage_lists_command_families() {
let text = usage();
let plain = strip_ansi(&text);
assert!(plain.contains(&format!(
"Canic Operator CLI v{}",
env!("CARGO_PKG_VERSION")
)));
assert!(plain.contains("Usage: canic [OPTIONS] <COMMAND>"));
assert!(plain.contains("\nCommands:\n"));
assert!(plain.contains("Default context commands"));
assert!(plain.contains("Current network + fleet commands"));
assert!(plain.contains("Workspace and file commands"));
assert!(
plain.find("Default context commands") < plain.find("Current network + fleet commands")
);
assert!(
plain.find("Current network + fleet commands")
< plain.find("Workspace and file commands")
);
assert!(plain.find(" status") < plain.find(" network"));
assert!(plain.find(" network") < plain.find(" fleet"));
assert!(plain.find(" fleet") < plain.find(" scaffold"));
assert!(plain.find(" scaffold") < plain.find(" install"));
assert!(plain.contains("Options:"));
assert!(plain.contains("scaffold"));
assert!(plain.contains("list"));
assert!(plain.contains("build"));
assert!(plain.contains("network"));
assert!(plain.contains("status"));
assert!(plain.contains("fleet"));
assert!(plain.contains("install"));
assert!(plain.contains("snapshot"));
assert!(plain.contains("backup"));
assert!(plain.contains("manifest"));
assert!(plain.contains("medic"));
assert!(plain.contains("restore"));
assert!(plain.contains("Tip: Run `canic <command> help`"));
assert!(text.contains(COLOR_HEADING));
assert!(text.contains(COLOR_GROUP));
assert!(text.contains(COLOR_COMMAND));
}
#[test]
fn command_family_help_returns_ok() {
assert!(run([OsString::from("backup"), OsString::from("help")]).is_ok());
assert!(
run([
OsString::from("backup"),
OsString::from("list"),
OsString::from("help")
])
.is_ok()
);
assert!(
run([
OsString::from("backup"),
OsString::from("status"),
OsString::from("help")
])
.is_ok()
);
assert!(
run([
OsString::from("backup"),
OsString::from("verify"),
OsString::from("help")
])
.is_ok()
);
assert!(run([OsString::from("build"), OsString::from("help")]).is_ok());
assert!(run([OsString::from("install"), OsString::from("help")]).is_ok());
assert!(run([OsString::from("fleet"), OsString::from("help")]).is_ok());
assert!(
run([
OsString::from("fleet"),
OsString::from("list"),
OsString::from("help")
])
.is_ok()
);
assert!(
run([
OsString::from("fleet"),
OsString::from("use"),
OsString::from("help")
])
.is_ok()
);
assert!(
run([
OsString::from("fleet"),
OsString::from("delete"),
OsString::from("help")
])
.is_ok()
);
assert!(run([OsString::from("list"), OsString::from("help")]).is_ok());
assert!(run([OsString::from("restore"), OsString::from("help")]).is_ok());
assert!(
run([
OsString::from("restore"),
OsString::from("plan"),
OsString::from("help")
])
.is_ok()
);
assert!(
run([
OsString::from("restore"),
OsString::from("apply"),
OsString::from("help")
])
.is_ok()
);
assert!(
run([
OsString::from("restore"),
OsString::from("run"),
OsString::from("help")
])
.is_ok()
);
assert!(run([OsString::from("manifest"), OsString::from("help")]).is_ok());
assert!(
run([
OsString::from("manifest"),
OsString::from("validate"),
OsString::from("help")
])
.is_ok()
);
assert!(run([OsString::from("medic"), OsString::from("help")]).is_ok());
assert!(run([OsString::from("network"), OsString::from("help")]).is_ok());
assert!(run([OsString::from("scaffold"), OsString::from("help")]).is_ok());
assert!(run([OsString::from("snapshot"), OsString::from("help")]).is_ok());
assert!(
run([
OsString::from("snapshot"),
OsString::from("download"),
OsString::from("help")
])
.is_ok()
);
assert!(run([OsString::from("status"), OsString::from("help")]).is_ok());
}
#[test]
fn version_flags_return_ok() {
assert_eq!(version_text(), concat!("canic ", env!("CARGO_PKG_VERSION")));
assert!(run([OsString::from("--version")]).is_ok());
assert!(
run([
OsString::from("backup"),
OsString::from("list"),
OsString::from("--dir"),
OsString::from("version")
])
.is_ok()
);
assert!(run([OsString::from("backup"), OsString::from("--version")]).is_ok());
assert!(
run([
OsString::from("backup"),
OsString::from("list"),
OsString::from("--version")
])
.is_ok()
);
assert!(run([OsString::from("build"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("install"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("fleet"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("list"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("restore"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("manifest"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("medic"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("network"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("scaffold"), OsString::from("--version")]).is_ok());
assert!(run([OsString::from("snapshot"), OsString::from("--version")]).is_ok());
assert!(
run([
OsString::from("snapshot"),
OsString::from("download"),
OsString::from("--version")
])
.is_ok()
);
assert!(run([OsString::from("status"), OsString::from("--version")]).is_ok());
}
fn strip_ansi(text: &str) -> String {
let mut plain = String::new();
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\x1b' && chars.peek() == Some(&'[') {
chars.next();
for ch in chars.by_ref() {
if ch == 'm' {
break;
}
}
continue;
}
plain.push(ch);
}
plain
}
}