use std::{ffi::OsString, net::IpAddr, path::PathBuf};
use clap::{Args, Parser, Subcommand, ValueEnum, value_parser};
use rmcp::schemars::{self, JsonSchema};
use serde::Deserialize;
use time::{OffsetDateTime, SignedDuration};
use troll_core::{Protocol, Role, Web, parse_duration};
use troll_probe::Kind;
use crate::commands::timestamp::parse_leased_at;
#[derive(Parser)]
#[command(
name = "troll",
version,
disable_version_flag = true,
disable_help_subcommand = true,
about
)]
pub struct Cli {
#[arg(short = 'V', long, exclusive = true)]
pub version: bool,
#[arg(long, global = true)]
pub json: bool,
#[arg(long = "color", global = true, value_enum)]
pub color: Option<Color>,
#[arg(
long = "no-ansi-colors",
visible_aliases = ["no-color", "no-colors"],
global = true
)]
pub no_color: bool,
#[arg(long)]
pub llm_guide: bool,
#[arg(long = "full", requires = "llm_guide")]
pub full: bool,
#[command(subcommand)]
pub command: Option<Command>,
}
#[derive(Args)]
pub struct WithCommand {
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "tcp")]
pub proto: ProtocolArg,
#[arg(long, value_name = "COMPONENTS", value_delimiter = ',')]
pub group: Option<Vec<String>>,
#[arg(long = "for", value_parser = parse_duration, value_name = "DURATION")]
pub duration: Option<SignedDuration>,
#[arg(long, value_name = "NAME")]
pub pool: Option<String>,
#[arg(long)]
pub heartbeat: bool,
#[arg(last = true, required = true, value_name = "COMMAND", num_args = 1..)]
pub arguments: Vec<OsString>,
}
#[derive(Subcommand)]
pub enum Command {
Init {
#[arg(long)]
yes: bool,
#[arg(long, requires = "yes")]
service: bool,
},
Setup {
#[command(subcommand)]
integration: Integration,
},
Doctor,
Claim(ClaimArgs),
Edit {
#[arg(value_parser = value_parser!(u16).range(1..))]
port: u16,
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "tcp")]
proto: ProtocolArg,
#[command(flatten)]
changes: EditArgs,
},
Lease {
#[command(flatten)]
args: LeaseArgs,
#[arg(long, value_name = "COMPONENTS", value_delimiter = ',')]
group: Option<Vec<String>>,
},
LeaseEdit {
#[arg(value_parser = value_parser!(u16).range(1..))]
port: u16,
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "tcp")]
proto: ProtocolArg,
#[arg(long)]
tag: Option<String>,
#[arg(long)]
purpose: Option<String>,
#[arg(long = "for",
alias = "expires-in",
value_parser = parse_duration,
value_name = "DURATION")]
duration: Option<SignedDuration>,
},
Renew {
#[command(flatten)]
target: LeaseTargetArgs,
#[arg(long = "for", value_parser = parse_duration, value_name = "DURATION")]
duration: Option<SignedDuration>,
},
Release {
#[command(flatten)]
target: ReleaseTargetArgs,
#[arg(long, conflicts_with = "group")]
force_shared: bool,
},
History {
#[command(subcommand)]
action: Option<HistoryCommand>,
},
Zone {
#[command(subcommand)]
action: ZoneCommand,
},
App {
#[command(subcommand)]
action: AppCommand,
},
Env {
app: String,
#[arg(long, value_name = "PATH")]
write: Option<PathBuf>,
},
Sync {
#[arg(short = 'f', long, default_value = "troll.toml", value_name = "PATH")]
file: PathBuf,
#[arg(long)]
dry_run: bool,
#[arg(long, value_name = "PATH")]
write_env: Option<PathBuf>,
},
With {
#[arg(long)]
project: Option<String>,
#[arg(long)]
purpose: Option<String>,
#[command(flatten)]
command: WithCommand,
},
Check {
#[arg(value_parser = value_parser!(u16).range(1..))]
port: u16,
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "tcp")]
proto: ProtocolArg,
},
Explain {
#[arg(value_parser = value_parser!(u16).range(1..))]
port: u16,
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "tcp")]
proto: ProtocolArg,
},
List {
#[arg(long, value_enum)]
kind: Option<KindArg>,
#[arg(long, value_enum)]
role: Option<RoleArg>,
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "all")]
proto: ProtoFilterArg,
#[arg(long)]
include_ephemeral_udp: bool,
#[arg(long)]
drift: bool,
},
Sweep {
#[arg(long)]
dry_run: bool,
},
ImportLegacy {
dir: PathBuf,
#[arg(long, conflicts_with = "apply")]
dry_run: bool,
#[arg(long)]
apply: bool,
},
Serve {
#[arg(long)]
port: Option<u16>,
#[arg(long, default_value = "127.0.0.1", value_name = "ADDRESS")]
bind: IpAddr,
},
#[command(after_help = "The MCP protocol is always JSON. --json has no effect.")]
Mcp,
}
#[derive(Args)]
pub struct ClaimArgs {
#[arg(value_parser = value_parser!(u16).range(1..))]
pub port: u16,
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "tcp")]
pub proto: ProtocolArg,
#[arg(long)]
pub project: String,
#[arg(long)]
pub service: String,
#[arg(long, value_name = "ADDRESS")]
pub bind: Option<IpAddr>,
#[arg(long, value_enum, default_value = "app")]
pub role: RoleArg,
#[arg(long)]
pub container: Option<String>,
#[arg(long, value_delimiter = ',')]
pub used_by: Option<Vec<String>>,
#[command(flatten)]
pub web: WebArgs,
#[arg(long)]
pub component: Option<String>,
}
#[derive(Args, Default)]
pub struct WebArgs {
#[arg(long, value_name = "PATH")]
pub web: Option<String>,
#[arg(long, value_enum)]
pub web_scheme: Option<WebScheme>,
}
impl WebArgs {
pub(crate) fn apply(self, current: Option<&Web>) -> Option<Web> {
if self.web.is_none() && self.web_scheme.is_none() {
return None;
}
let mut web = current.cloned().unwrap_or_default();
if let Some(path) = self.web {
web.path = path;
}
if let Some(scheme) = self.web_scheme {
web.scheme = match scheme {
WebScheme::Http => "http",
WebScheme::Https => "https",
}
.into();
}
Some(web)
}
}
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum WebScheme {
Http,
Https,
}
#[derive(Args)]
pub struct EditArgs {
#[arg(long)]
pub tag: Option<String>,
#[arg(long)]
pub service: Option<String>,
#[arg(long, value_enum)]
pub role: Option<RoleArg>,
#[arg(long, value_name = "ADDRESS")]
pub bind: Option<IpAddr>,
#[arg(long, value_delimiter = ',')]
pub used_by: Option<Vec<String>>,
#[arg(long, conflicts_with = "used_by")]
pub clear_used_by: bool,
#[arg(long)]
pub container: Option<String>,
#[arg(long, conflicts_with = "container")]
pub clear_container: bool,
#[command(flatten)]
pub web: WebArgs,
#[arg(long, conflicts_with_all = ["web", "web_scheme"])]
pub no_web: bool,
#[arg(id = "new_component", long = "component", value_name = "NAME")]
pub component: Option<String>,
#[arg(long, conflicts_with = "new_component")]
pub no_component: bool,
}
#[derive(Args)]
pub struct LeaseArgs {
#[arg(long = "proto", alias = "protocol", value_enum, default_value = "tcp")]
pub proto: ProtocolArg,
#[arg(long)]
pub project: String,
#[arg(long)]
pub purpose: String,
#[arg(long = "for", value_parser = parse_duration, value_name = "DURATION")]
pub duration: Option<SignedDuration>,
#[arg(long, value_parser = value_parser!(u32).range(1..))]
pub pid: Option<u32>,
#[arg(long, value_name = "ADDRESS")]
pub bind: Option<IpAddr>,
#[arg(long, value_name = "NAME")]
pub pool: Option<String>,
}
#[derive(Args)]
#[group(skip)]
pub struct LeaseTargetArgs {
#[arg(required_unless_present = "group", value_parser = value_parser!(u16).range(1..))]
pub port: Option<u16>,
#[arg(
long = "proto",
alias = "protocol",
value_enum,
conflicts_with = "group"
)]
pub proto: Option<ProtocolArg>,
#[arg(long, conflicts_with = "port", value_name = "ID")]
pub group: Option<String>,
#[arg(long, conflicts_with = "group", value_parser = parse_leased_at, value_name = "RFC 3339")]
pub leased_at: Option<OffsetDateTime>,
}
#[derive(Args)]
pub struct ReleaseTargetArgs {
#[command(flatten)]
pub lease: LeaseTargetArgs,
#[arg(long, conflicts_with_all = ["group", "leased_at"])]
pub if_tag: Option<String>,
}
#[derive(Subcommand)]
pub enum HistoryCommand {
List,
Show { id: String },
Restore { id: String },
}
#[derive(Subcommand)]
pub enum ZoneCommand {
Add {
label: String,
#[arg(long, required = true, value_delimiter = ',', value_name = "PORTS")]
ports: Vec<String>,
#[arg(long)]
reason: Option<String>,
#[arg(long = "proto", alias = "protocol", value_enum)]
proto: Option<ProtocolArg>,
#[arg(long)]
disabled: bool,
},
List,
Enable { label: String },
Disable { label: String },
Edit {
label: String,
#[arg(long, value_delimiter = ',', value_name = "PORTS")]
ports: Option<Vec<String>>,
#[arg(long)]
reason: Option<String>,
#[arg(long, conflicts_with = "reason")]
no_reason: bool,
#[arg(long = "proto", alias = "protocol", value_enum)]
proto: Option<ProtocolArg>,
#[arg(long, conflicts_with = "proto")]
any_proto: bool,
},
Remove {
label: String,
#[arg(long)]
if_tag: Option<String>,
},
}
#[derive(Subcommand)]
pub enum AppCommand {
Reserve(AppAllocationArgs),
List,
Show { app: String },
Add(AppAllocationArgs),
Remove {
app: String,
component: String,
#[arg(long)]
force_shared: bool,
#[arg(long)]
if_tag: Option<String>,
},
Edit {
app: String,
component: String,
#[command(flatten)]
changes: EditArgs,
},
Release {
app: String,
#[arg(long)]
confirm: String,
#[arg(long)]
if_tag: Option<String>,
},
}
#[derive(Args)]
pub struct AppAllocationArgs {
pub app: String,
#[arg(long, required = true, value_delimiter = ',')]
pub components: Vec<String>,
#[arg(long = "port", value_name = "COMPONENT=PORT")]
pub pins: Vec<String>,
#[arg(long, value_name = "ADDRESS")]
pub bind: Option<IpAddr>,
}
#[derive(Clone, Copy, ValueEnum)]
pub enum Color {
Auto,
Always,
Never,
}
#[derive(Subcommand)]
pub enum Integration {
Claude {
#[arg(long)]
force: bool,
},
Codex {
#[arg(long)]
force: bool,
},
Service {
#[arg(long)]
force: bool,
},
}
#[derive(Clone, Copy, Default, Deserialize, Eq, JsonSchema, PartialEq, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum ProtocolArg {
#[default]
Tcp,
Udp,
}
impl From<ProtocolArg> for Protocol {
fn from(proto: ProtocolArg) -> Self {
match proto {
ProtocolArg::Tcp => Self::Tcp,
ProtocolArg::Udp => Self::Udp,
}
}
}
impl From<Protocol> for ProtocolArg {
fn from(proto: Protocol) -> Self {
match proto {
Protocol::Tcp => Self::Tcp,
Protocol::Udp => Self::Udp,
}
}
}
#[derive(Clone, Copy, Default, Deserialize, Eq, JsonSchema, PartialEq, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum ProtoFilterArg {
#[default]
All,
Tcp,
Udp,
}
impl ProtoFilterArg {
pub fn into_option(self) -> Option<Protocol> {
match self {
Self::All => None,
Self::Tcp => Some(Protocol::Tcp),
Self::Udp => Some(Protocol::Udp),
}
}
}
#[derive(Clone, Copy, ValueEnum)]
pub enum RoleArg {
App,
Service,
}
impl From<RoleArg> for Role {
fn from(role: RoleArg) -> Self {
match role {
RoleArg::App => Self::App,
RoleArg::Service => Self::Service,
}
}
}
#[derive(Clone, Copy, ValueEnum)]
pub enum KindArg {
Ours,
System,
ThirdParty,
}
impl From<KindArg> for Kind {
fn from(kind: KindArg) -> Self {
match kind {
KindArg::Ours => Self::Ours,
KindArg::System => Self::System,
KindArg::ThirdParty => Self::ThirdParty,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
#[test]
fn console_command_tree_parses_edits_and_app_component_pins() {
Cli::command().debug_assert();
let cli = Cli::try_parse_from([
"troll",
"edit",
"8100",
"--tag",
"abc",
"--clear-used-by",
"--web",
"/admin",
"--web-scheme",
"https",
"--no-component",
])
.unwrap();
let Some(Command::Edit { port, changes, .. }) = cli.command else {
panic!("expected edit")
};
assert_eq!(port, 8100);
assert_eq!(changes.tag.as_deref(), Some("abc"));
assert!(changes.clear_used_by && changes.no_component);
assert_eq!(changes.web.web.as_deref(), Some("/admin"));
assert!(matches!(changes.web.web_scheme, Some(WebScheme::Https)));
let cli =
Cli::try_parse_from(["troll", "lease-edit", "20000", "--expires-in", "2h"]).unwrap();
assert!(
matches!(cli.command, Some(Command::LeaseEdit { duration: Some(duration), .. })
if duration == SignedDuration::hours(2))
);
let cli = Cli::try_parse_from([
"troll",
"app",
"reserve",
"demo",
"--components",
"api,db:service",
"--port",
"api=8100",
"--port",
"db=8101",
])
.unwrap();
let Some(Command::App {
action: AppCommand::Reserve(args),
}) = cli.command
else {
panic!("expected app reserve")
};
assert_eq!(args.components, ["api", "db:service"]);
assert_eq!(args.pins, ["api=8100", "db=8101"]);
}
#[test]
fn console_command_tree_rejects_conflicting_or_missing_arguments() {
for args in [
&["edit", "8100", "--used-by", "demo", "--clear-used-by"][..],
&["edit", "8100", "--no-web", "--web", "/"],
&["edit", "8100", "--no-web", "--web-scheme", "http"],
&[
"app",
"edit",
"demo",
"api",
"--component",
"ui",
"--no-component",
],
&["zone", "edit", "mine", "--reason", "new", "--no-reason"],
&["zone", "add", "mine"],
&["app", "release", "demo"],
&["release"],
&["renew", "8100", "--group", "g-123"],
&[
"renew",
"--group",
"g-123",
"--leased-at",
"2026-01-01T00:00:00Z",
],
&["release", "--group", "g-123", "--force-shared"],
&["lease-edit", "0"],
&["lease-edit", "8100", "--for", "0h"],
] {
let result = Cli::try_parse_from(std::iter::once("troll").chain(args.iter().copied()));
assert_eq!(
result.err().expect("usage error").exit_code(),
2,
"{args:?}"
);
}
}
#[test]
fn group_commands_parse_without_a_port() {
let cli = Cli::try_parse_from([
"troll",
"lease",
"--project",
"demo",
"--purpose",
"preview",
"--group",
"api,db",
])
.unwrap();
let Some(Command::Lease {
group: Some(components),
..
}) = cli.command
else {
panic!("expected grouped lease")
};
assert_eq!(components, ["api", "db"]);
let cli =
Cli::try_parse_from(["troll", "renew", "--group", "g-123", "--for", "2h"]).unwrap();
let Some(Command::Renew { target, duration }) = cli.command else {
panic!("expected renew")
};
assert_eq!(target.group.as_deref(), Some("g-123"));
assert!(target.port.is_none());
assert_eq!(duration, Some(SignedDuration::hours(2)));
let cli = Cli::try_parse_from(["troll", "release", "--group", "g-123"]).unwrap();
let Some(Command::Release { target, .. }) = cli.command else {
panic!("expected release")
};
assert_eq!(target.lease.group.as_deref(), Some("g-123"));
assert!(target.lease.port.is_none());
}
}