use anyhow::Context;
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use std::time::Duration;
use termshot::capture::LineSelection;
use termshot::config::Config;
use termshot::redaction::{
ManualRedactionSpec, ManualRedactions, REDACTION_DISABLED_MSG, RedactionEngine,
explicit_request_is_blocked, resolve_should_redact,
};
use termshot::renderer::{
ChromeOptions, ComposeLayout, ExtendedRenderOptions, FontSelection, RedactionRequest, Renderer,
RendererOptions, TextOptions, fallback_output_name,
};
use termshot::{executor, server};
#[derive(Parser)]
#[command(
name = "termshot",
about = "Capture terminal screenshots with full ANSI rendering",
version
)]
struct Cli {
#[command(subcommand)]
command: Commands,
#[arg(long, global = true)]
config: Option<String>,
#[arg(long, global = true)]
rules_path: Option<String>,
}
#[derive(Subcommand)]
enum Commands {
Mcp,
Exec {
#[arg(trailing_var_arg = true, required = true)]
command: Vec<String>,
#[arg(long, value_name = "DIR")]
cwd: Option<PathBuf>,
#[arg(short = 'c', long, default_value_t = 120, value_parser = clap::value_parser!(u16).range(1..=500))]
cols: u16,
#[arg(short = 'r', long, default_value_t = 40, value_parser = clap::value_parser!(u16).range(1..=500))]
rows: u16,
#[arg(short, long, default_value_t = 30)]
timeout: u64,
#[arg(long, value_name = "N", conflicts_with = "tail_lines", value_parser = clap::value_parser!(u64).range(1..))]
head_lines: Option<u64>,
#[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
tail_lines: Option<u64>,
#[arg(long)]
chrome: Option<String>,
#[arg(long)]
font: Option<PathBuf>,
#[arg(long)]
font_bold: Option<PathBuf>,
#[arg(long = "no-prompt", default_value_t = false)]
no_prompt: bool,
#[arg(long)]
theme: Option<String>,
#[arg(long)]
title: Option<String>,
#[arg(long, default_value_t = false)]
timestamp: bool,
#[arg(short, long)]
output: Option<String>,
#[arg(long, default_value_t = false)]
redact: bool,
#[arg(long, value_name = "RULES")]
redact_rules: Option<String>,
#[arg(long = "no-redact", default_value_t = false)]
no_redact: bool,
#[arg(long = "redact-text", default_value_t = false)]
redact_text: bool,
#[arg(
long = "redaction",
value_name = "JSON",
conflicts_with = "no_redact",
verbatim_doc_comment
)]
redaction: Vec<String>,
#[arg(long = "plain-text", default_value_t = false)]
plain_text: bool,
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
auto_crop: bool,
#[arg(long = "no-description", default_value_t = false)]
no_description: bool,
#[arg(long, overrides_with = "no_rounded")]
rounded: bool,
#[arg(long = "no-rounded", overrides_with = "rounded")]
no_rounded: bool,
},
Render {
input: String,
#[arg(short = 'c', long, default_value_t = 120, value_parser = clap::value_parser!(u16).range(1..=500))]
cols: u16,
#[arg(short = 'r', long, default_value_t = 40, value_parser = clap::value_parser!(u16).range(1..=500))]
rows: u16,
#[arg(long, value_name = "N", conflicts_with = "tail_lines", value_parser = clap::value_parser!(u64).range(1..))]
head_lines: Option<u64>,
#[arg(long, value_name = "N", value_parser = clap::value_parser!(u64).range(1..))]
tail_lines: Option<u64>,
#[arg(long)]
theme: Option<String>,
#[arg(long)]
chrome: Option<String>,
#[arg(long)]
title: Option<String>,
#[arg(long, default_value_t = false)]
timestamp: bool,
#[arg(short, long)]
output: Option<String>,
#[arg(long = "plain-text", default_value_t = false)]
plain_text: bool,
#[arg(long, default_value_t = false)]
redact: bool,
#[arg(long, value_name = "RULES")]
redact_rules: Option<String>,
#[arg(long = "no-redact", default_value_t = false)]
no_redact: bool,
#[arg(long = "redact-text", default_value_t = false)]
redact_text: bool,
#[arg(
long = "redaction",
value_name = "JSON",
conflicts_with = "no_redact",
verbatim_doc_comment
)]
redaction: Vec<String>,
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
auto_crop: bool,
#[arg(long = "no-description", default_value_t = false)]
no_description: bool,
#[arg(long, overrides_with = "no_rounded")]
rounded: bool,
#[arg(long = "no-rounded", overrides_with = "rounded")]
no_rounded: bool,
},
Themes,
Compose {
#[arg(required = true, num_args = 2..)]
images: Vec<PathBuf>,
#[arg(long, default_value = "vertical")]
layout: String,
#[arg(long, default_value_t = 2)]
divider: u32,
#[arg(long)]
theme: Option<String>,
#[arg(long)]
chrome: Option<String>,
#[arg(long)]
title: Option<String>,
#[arg(short, long)]
output: Option<String>,
},
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
.add_directive("termshot=info".parse()?),
)
.with_writer(std::io::stderr)
.init();
let loaded = Config::load_with_options(cli.config.as_deref(), cli.rules_path.as_deref())?;
let max_scrollback_lines = loaded.max_scrollback_lines;
let config = loaded.into_config();
match cli.command {
Commands::Mcp => {
let renderer = build_renderer(&config, max_scrollback_lines, None, None)?;
server::run_mcp_server(config, renderer).await?;
}
Commands::Exec {
command,
cwd,
cols,
rows,
timeout,
head_lines,
tail_lines,
no_prompt,
theme,
chrome,
font,
font_bold,
title,
timestamp,
output,
redact,
redact_rules,
no_redact,
redact_text,
redaction,
plain_text,
auto_crop,
no_description,
rounded,
no_rounded,
} => {
let renderer = build_renderer(
&config,
max_scrollback_lines,
font.as_deref(),
font_bold.as_deref(),
)?;
let lines = line_selection(head_lines, tail_lines)?;
let timeout = Duration::from_secs(timeout);
let working_dir = cwd
.as_deref()
.map(executor::resolve_working_directory)
.transpose()?;
let manual = manual_redactions(&redaction)?;
let exec_result = if !no_prompt {
let cmd_refs: Vec<&str> = command.iter().map(|s| s.as_str()).collect();
executor::execute_command_in_dir(
&cmd_refs,
&config.shell,
rows,
cols,
timeout,
working_dir.as_deref(),
)
.await?
} else {
let cmd_str = command.join(" ");
executor::execute_command_simple_in_dir(
&cmd_str,
&config.shell,
rows,
cols,
timeout,
working_dir.as_deref(),
)
.await?
};
let theme_name = theme.as_deref();
let chrome_options = chrome_options_from_args(
&config,
chrome,
title,
timestamp,
rounded_override(rounded, no_rounded),
command.first().map(String::as_str),
);
let redaction_engine =
resolve_redaction(&config, redact, redact_rules.as_deref(), no_redact)?;
let redaction_request = redaction_engine.as_ref().map(|engine| RedactionRequest {
engine,
rules: redact_rules.as_ref().map(|s| parse_rule_list(s)),
});
let output_name = {
let fallback_dir = working_dir
.as_deref()
.map(PathBuf::from)
.or_else(|| std::env::current_dir().ok());
fallback_output_name(fallback_dir.as_deref(), &command.join(" "))
};
let (image_path, terminal_text, redactions, meta) = renderer
.render_bytes_with_extended_options(
&exec_result.raw_output,
cols,
rows,
&config.output_dir,
Some(output_name.as_str()),
theme_name,
chrome_options.as_ref(),
redaction_request.as_ref(),
TextOptions {
strip_ansi: plain_text,
redact_text,
embed_description: config.embed_description && !no_description,
from_screen: !no_prompt,
},
auto_crop,
render_options(lines, manual.as_ref()),
)?;
if meta.truncated {
eprintln!("{}", truncation_notice(&renderer, rows, cols));
}
if !redactions.is_empty() {
let summary = redactions
.iter()
.map(|(name, count)| format!("{}x {}", count, name))
.collect::<Vec<_>>()
.join(", ");
eprintln!("Redacted: {}", summary);
}
let final_path = if let Some(out) = output {
move_screenshot(&image_path, &out)?
} else {
image_path
};
println!("{}", final_path.display());
eprintln!("--- Terminal Output ---");
eprintln!("{}", terminal_text);
if exec_result.timed_out {
eprintln!("(timed out)");
} else if let Some(code) = exec_result.exit_code
&& code != 0
{
eprintln!("(exit {})", code);
}
}
Commands::Render {
input,
cols,
rows,
head_lines,
tail_lines,
theme,
chrome,
title,
timestamp,
output,
plain_text,
redact,
redact_rules,
no_redact,
redact_text,
redaction,
auto_crop,
no_description,
rounded,
no_rounded,
} => {
let renderer = build_renderer(&config, max_scrollback_lines, None, None)?;
let lines = line_selection(head_lines, tail_lines)?;
let manual = manual_redactions(&redaction)?;
let data = if input == "-" {
use std::io::Read;
let mut buf = Vec::new();
std::io::stdin()
.read_to_end(&mut buf)
.context("failed to read ANSI data from stdin")?;
buf
} else {
std::fs::read(&input)
.with_context(|| format!("failed to read ANSI file {:?}", input))?
};
let theme_name = theme.as_deref();
let chrome_options = chrome_options_from_args(
&config,
chrome,
title,
timestamp,
rounded_override(rounded, no_rounded),
None,
);
let output_name = if input == "-" {
Some("render".to_string())
} else {
std::path::Path::new(&input)
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
};
let redaction_engine =
resolve_redaction(&config, redact, redact_rules.as_deref(), no_redact)?;
let redaction_request = redaction_engine.as_ref().map(|engine| RedactionRequest {
engine,
rules: redact_rules.as_ref().map(|s| parse_rule_list(s)),
});
let (image_path, plain_text, redactions, meta) = renderer
.render_bytes_with_extended_options(
&data,
cols,
rows,
&config.output_dir,
output_name.as_deref(),
theme_name,
chrome_options.as_ref(),
redaction_request.as_ref(),
TextOptions {
strip_ansi: plain_text,
redact_text,
embed_description: config.embed_description && !no_description,
from_screen: false,
},
auto_crop,
render_options(lines, manual.as_ref()),
)?;
if meta.truncated {
eprintln!("{}", truncation_notice(&renderer, rows, cols));
}
if !redactions.is_empty() {
let summary = redactions
.iter()
.map(|(name, count)| format!("{}x {}", count, name))
.collect::<Vec<_>>()
.join(", ");
eprintln!("Redacted: {}", summary);
}
let final_path = if let Some(out) = output {
move_screenshot(&image_path, &out)?
} else {
image_path
};
println!("{}", final_path.display());
eprintln!("--- Terminal Output ---");
eprint!("{}", plain_text);
}
Commands::Compose {
images,
layout,
divider,
theme,
chrome,
title,
output,
} => {
let renderer = build_renderer(&config, max_scrollback_lines, None, None)?;
let layout = ComposeLayout::parse(&layout)?;
let chrome_options =
chrome_options_from_args(&config, chrome, title, false, None, None);
let output_path = output.map(PathBuf::from);
let path = renderer.compose_screenshots(
&images,
layout,
divider,
theme.as_deref(),
chrome_options.as_ref(),
&config.output_dir,
output_path.as_deref(),
config.embed_description,
)?;
println!("{}", path.display());
}
Commands::Themes => {
let renderer = build_renderer(&config, max_scrollback_lines, None, None)?;
let names = renderer.theme_names();
let default = &config.default_theme;
for name in &names {
let kind = if config.user_theme_names.contains(name) {
"user"
} else {
"built-in"
};
if name == default {
println!("{} ({}, default)", name, kind);
} else {
println!("{} ({})", name, kind);
}
}
}
}
Ok(())
}
fn build_renderer(
config: &Config,
max_scrollback_lines: usize,
font: Option<&std::path::Path>,
font_bold: Option<&std::path::Path>,
) -> anyhow::Result<Renderer> {
let selection = FontSelection {
font_override: font.map(PathBuf::from),
font_bold_override: font_bold.map(PathBuf::from),
global_font: config.font_path.clone(),
global_fallback_fonts: Vec::new(),
};
Renderer::new_with_options(
&selection,
config.font_size,
&config.themes,
&config.default_theme,
&config.chrome,
RendererOptions::default().with_max_scrollback_lines(max_scrollback_lines),
)
}
fn manual_redactions(specs: &[String]) -> anyhow::Result<Option<ManualRedactions>> {
if specs.is_empty() {
return Ok(None);
}
let parsed = ManualRedactionSpec::parse_all(specs)?;
Ok(Some(ManualRedactions::new(&parsed, true)?))
}
fn render_options(
lines: LineSelection,
manual: Option<&ManualRedactions>,
) -> ExtendedRenderOptions<'_> {
ExtendedRenderOptions::default()
.with_lines(lines)
.with_optional_manual(manual)
}
fn resolve_redaction(
config: &Config,
redact: bool,
redact_rules: Option<&str>,
no_redact: bool,
) -> anyhow::Result<Option<RedactionEngine>> {
let want_redact = redact || redact_rules.is_some();
if explicit_request_is_blocked(&config.redaction, want_redact, no_redact) {
anyhow::bail!(REDACTION_DISABLED_MSG);
}
if !resolve_should_redact(&config.redaction, want_redact, no_redact) {
return Ok(None);
}
match RedactionEngine::from_config(&config.redaction) {
Ok(engine) => {
if let Some(rules) = redact_rules {
engine.validate_rule_names(&parse_rule_list(rules))?;
}
Ok(Some(engine))
}
Err(e) if want_redact => Err(anyhow::anyhow!(
"redaction was requested but could not be enabled: {}",
e
)),
Err(e) => {
eprintln!("(auto-redaction disabled: {})", e);
Ok(None)
}
}
}
fn chrome_options_from_args(
config: &Config,
chrome: Option<String>,
title: Option<String>,
timestamp: bool,
rounded: Option<bool>,
inferred_title: Option<&str>,
) -> Option<ChromeOptions> {
let has_overrides = chrome.is_some() || title.is_some() || timestamp || rounded.is_some();
let mut options = ChromeOptions::from_config(&config.chrome);
if let Some(preset) = chrome {
options.enabled = preset != "none";
options.preset = preset;
}
if let Some(title) = title {
options.title = Some(title);
} else if options.enabled {
options.title = inferred_title.map(str::to_owned);
}
if timestamp {
options.timestamp = true;
}
if let Some(rounded) = rounded {
options.rounded = rounded;
}
if !(has_overrides || options.enabled && inferred_title.is_some()) {
return None;
}
Some(options)
}
fn rounded_override(rounded: bool, no_rounded: bool) -> Option<bool> {
if no_rounded {
Some(false)
} else if rounded {
Some(true)
} else {
None
}
}
fn line_selection(head: Option<u64>, tail: Option<u64>) -> anyhow::Result<LineSelection> {
LineSelection::from_head_tail(head.map(|n| n as usize), tail.map(|n| n as usize))
}
fn truncation_notice(renderer: &Renderer, rows: u16, cols: u16) -> String {
let configured = renderer.max_scrollback_lines();
let effective = renderer.effective_scrollback_lines(rows, cols);
let advice = if effective < configured {
format!(
"the configured {} was capped to what {} columns can hold in memory, so keep \
fewer columns or select fewer lines",
configured, cols
)
} else {
"raise `max_scrollback_lines` in the config to keep more".to_string()
};
format!(
"(output exceeded the {}-line scrollback, so the oldest lines were dropped; {}, \
or use --head-lines/--tail-lines to pick the end you care about)",
effective, advice
)
}
fn parse_rule_list(s: &str) -> Vec<String> {
s.split(',')
.map(|r| r.trim())
.filter(|r| !r.is_empty())
.map(|r| r.to_string())
.collect()
}
fn move_screenshot(src: &std::path::Path, dst: &str) -> anyhow::Result<PathBuf> {
let dst = PathBuf::from(dst);
match std::fs::rename(src, &dst) {
Ok(()) => Ok(dst),
Err(_) => {
std::fs::copy(src, &dst)?;
std::fs::remove_file(src).ok();
Ok(dst)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
#[test]
fn cli_definition_is_valid() {
Cli::command().debug_assert();
}
fn exec_selection(args: &[&str]) -> anyhow::Result<LineSelection> {
let cli = Cli::try_parse_from(args)?;
match cli.command {
Commands::Exec {
head_lines,
tail_lines,
..
} => line_selection(head_lines, tail_lines),
_ => panic!("expected the exec subcommand"),
}
}
#[test]
fn head_and_tail_lines_are_mutually_exclusive() {
assert_eq!(
exec_selection(&["termshot", "exec", "--", "seq 1 200"]).unwrap(),
LineSelection::All
);
assert_eq!(
exec_selection(&["termshot", "exec", "--head-lines", "10", "--", "seq 1 200"]).unwrap(),
LineSelection::Head(10)
);
assert_eq!(
exec_selection(&["termshot", "exec", "--tail-lines", "10", "--", "seq 1 200"]).unwrap(),
LineSelection::Tail(10)
);
let err = Cli::try_parse_from([
"termshot",
"exec",
"--head-lines",
"10",
"--tail-lines",
"10",
"--",
"seq 1 200",
])
.err()
.expect("--head-lines and --tail-lines must not be accepted together");
assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
assert!(
Cli::try_parse_from(["termshot", "exec", "--head-lines", "0", "--", "echo hi"])
.is_err()
);
}
#[test]
fn render_also_takes_head_and_tail_lines() {
let cli = Cli::try_parse_from(["termshot", "render", "--tail-lines", "5", "out.ansi"])
.expect("parses");
match cli.command {
Commands::Render {
head_lines,
tail_lines,
..
} => {
assert_eq!(
line_selection(head_lines, tail_lines).unwrap(),
LineSelection::Tail(5)
);
}
_ => panic!("expected render"),
}
assert!(
Cli::try_parse_from([
"termshot",
"render",
"--head-lines",
"5",
"--tail-lines",
"5",
"out.ansi",
])
.is_err()
);
}
}