use std::io::{self, Write};
use crate::{
cli::Color,
style::{COMMAND, DIM, HEADER, RESET, is_no_color_flag},
};
const BANNER_LINES: [&str; 6] = [
"████████╗██████╗ ██████╗ ██╗ ██╗ ",
"╚══██╔══╝██╔══██╗██╔═══██╗██║ ██║ ",
" ██║ ██████╔╝██║ ██║██║ ██║ ",
" ██║ ██╔══██╗██║ ██║██║ ██║ ",
" ██║ ██║ ██║╚██████╔╝███████╗███████╗",
" ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝",
];
const BANNER_GRADIENT: [u8; 6] = [33, 39, 45, 81, 117, 220];
const AUTHOR: &str = "Michel Abboud";
const URL: &str = "https://github.com/michelabboud/troll";
const SHORT_GUIDE: &str = include_str!("../embedded/docs/llm-guide.md");
const FULL_GUIDE: &str = include_str!("../embedded/docs/llm-guide-full.md");
const AGENT: &[(&str, &str)] = &[
(
"troll --llm-guide",
"Read the short agent guide; prefer --json for commands.",
),
("troll --llm-guide --full", "Read the complete manual."),
];
const QUICK_START: &[(&str, &str)] = &[
("troll --help", "Full command reference."),
("troll list", "See claims, leases, and live listeners."),
("troll check <port>", "Check who owns or listens on a port."),
(
"troll lease --project P --purpose S",
"Reserve a temporary port from the lease range.",
),
(
"troll serve",
"Start the local HTTP API, console, and hourly sweep.",
),
];
const BUILT: &[(&str, &str)] = &[
("doctor", "Inspect registry health and drift."),
("claim", "Register a permanent port."),
("edit", "Edit a permanent claim in place."),
("lease", "Reserve a port or stack for a limited time."),
("lease-edit", "Edit a lease in place."),
("renew", "Reset the expiry of a lease or group."),
("release", "Release a claim, lease, or lease group."),
(
"history",
"List or restore apps and ports removed within 30 days.",
),
("zone", "Manage red zones and inspect allocation conflicts."),
("app", "Reserve and manage an app's ports."),
(
"env",
"Print an app's component ports as environment assignments.",
),
("with", "Run a child with a leased port."),
("check", "Check a port and its listeners."),
(
"explain",
"Explain a port's claims, leases, red zones, files, and history.",
),
("list", "List entries and listeners."),
("sweep", "Remove reclaimable leases."),
("serve", "Run the local HTTP API and automatic sweep."),
("init", "Configure troll and claim its service port."),
(
"setup",
"Prepare agent plugins or write the user service definition.",
),
("import-legacy", "Preview or import legacy port claims."),
(
"mcp",
"Model Context Protocol server over standard input and output.",
),
];
const OPTIONS: &[(&str, &str)] = &[
(
"-h, --help",
"Print this help; use a command's --help for its options.",
),
("-V, --version", "Print the version."),
("--json", "Print command results as JSON."),
(
"--color <auto|always|never>",
"Control ANSI color (default: auto; off on pipes, CI, and agents).",
),
(
"--no-ansi-colors",
"Disable ANSI color everywhere (aliases: --no-color, --no-colors).",
),
(
"--llm-guide [--full]",
"Print the agent guide or full manual.",
),
];
const EXIT: &[(&str, &str)] = &[
("0", "Success."),
("1", "Failure."),
("2", "Usage error."),
("3", "Operation refused."),
("4", "Registry lock timeout."),
];
const FILES: &[(&str, &str)] = &[
(
"$XDG_CONFIG_HOME/troll/",
"Config home; defaults to $HOME/.config/troll/.",
),
("config.toml", "Optional configuration in the config home."),
(
"registry.toml",
"Registry in registry_home (the config home by default).",
),
(
"history.toml",
"30-day removal history for restoring released apps and ports.",
),
];
fn paint(text: &str, style: &str, color: bool) -> String {
if color {
format!("{style}{text}{RESET}")
} else {
text.to_owned()
}
}
fn write_banner(out: &mut dyn Write, color: bool) -> io::Result<()> {
for (line, step) in BANNER_LINES.iter().zip(BANNER_GRADIENT) {
if color {
writeln!(out, "\x1b[1;38;5;{step}m{line}{RESET}")?;
} else {
writeln!(out, "{line}")?;
}
}
Ok(())
}
fn section(
out: &mut dyn Write,
title: &str,
rows: &[(&str, &str)],
width: usize,
color: bool,
) -> io::Result<()> {
writeln!(out, "{}", paint(title, HEADER, color))?;
for (left, right) in rows {
let pad = " ".repeat(width.saturating_sub(left.chars().count()));
writeln!(
out,
" {}{pad} {}",
paint(left, COMMAND, color),
paint(right, DIM, color)
)?;
}
writeln!(out)
}
pub fn print(full: bool, color: bool) -> io::Result<()> {
let mut out = io::stdout().lock();
render(&mut out, full, color)
}
fn render(out: &mut dyn Write, full: bool, color: bool) -> io::Result<()> {
let sections: &[&[(&str, &str)]] = if full {
&[AGENT, BUILT, OPTIONS, EXIT, FILES]
} else {
&[AGENT, QUICK_START]
};
let width = sections
.iter()
.flat_map(|rows| rows.iter())
.map(|(left, _)| left.chars().count())
.max()
.unwrap_or(0);
write_banner(out, color)?;
writeln!(out)?;
let identity = format!(
"troll {}: {}",
env!("CARGO_PKG_VERSION"),
env!("CARGO_PKG_DESCRIPTION")
);
writeln!(out, "{}\n", paint(&identity, HEADER, color))?;
section(out, "IF YOU ARE AN LLM:", AGENT, width, color)?;
if full {
for (title, rows) in [
("COMMANDS:", BUILT),
("GLOBAL OPTIONS:", OPTIONS),
("EXIT CODES:", EXIT),
("FILES:", FILES),
] {
section(out, title, rows, width, color)?;
}
writeln!(
out,
"{}",
paint(
"Output uses ANSI color on human terminals and raw plain text on pipes, CI, and agent shells (override with TROLL_OUTPUT=plain|human).",
DIM,
color
)
)?;
writeln!(
out,
"{}",
paint(&format!("Author: {AUTHOR} · {URL}"), DIM, color)
)?;
} else {
section(out, "QUICK START:", QUICK_START, width, color)?;
writeln!(
out,
"{}",
paint("Run troll --help for all commands and options.", DIM, color)
)?;
writeln!(
out,
"{}",
paint(&format!("Author: {AUTHOR} · {URL}"), DIM, color)
)?;
}
Ok(())
}
pub fn guide(full: bool) -> io::Result<()> {
io::stdout()
.lock()
.write_all(if full { FULL_GUIDE } else { SHORT_GUIDE }.as_bytes())
}
pub fn help_color(args: &[std::ffi::OsString]) -> Color {
let mut color = Color::Auto;
let mut args = args.iter().skip(1);
while let Some(arg) = args.next() {
if arg.to_str().is_some_and(is_no_color_flag) {
color = Color::Never;
continue;
}
let value = if arg == "--color" {
args.next().and_then(|v| v.to_str())
} else {
arg.to_str().and_then(|s| s.strip_prefix("--color="))
};
color = match value {
Some("always") => Color::Always,
Some("never") => Color::Never,
Some("auto") => Color::Auto,
_ => color,
};
}
color
}
pub fn is_root_help(error: &clap::Error) -> bool {
error.kind() == clap::error::ErrorKind::DisplayHelp
&& error.to_string().lines().any(|line| {
line.starts_with("Usage: troll [OPTIONS]")
|| line.starts_with("Usage: troll.exe [OPTIONS]")
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::Cli;
use clap::CommandFactory;
#[test]
fn all_clap_commands_are_in_help_and_manual() {
let mut help = Vec::new();
render(&mut help, true, false).unwrap();
let help = String::from_utf8(help).unwrap();
assert!(!help.contains('\x1b'));
for command in Cli::command().get_subcommands() {
let name = command.get_name();
assert!(
BUILT.iter().any(|(entry, _)| *entry == name),
"missing help for {name}"
);
assert!(
help.lines()
.any(|line| line.split_whitespace().next() == Some(name)),
"missing help for {name}"
);
assert!(
FULL_GUIDE.lines().any(|line| line == format!("## {name}")),
"missing manual section for {name}"
);
}
}
#[test]
fn embedded_guides_match_repo_docs() {
assert_eq!(SHORT_GUIDE, include_str!("../../../docs/llm-guide.md"));
assert_eq!(FULL_GUIDE, include_str!("../../../docs/llm-guide-full.md"));
}
#[test]
fn colored_help_uses_gradient_banner_and_semantic_styles() {
let mut help = Vec::new();
render(&mut help, true, true).unwrap();
let help = String::from_utf8(help).unwrap();
for step in BANNER_GRADIENT {
assert!(help.contains(&format!("\x1b[1;38;5;{step}m")), "{step}");
}
assert!(help.contains(&format!("{HEADER}IF YOU ARE AN LLM:{RESET}")));
assert!(help.contains(&format!("{COMMAND}troll --llm-guide{RESET}")));
}
}