use clap::error::ErrorKind;
use clap::{Parser, ValueEnum};
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn parse() -> Args {
let argv: Vec<String> = std::env::args().collect();
match Args::try_parse_from(&argv) {
Ok(mut args) => {
args.filter_rules = extract_filter_rules(argv.iter().map(|s| s.as_str()));
args
}
Err(e) => {
e.print().ok();
let is_help_or_version = matches!(
e.kind(),
ErrorKind::DisplayHelp
| ErrorKind::DisplayVersion
| ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
);
if !is_help_or_version {
eprintln!();
eprintln!("Try:");
eprintln!(" tree2md # pretty tree of the current directory");
eprintln!(" tree2md -c | pbcopy # tree + file contents for AI context");
}
std::process::exit(e.exit_code());
}
}
}
#[derive(Debug, Clone, ValueEnum)]
pub enum UseGitignoreMode {
Auto,
Never,
Always,
}
#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum FunMode {
Auto,
On,
Off,
}
#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum StatsMode {
Off,
Min,
Full,
}
#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum LocMode {
Off,
Fast,
Accurate,
}
#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum ContentsMode {
Head,
Nest,
}
#[derive(Parser, Clone)]
#[command(name = "tree2md")]
#[command(version = VERSION)]
#[command(
about = "Like the `tree` command, but optimized for AI agents.\n\nQUICK START:\n tree2md # pretty tree of the current directory\n tree2md -c | pbcopy # tree + file contents, copied for AI context"
)]
#[command(
long_about = r#"tree2md — Visualize your codebase structure for humans and AI agents.
QUICK START:
tree2md # Pretty tree in terminal (TTY)
tree2md | pbcopy # Pipe-friendly tree for clipboard
tree2md -c -I "*.rs" -L 2 # Tree + file contents for AI context
tree2md -c --max-chars 30000 # Fit contents within token budget
OUTPUT MODES (auto-detected):
TTY Pretty output with emoji, LOC bars, stats, tree characters
Pipe Simple tree + line counts — ideal for pbcopy or LLM pipes
-c Tree + file contents (code-fenced) — full context for agents
-c --max-chars N Truncate contents to fit within N characters
FILTERING:
-L N Limit depth to N levels
-I "*.rs" Include only matching files
-X "*.log" Exclude matching files
--use-gitignore Respect .gitignore (auto|never|always)
SAFETY:
Safe by default: excludes .env, private keys, node_modules, etc.
Use --unsafe to disable safety filters (not recommended)
Use -I patterns to selectively include filtered items"#
)]
pub struct Args {
#[arg(default_value = ".", value_name = "TARGET")]
pub target: String,
#[arg(
short = 'L',
long = "level",
value_name = "N",
help_heading = "Filtering"
)]
pub level: Option<usize>,
#[arg(
short = 'I',
long = "include",
value_name = "GLOB",
help_heading = "Filtering"
)]
pub include: Vec<String>,
#[arg(
short = 'X',
long = "exclude",
value_name = "GLOB",
help_heading = "Filtering"
)]
pub exclude: Vec<String>,
#[arg(
long = "use-gitignore",
value_enum,
default_value = "auto",
value_name = "MODE",
help_heading = "Filtering"
)]
pub use_gitignore: UseGitignoreMode,
#[arg(
short = 'l',
long = "follow-links",
help_heading = "Filtering",
hide_short_help = true
)]
pub follow_links: bool,
#[arg(
long = "emoji",
value_name = "MAPPING",
help_heading = "Fun & Style",
hide_short_help = true
)]
pub emoji: Vec<String>,
#[arg(
long = "emoji-map",
value_name = "FILE",
help_heading = "Fun & Style",
hide_short_help = true
)]
pub emoji_map: Option<String>,
#[arg(
long = "fun",
value_enum,
default_value = "auto",
help_heading = "Fun & Style",
hide_short_help = true
)]
pub fun: FunMode,
#[arg(
long = "no-anim",
conflicts_with = "fun",
help_heading = "Fun & Style",
hide_short_help = true
)]
pub no_anim: bool,
#[arg(
long = "stats",
value_enum,
default_value = "full",
help_heading = "Statistics",
hide_short_help = true
)]
pub stats: StatsMode,
#[arg(
long = "loc",
value_enum,
default_value = "fast",
help_heading = "Statistics",
hide_short_help = true
)]
pub loc: LocMode,
#[arg(short = 'c', long = "contents")]
pub contents: bool,
#[arg(
long = "max-chars",
value_name = "N",
requires = "contents",
help_heading = "Contents"
)]
pub max_chars: Option<usize>,
#[arg(
long = "contents-mode",
value_enum,
default_value = "head",
help_heading = "Contents",
hide_short_help = true
)]
pub contents_mode: ContentsMode,
#[arg(long = "safe", help_heading = "Safety", hide_short_help = true)]
pub safe: bool,
#[arg(long = "unsafe", conflicts_with = "safe", help_heading = "Safety")]
pub unsafe_mode: bool,
#[arg(skip)]
pub filter_rules: Vec<FilterRule>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RuleKind {
#[default]
Include,
Exclude,
}
#[derive(Debug, Clone, Default)]
pub struct FilterRule {
pub kind: RuleKind,
pub pattern: String,
}
pub fn extract_filter_rules<I, S>(argv: I) -> Vec<FilterRule>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut rules = Vec::new();
let mut iter = argv.into_iter().peekable();
iter.next();
while let Some(arg) = iter.next() {
let a = arg.as_ref();
if a == "--" {
break;
}
let push = |kind: RuleKind, pat: String, rules: &mut Vec<FilterRule>| {
rules.push(FilterRule { kind, pattern: pat });
};
if let Some(rest) = a.strip_prefix("--include=") {
push(RuleKind::Include, rest.to_string(), &mut rules);
continue;
}
if let Some(rest) = a.strip_prefix("--exclude=") {
push(RuleKind::Exclude, rest.to_string(), &mut rules);
continue;
}
if a == "--include" {
if let Some(v) = iter.next() {
push(RuleKind::Include, v.as_ref().to_string(), &mut rules);
}
continue;
}
if a == "--exclude" {
if let Some(v) = iter.next() {
push(RuleKind::Exclude, v.as_ref().to_string(), &mut rules);
}
continue;
}
if a == "-I" {
if let Some(v) = iter.next() {
push(RuleKind::Include, v.as_ref().to_string(), &mut rules);
}
continue;
}
if a == "-X" {
if let Some(v) = iter.next() {
push(RuleKind::Exclude, v.as_ref().to_string(), &mut rules);
}
continue;
}
if let Some(rest) = a.strip_prefix("-I") {
if !rest.is_empty() {
push(RuleKind::Include, rest.to_string(), &mut rules);
continue;
}
}
if let Some(rest) = a.strip_prefix("-X") {
if !rest.is_empty() {
push(RuleKind::Exclude, rest.to_string(), &mut rules);
continue;
}
}
}
rules
}
impl Args {
pub fn is_safe_mode(&self) -> bool {
!self.unsafe_mode
}
pub fn should_show_stats(&self) -> bool {
self.stats != StatsMode::Off
}
pub fn is_fun_enabled(&self, is_tty: bool) -> bool {
match self.fun {
FunMode::On => true,
FunMode::Off => false,
FunMode::Auto => is_tty,
}
}
}