tree2md 0.14.0

Like the tree command, but outputs in Markdown. Optimized for AI agents.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use crate::hotspot::{parse_span, Metric, Span};
use clap::error::ErrorKind;
use clap::{Parser, ValueEnum};

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Parse CLI arguments, exiting with actionable guidance on usage errors.
///
/// On `--help`/`--version` we defer to clap (stdout, exit 0). On a usage error
/// we keep clap's message + "similar argument" tip, then append a short block of
/// runnable next commands so a failed invocation points straight at the fix.
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 {
    /// Use .gitignore if in a git repository
    Auto,
    /// Never use .gitignore
    Never,
    /// Always use .gitignore
    Always,
}

#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum FunMode {
    /// Auto-detect based on terminal
    Auto,
    /// Enable fun features (animations, emojis)
    On,
    /// Disable fun features
    Off,
}

#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum StatsMode {
    /// No statistics
    Off,
    /// Minimal statistics
    Min,
    /// Full statistics with progress bars
    Full,
}

#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum LocMode {
    /// Don't count lines of code
    Off,
    /// Fast line counting
    Fast,
    /// Accurate line counting
    Accurate,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum SortOrder {
    /// Alphabetical (directories first)
    Name,
    /// Most changed first (directories first); implies --hot
    Hot,
}

#[derive(Debug, Clone, PartialEq, ValueEnum)]
pub enum ContentsMode {
    /// Keep the first N characters per file (line-boundary cut)
    Head,
    /// Keep low-indentation lines, collapse deeply-indented blocks
    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

HOT SPOTS:
  --hot                Mark files that changed most often in git history
  --hot-since 30d      History window (d, w, m, y; default 90d)
  --hot-top 10         Show only the 10 hottest files
  --sort hot           Hottest first within each directory
  --hot-metric risk    Rank by commits|recency|churn|risk

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)
  --paths-from FILE    Include only the paths listed in FILE (`-` = stdin)
  --files0-from FILE   Same, NUL-separated (find -print0 / git ls-files -z)

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 {
    /// Target directory to scan
    #[arg(default_value = ".", value_name = "TARGET")]
    pub target: String,

    // ==================== Filtering Options ====================
    /// Limit traversal depth (e.g., -L 3 for max 3 levels deep)
    #[arg(
        short = 'L',
        long = "level",
        value_name = "N",
        help_heading = "Filtering"
    )]
    pub level: Option<usize>,

    /// Include patterns (e.g., -I "*.rs" -I "src/**")
    #[arg(
        short = 'I',
        long = "include",
        value_name = "GLOB",
        help_heading = "Filtering"
    )]
    pub include: Vec<String>,

    /// Exclude patterns (e.g., -X "*.log" -X "temp/**")
    #[arg(
        short = 'X',
        long = "exclude",
        value_name = "GLOB",
        help_heading = "Filtering"
    )]
    pub exclude: Vec<String>,

    /// Respect .gitignore (default: auto)
    #[arg(
        long = "use-gitignore",
        value_enum,
        default_value = "auto",
        value_name = "MODE",
        help_heading = "Filtering"
    )]
    pub use_gitignore: UseGitignoreMode,

    /// Read paths to include from FILE, one per line (`-` = stdin). No glob
    /// interpretation; paths are relative to the current directory. A listed
    /// directory includes everything beneath it. Combine with `-I`/`-X` to
    /// refine the set further (rules are applied last-match-wins on top).
    #[arg(
        long = "paths-from",
        value_name = "FILE",
        conflicts_with = "files0_from",
        help_heading = "Filtering"
    )]
    pub paths_from: Option<String>,

    /// Like --paths-from but NUL-separated (for `find -print0`, `git ls-files -z`, `fd -0`)
    #[arg(
        long = "files0-from",
        value_name = "FILE",
        help_heading = "Filtering",
        hide_short_help = true
    )]
    pub files0_from: Option<String>,

    /// Follow symbolic links (default: symlinks are skipped)
    #[arg(
        short = 'l',
        long = "follow-links",
        help_heading = "Filtering",
        hide_short_help = true
    )]
    pub follow_links: bool,

    // ==================== Fun & Emojis ====================
    /// Custom emoji mappings (e.g., --emoji ".rs=🚀" --emoji "test=🧪")
    #[arg(
        long = "emoji",
        value_name = "MAPPING",
        help_heading = "Fun & Style",
        hide_short_help = true
    )]
    pub emoji: Vec<String>,

    /// Load emoji mappings from TOML file
    #[arg(
        long = "emoji-map",
        value_name = "FILE",
        help_heading = "Fun & Style",
        hide_short_help = true
    )]
    pub emoji_map: Option<String>,

    /// Fun mode with emojis and animations
    #[arg(
        long = "fun",
        value_enum,
        default_value = "auto",
        help_heading = "Fun & Style",
        hide_short_help = true
    )]
    pub fun: FunMode,

    /// Disable animations
    #[arg(
        long = "no-anim",
        conflicts_with = "fun",
        help_heading = "Fun & Style",
        hide_short_help = true
    )]
    pub no_anim: bool,

    // ==================== Statistics ====================
    /// Statistics display: off|min|full (default: full)
    #[arg(
        long = "stats",
        value_enum,
        default_value = "full",
        help_heading = "Statistics",
        hide_short_help = true
    )]
    pub stats: StatsMode,

    /// Line counting mode: off|fast|accurate
    #[arg(
        long = "loc",
        value_enum,
        default_value = "fast",
        help_heading = "Statistics",
        hide_short_help = true
    )]
    pub loc: LocMode,

    // ==================== Contents ====================
    /// Include file contents as code blocks (for AI context)
    #[arg(short = 'c', long = "contents")]
    pub contents: bool,

    /// Limit total content to N characters — controls AI context budget (only with -c)
    #[arg(
        long = "max-chars",
        value_name = "N",
        requires = "contents",
        help_heading = "Contents"
    )]
    pub max_chars: Option<usize>,

    /// Truncation strategy: head = first N lines, nest = collapse deep indentation (only with --max-chars)
    #[arg(
        long = "contents-mode",
        value_enum,
        default_value = "head",
        help_heading = "Contents",
        hide_short_help = true
    )]
    pub contents_mode: ContentsMode,

    // ==================== Hot spots ====================
    /// Mark the files that changed most often in recent git history
    #[arg(long = "hot", help_heading = "Hot spots")]
    pub hot: bool,

    /// History window for --hot: 30d, 12w, 6m, 1y (default: 90d). Implies --hot
    #[arg(
        long = "hot-since",
        value_name = "SPAN",
        value_parser = parse_span,
        help_heading = "Hot spots",
        hide_short_help = true
    )]
    pub hot_since: Option<Span>,

    /// Show only the N hottest files and their directories. Implies --hot
    #[arg(
        long = "hot-top",
        value_name = "N",
        value_parser = parse_top,
        help_heading = "Hot spots",
        hide_short_help = true
    )]
    pub hot_top: Option<usize>,

    /// What makes a file hot (default: commits). Implies --hot
    #[arg(
        long = "hot-metric",
        value_enum,
        value_name = "METRIC",
        help_heading = "Hot spots",
        hide_short_help = true
    )]
    pub hot_metric: Option<Metric>,

    /// Order within each directory: name, or hot (hottest first; implies --hot)
    #[arg(
        long = "sort",
        value_enum,
        default_value = "name",
        value_name = "ORDER",
        help_heading = "Hot spots",
        hide_short_help = true
    )]
    pub sort: SortOrder,

    // ==================== Safety & Security ====================
    /// Apply safety filters (enabled by default)
    #[arg(long = "safe", help_heading = "Safety", hide_short_help = true)]
    pub safe: bool,

    /// Disable all safety filters (not recommended)
    #[arg(long = "unsafe", conflicts_with = "safe", help_heading = "Safety")]
    pub unsafe_mode: bool,

    /// Ordered -I / -X rules captured from argv. Populated AFTER clap parses
    /// because clap derive cannot preserve the relative order of `-I` and
    /// `-X` across two separate Vec fields. Last-match-wins semantics relies
    /// on this order.
    #[arg(skip)]
    pub filter_rules: Vec<FilterRule>,
}

fn parse_top(s: &str) -> Result<usize, String> {
    match s.trim().parse::<usize>() {
        Ok(n) if n > 0 => Ok(n),
        _ => Err("expected a positive number of files, e.g. 10".to_string()),
    }
}

/// Whether a filter rule includes or excludes paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RuleKind {
    #[default]
    Include,
    Exclude,
}

/// A single -I/-X rule with its original pattern, preserving CLI order.
#[derive(Debug, Clone, Default)]
pub struct FilterRule {
    pub kind: RuleKind,
    pub pattern: String,
}

/// Walk argv and extract `-I` / `-X` (and `--include` / `--exclude`) in the
/// order they appeared on the command line. Used to drive last-match-wins
/// semantics in the filter engine.
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();
    // Skip program name
    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 });
        };
        // Long forms with `=`
        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;
        }
        // Long forms with space
        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;
        }
        // Short forms `-I`, `-X` with space
        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;
        }
        // Short forms `-Ifoo`, `-Xfoo` (attached value)
        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 {
    /// Determine if safe mode is enabled (default: true)
    pub fn is_safe_mode(&self) -> bool {
        !self.unsafe_mode
    }

    /// Check if stats should be shown
    pub fn should_show_stats(&self) -> bool {
        self.stats != StatsMode::Off
    }

    /// History window for hot spots, or `None` when they are off. Any
    /// hot spot option turns them on.
    pub fn hot_span(&self) -> Option<Span> {
        let on = self.hot
            || self.hot_since.is_some()
            || self.hot_top.is_some()
            || self.hot_metric.is_some()
            || self.sort == SortOrder::Hot;
        on.then(|| self.hot_since.clone().unwrap_or_default())
    }

    /// Check if fun mode is enabled
    pub fn is_fun_enabled(&self, is_tty: bool) -> bool {
        match self.fun {
            FunMode::On => true,
            FunMode::Off => false,
            FunMode::Auto => is_tty,
        }
    }
}