Organize the public CLI with clap
This commit is contained in:
parent
e7dd95aea6
commit
d08d931b5f
4 changed files with 445 additions and 255 deletions
182
crates/lazaret-client/src/cli.rs
Normal file
182
crates/lazaret-client/src/cli.rs
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use lazaret_host_coordinator::domain_store::StateResetScopeV1;
|
||||
|
||||
use crate::ClientCommand;
|
||||
use crate::state::{StateCommand, StateOperation};
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
name = "lazaret",
|
||||
version,
|
||||
about = "Run development tools in an isolated agent sandbox",
|
||||
long_about = "Run development tools in an isolated gVisor sandbox while keeping workspace editing, persistent tool state, controlled network access, and developer-approved host actions available."
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: PublicCommand,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum PublicCommand {
|
||||
/// Run a command in the sandbox for a profile and workspace.
|
||||
Run(RunArguments),
|
||||
/// Inspect, verify, or reset persistent sandbox state.
|
||||
State {
|
||||
#[command(subcommand)]
|
||||
operation: StateArguments,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct RunArguments {
|
||||
#[command(flatten)]
|
||||
domain: DomainArguments,
|
||||
/// Command and arguments to run inside the sandbox.
|
||||
#[arg(last = true, required = true, num_args = 1.., value_name = "COMMAND")]
|
||||
command: Vec<OsString>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct DomainArguments {
|
||||
/// Agent profile to use from the Lazaret configuration.
|
||||
#[arg(long, value_name = "NAME")]
|
||||
profile: String,
|
||||
/// Project directory to share with the sandbox.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
workspace: Option<PathBuf>,
|
||||
/// Lazaret configuration file to load instead of the user default.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
config: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum StateArguments {
|
||||
/// List configured persistent sandbox paths without reading file contents.
|
||||
List(StateReadArguments),
|
||||
/// Show structural changes in persistent sandbox paths without file contents.
|
||||
Inspect(StateReadArguments),
|
||||
/// Verify persistent sandbox state while the domain is inactive.
|
||||
Verify(StateReadArguments),
|
||||
/// Discard persistent sandbox state for selected configured paths.
|
||||
Reset(StateResetArguments),
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct StateReadArguments {
|
||||
#[command(flatten)]
|
||||
domain: DomainArguments,
|
||||
/// Write a stable machine-readable JSON report.
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
struct StateResetArguments {
|
||||
#[command(flatten)]
|
||||
domain: DomainArguments,
|
||||
/// Write a stable machine-readable JSON report.
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
/// Reset without asking for interactive confirmation.
|
||||
#[arg(long)]
|
||||
yes: bool,
|
||||
#[command(flatten)]
|
||||
scope: ResetScope,
|
||||
}
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
#[group(id = "scope", required = true, multiple = false)]
|
||||
struct ResetScope {
|
||||
/// Reset every configured persistent sandbox path in the domain.
|
||||
#[arg(long)]
|
||||
all: bool,
|
||||
/// Reset one exact configured container path, such as `/usr/local`.
|
||||
#[arg(long, value_name = "CONTAINER_PATH")]
|
||||
path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Command {
|
||||
Run(ClientCommand),
|
||||
State(StateCommand),
|
||||
}
|
||||
|
||||
/// Parses the public command tree while preserving non-UTF-8 host paths and command arguments.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns clap's structured usage or help result.
|
||||
pub fn parse(
|
||||
arguments: impl IntoIterator<Item = OsString>,
|
||||
current_workspace: PathBuf,
|
||||
) -> Result<Command, clap::Error> {
|
||||
let cli = Cli::try_parse_from(std::iter::once(OsString::from("lazaret")).chain(arguments))?;
|
||||
Ok(match cli.command {
|
||||
PublicCommand::Run(arguments) => Command::Run(ClientCommand {
|
||||
profile: arguments.domain.profile,
|
||||
workspace: arguments.domain.workspace.unwrap_or(current_workspace),
|
||||
configuration: arguments.domain.config,
|
||||
argv: arguments
|
||||
.command
|
||||
.into_iter()
|
||||
.map(std::os::unix::ffi::OsStringExt::into_vec)
|
||||
.collect(),
|
||||
}),
|
||||
PublicCommand::State { operation } => {
|
||||
Command::State(state_command(operation, current_workspace))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn state_command(operation: StateArguments, current_workspace: PathBuf) -> StateCommand {
|
||||
let (operation, domain, machine, yes, scope) = match operation {
|
||||
StateArguments::List(arguments) => (
|
||||
StateOperation::List,
|
||||
arguments.domain,
|
||||
arguments.json,
|
||||
false,
|
||||
None,
|
||||
),
|
||||
StateArguments::Inspect(arguments) => (
|
||||
StateOperation::Inspect,
|
||||
arguments.domain,
|
||||
arguments.json,
|
||||
false,
|
||||
None,
|
||||
),
|
||||
StateArguments::Verify(arguments) => (
|
||||
StateOperation::Verify,
|
||||
arguments.domain,
|
||||
arguments.json,
|
||||
false,
|
||||
None,
|
||||
),
|
||||
StateArguments::Reset(arguments) => {
|
||||
let scope = match arguments.scope.path {
|
||||
Some(path) => StateResetScopeV1::Selected(path.into_bytes()),
|
||||
None => StateResetScopeV1::All,
|
||||
};
|
||||
(
|
||||
StateOperation::Reset,
|
||||
arguments.domain,
|
||||
arguments.json,
|
||||
arguments.yes,
|
||||
Some(scope),
|
||||
)
|
||||
}
|
||||
};
|
||||
StateCommand {
|
||||
operation,
|
||||
context: ClientCommand {
|
||||
profile: domain.profile,
|
||||
workspace: domain.workspace.unwrap_or(current_workspace),
|
||||
configuration: domain.config,
|
||||
argv: Vec::new(),
|
||||
},
|
||||
machine,
|
||||
yes,
|
||||
scope,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,6 @@
|
|||
use std::ffi::OsString;
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Write};
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
|
|
@ -22,6 +20,7 @@ use sha2::{Digest, Sha256};
|
|||
|
||||
use crate::terminal::{HostTerminal, InteractiveSessionTransport, run_interactive_session};
|
||||
|
||||
pub mod cli;
|
||||
pub mod coordinator_backend;
|
||||
pub mod state;
|
||||
pub mod terminal;
|
||||
|
|
@ -34,82 +33,6 @@ pub struct ClientCommand {
|
|||
pub argv: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ArgumentError(&'static str);
|
||||
|
||||
impl fmt::Display for ArgumentError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ArgumentError {}
|
||||
|
||||
/// Parses `--profile`, optional host paths, and the exact command following `--`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns a concise usage error for missing values, unknown options, or a missing command.
|
||||
pub fn parse_command_line(
|
||||
arguments: impl IntoIterator<Item = OsString>,
|
||||
current_workspace: PathBuf,
|
||||
) -> Result<ClientCommand, ArgumentError> {
|
||||
let mut arguments = arguments.into_iter();
|
||||
let mut profile = None;
|
||||
let mut workspace = None;
|
||||
let mut configuration = None;
|
||||
let mut argv = Vec::new();
|
||||
while let Some(argument) = arguments.next() {
|
||||
match argument.to_str() {
|
||||
Some("--profile") => profile = Some(required_utf8(&mut arguments, "--profile")?),
|
||||
Some("--workspace") => {
|
||||
workspace = Some(PathBuf::from(required_value(
|
||||
&mut arguments,
|
||||
"--workspace",
|
||||
)?));
|
||||
}
|
||||
Some("--config") => {
|
||||
configuration = Some(PathBuf::from(required_value(&mut arguments, "--config")?));
|
||||
}
|
||||
Some("--") => {
|
||||
argv.extend(arguments.map(OsString::into_vec));
|
||||
break;
|
||||
}
|
||||
Some(_) | None => return Err(ArgumentError("unknown option before `--`")),
|
||||
}
|
||||
}
|
||||
let profile = profile.ok_or(ArgumentError("`--profile <name>` is required"))?;
|
||||
if argv.is_empty() {
|
||||
return Err(ArgumentError("a command is required after `--`"));
|
||||
}
|
||||
Ok(ClientCommand {
|
||||
profile,
|
||||
workspace: workspace.unwrap_or(current_workspace),
|
||||
configuration,
|
||||
argv,
|
||||
})
|
||||
}
|
||||
|
||||
fn required_value(
|
||||
arguments: &mut impl Iterator<Item = OsString>,
|
||||
option: &'static str,
|
||||
) -> Result<OsString, ArgumentError> {
|
||||
arguments.next().ok_or(match option {
|
||||
"--profile" => ArgumentError("`--profile` requires a value"),
|
||||
"--workspace" => ArgumentError("`--workspace` requires a path"),
|
||||
"--config" => ArgumentError("`--config` requires a path"),
|
||||
_ => ArgumentError("option requires a value"),
|
||||
})
|
||||
}
|
||||
|
||||
fn required_utf8(
|
||||
arguments: &mut impl Iterator<Item = OsString>,
|
||||
option: &'static str,
|
||||
) -> Result<String, ArgumentError> {
|
||||
required_value(arguments, option)?
|
||||
.into_string()
|
||||
.map_err(|_| ArgumentError("profile name must be UTF-8"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum DomainStatus<E> {
|
||||
Absent,
|
||||
|
|
|
|||
|
|
@ -7,29 +7,27 @@ fn main() {
|
|||
}
|
||||
return;
|
||||
}
|
||||
if arguments.first().and_then(|value| value.to_str()) == Some("state") {
|
||||
match lazaret_client::state::run_command(&arguments[1..]) {
|
||||
Ok(status) => std::process::exit(status),
|
||||
Err(error) => {
|
||||
eprintln!("Lazaret state maintenance failed: {error}");
|
||||
std::process::exit(1);
|
||||
let current_workspace = std::env::current_dir().unwrap_or_else(|error| {
|
||||
eprintln!("cannot determine current workspace: {error}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let command = lazaret_client::cli::parse(arguments, current_workspace)
|
||||
.unwrap_or_else(|error| error.exit());
|
||||
match command {
|
||||
lazaret_client::cli::Command::State(command) => {
|
||||
match lazaret_client::state::run_command(command) {
|
||||
Ok(status) => std::process::exit(status),
|
||||
Err(error) => {
|
||||
eprintln!("Lazaret state maintenance failed: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
lazaret_client::cli::Command::Run(command) => run(&command),
|
||||
}
|
||||
let current_workspace = match std::env::current_dir() {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("cannot determine current workspace: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let command = match lazaret_client::parse_command_line(arguments, current_workspace) {
|
||||
Ok(command) => command,
|
||||
Err(error) => {
|
||||
eprintln!("invalid command line: {error}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn run(command: &lazaret_client::ClientCommand) {
|
||||
let mut backend = match lazaret_client::coordinator_backend::CoordinatorClientBackend::new() {
|
||||
Ok(backend) => backend,
|
||||
Err(error) => {
|
||||
|
|
@ -39,7 +37,7 @@ fn main() {
|
|||
};
|
||||
match lazaret_client::run(
|
||||
&mut backend,
|
||||
&command,
|
||||
command,
|
||||
&mut std::io::stdout(),
|
||||
&mut std::io::stderr(),
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
use std::ffi::OsString;
|
||||
use std::io::{self, Write};
|
||||
use std::os::fd::AsFd;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lazaret_core::records::Domain;
|
||||
use lazaret_host_coordinator::domain_store::{HostCoordinatorDomainStore, StateResetScopeV1};
|
||||
|
|
@ -19,19 +17,20 @@ use crate::coordinator_backend::{load_configuration, open_private_domain_lock};
|
|||
const OUTPUT_SCHEMA: &str = "lazaret-state-output-v1";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum Operation {
|
||||
pub enum StateOperation {
|
||||
List,
|
||||
Inspect,
|
||||
Verify,
|
||||
Reset,
|
||||
}
|
||||
|
||||
struct StateCommand {
|
||||
operation: Operation,
|
||||
context: ClientCommand,
|
||||
machine: bool,
|
||||
yes: bool,
|
||||
scope: Option<StateResetScopeV1>,
|
||||
#[derive(Debug)]
|
||||
pub struct StateCommand {
|
||||
pub(crate) operation: StateOperation,
|
||||
pub(crate) context: ClientCommand,
|
||||
pub(crate) machine: bool,
|
||||
pub(crate) yes: bool,
|
||||
pub(crate) scope: Option<StateResetScopeV1>,
|
||||
}
|
||||
|
||||
/// Runs one state-maintenance command using resolved configuration and exclusive Domain authority.
|
||||
|
|
@ -39,8 +38,7 @@ struct StateCommand {
|
|||
/// # Errors
|
||||
/// Refuses invalid arguments, active Domains, arbitrary targets, authority changes, malformed
|
||||
/// durable state, structural failures, and reset without confirmation.
|
||||
pub fn run_command(arguments: &[OsString]) -> Result<i32, Box<dyn std::error::Error>> {
|
||||
let command = parse(arguments)?;
|
||||
pub fn run_command(command: StateCommand) -> Result<i32, Box<dyn std::error::Error>> {
|
||||
let configuration = load_configuration(&command.context)?;
|
||||
if let Some(StateResetScopeV1::Selected(path)) = &command.scope
|
||||
&& !configuration
|
||||
|
|
@ -78,10 +76,10 @@ pub fn run_command(arguments: &[OsString]) -> Result<i32, Box<dyn std::error::Er
|
|||
};
|
||||
let store = HostCoordinatorDomainStore::open_file(lock, database.into(), &expected)?;
|
||||
let report = match command.operation {
|
||||
Operation::List | Operation::Inspect | Operation::Verify => {
|
||||
StateOperation::List | StateOperation::Inspect | StateOperation::Verify => {
|
||||
inspect_domain_state(&configuration, &store)?
|
||||
}
|
||||
Operation::Reset => {
|
||||
StateOperation::Reset => {
|
||||
let scope = command.scope.ok_or("reset scope is missing")?;
|
||||
if !command.yes {
|
||||
confirm(&configuration, &scope)?;
|
||||
|
|
@ -93,97 +91,6 @@ pub fn run_command(arguments: &[OsString]) -> Result<i32, Box<dyn std::error::Er
|
|||
Ok(0)
|
||||
}
|
||||
|
||||
fn parse(arguments: &[OsString]) -> Result<StateCommand, &'static str> {
|
||||
let operation = match arguments.first().and_then(|value| value.to_str()) {
|
||||
Some("list") => Operation::List,
|
||||
Some("inspect") => Operation::Inspect,
|
||||
Some("verify") => Operation::Verify,
|
||||
Some("reset") => Operation::Reset,
|
||||
_ => return Err("expected `state list|inspect|verify|reset`"),
|
||||
};
|
||||
let mut profile = None;
|
||||
let mut workspace = None;
|
||||
let mut configuration = None;
|
||||
let mut machine = false;
|
||||
let mut yes = false;
|
||||
let mut scope = None;
|
||||
let mut index = 1;
|
||||
while index < arguments.len() {
|
||||
let option = arguments[index].to_str().ok_or("options must be UTF-8")?;
|
||||
index += 1;
|
||||
match option {
|
||||
"--profile" => profile = Some(value(arguments, &mut index, "--profile")?),
|
||||
"--workspace" => workspace = Some(PathBuf::from(value_os(arguments, &mut index)?)),
|
||||
"--config" => configuration = Some(PathBuf::from(value_os(arguments, &mut index)?)),
|
||||
"--json" => machine = true,
|
||||
"--yes" => yes = true,
|
||||
"--all" => set_scope(&mut scope, StateResetScopeV1::All)?,
|
||||
"--path" => {
|
||||
let path = value(arguments, &mut index, "--path")?;
|
||||
set_scope(&mut scope, StateResetScopeV1::Selected(path.into_bytes()))?;
|
||||
}
|
||||
_ => return Err("unknown state-maintenance option"),
|
||||
}
|
||||
}
|
||||
let profile = profile.ok_or("`--profile <name>` is required")?;
|
||||
let workspace = match workspace {
|
||||
Some(workspace) => workspace,
|
||||
None => std::env::current_dir().map_err(|_| "cannot determine current workspace")?,
|
||||
};
|
||||
if operation == Operation::Reset && scope.is_none() {
|
||||
return Err("reset requires exactly one of `--all` or `--path <container-path>`");
|
||||
}
|
||||
if operation != Operation::Reset && (scope.is_some() || yes) {
|
||||
return Err("reset scope and confirmation options require `state reset`");
|
||||
}
|
||||
Ok(StateCommand {
|
||||
operation,
|
||||
context: ClientCommand {
|
||||
profile,
|
||||
workspace,
|
||||
configuration,
|
||||
argv: Vec::new(),
|
||||
},
|
||||
machine,
|
||||
yes,
|
||||
scope,
|
||||
})
|
||||
}
|
||||
|
||||
fn value(
|
||||
arguments: &[OsString],
|
||||
index: &mut usize,
|
||||
option: &'static str,
|
||||
) -> Result<String, &'static str> {
|
||||
value_os(arguments, index)?
|
||||
.into_string()
|
||||
.map_err(|_| match option {
|
||||
"--profile" => "profile name must be UTF-8",
|
||||
"--path" => "container path must be UTF-8",
|
||||
_ => "option value must be UTF-8",
|
||||
})
|
||||
}
|
||||
|
||||
fn value_os(arguments: &[OsString], index: &mut usize) -> Result<OsString, &'static str> {
|
||||
let value = arguments
|
||||
.get(*index)
|
||||
.ok_or("option requires a value")?
|
||||
.clone();
|
||||
*index += 1;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn set_scope(
|
||||
current: &mut Option<StateResetScopeV1>,
|
||||
scope: StateResetScopeV1,
|
||||
) -> Result<(), &'static str> {
|
||||
if current.replace(scope).is_some() {
|
||||
Err("reset accepts exactly one scope")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(
|
||||
configuration: &lazaret_core::configuration::ResolvedDomainConfiguration,
|
||||
scope: &StateResetScopeV1,
|
||||
|
|
@ -211,7 +118,7 @@ fn confirm(
|
|||
}
|
||||
}
|
||||
|
||||
fn write_report(report: &DomainStateReport, operation: Operation, machine: bool) {
|
||||
fn write_report(report: &DomainStateReport, operation: StateOperation, machine: bool) {
|
||||
if machine {
|
||||
let anchors = report
|
||||
.anchors
|
||||
|
|
@ -252,7 +159,7 @@ fn write_report(report: &DomainStateReport, operation: Operation, machine: bool)
|
|||
anchor.container_path,
|
||||
anchor.changes.len()
|
||||
);
|
||||
if matches!(operation, Operation::Inspect | Operation::Verify) {
|
||||
if matches!(operation, StateOperation::Inspect | StateOperation::Verify) {
|
||||
for entry in &anchor.changes {
|
||||
println!(
|
||||
" {} {} mode {:o} uid {} gid {} size {}",
|
||||
|
|
@ -270,12 +177,12 @@ fn write_report(report: &DomainStateReport, operation: Operation, machine: bool)
|
|||
}
|
||||
}
|
||||
|
||||
const fn operation_name(operation: Operation) -> &'static str {
|
||||
const fn operation_name(operation: StateOperation) -> &'static str {
|
||||
match operation {
|
||||
Operation::List => "list",
|
||||
Operation::Inspect => "inspect",
|
||||
Operation::Verify => "verify",
|
||||
Operation::Reset => "reset",
|
||||
StateOperation::List => "list",
|
||||
StateOperation::Inspect => "inspect",
|
||||
StateOperation::Verify => "verify",
|
||||
StateOperation::Reset => "reset",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -295,43 +202,3 @@ fn hex(bytes: &[u8]) -> String {
|
|||
output
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parser_requires_explicit_reset_scope_and_rejects_arbitrary_options() {
|
||||
assert!(parse(&["reset", "--profile", "default"].map(OsString::from)).is_err());
|
||||
assert!(
|
||||
parse(
|
||||
&["reset", "--profile", "default", "--all", "--path", "/usr",].map(OsString::from)
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(parse(&["inspect", "--profile", "default", "--yes"].map(OsString::from)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_preserves_only_container_scope_not_a_host_upper_path() {
|
||||
let command = parse(
|
||||
&[
|
||||
"reset",
|
||||
"--profile",
|
||||
"default",
|
||||
"--path",
|
||||
"/usr",
|
||||
"--yes",
|
||||
"--json",
|
||||
]
|
||||
.map(OsString::from),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
command.scope,
|
||||
Some(StateResetScopeV1::Selected(b"/usr".to_vec()))
|
||||
);
|
||||
assert!(command.yes);
|
||||
assert!(command.machine);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue