tree2md 0.13.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
//! Hot spots: how often each file changed in recent git history.
//!
//! The history comes from one `git log --numstat` run over the target
//! directory. Counts are keyed by the path relative to the target, the same
//! form as a node's `display_path`, so the renderers can join them onto the
//! tree: a file that is not in the tree (filtered, a safety-preset secret,
//! deleted since) never shows up, whatever the history says.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// Commits that touch more files than this (inside the target) are skipped:
/// mass reformatting, renames and vendoring would otherwise make every file
/// they touch look hot.
pub const BULK_COMMIT_FILES: usize = 50;

/// How many files the "Hot spots" ranking lists (and the TTY tree marks).
pub const TOP_N: usize = 10;

/// File names whose churn is bookkeeping, not editing: lockfiles and
/// changelogs change with nearly every release or dependency bump.
const NOISE_FILE_NAMES: &[&str] = &[
    "Cargo.lock",
    "package-lock.json",
    "npm-shrinkwrap.json",
    "yarn.lock",
    "pnpm-lock.yaml",
    "bun.lock",
    "bun.lockb",
    "poetry.lock",
    "Pipfile.lock",
    "uv.lock",
    "pdm.lock",
    "Gemfile.lock",
    "composer.lock",
    "go.sum",
    "flake.lock",
    "mix.lock",
    "Podfile.lock",
    "Package.resolved",
    "pubspec.lock",
    "gradle.lockfile",
    "packages.lock.json",
];

/// Changelog stems, compared case-insensitively (`CHANGELOG.md`, `changes.rst`).
const NOISE_STEMS: &[&str] = &["changelog", "changes"];

/// A history window such as `90d`, given as a number and a unit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span {
    pub days: u32,
    /// Normalized form for display, e.g. `90d`.
    pub label: String,
}

impl Default for Span {
    fn default() -> Self {
        Self {
            days: 90,
            label: "90d".to_string(),
        }
    }
}

/// Parse `<N><unit>` with unit `d` (days), `w` (weeks), `m` (30-day months)
/// or `y` (365-day years). Used as a clap value parser.
pub fn parse_span(s: &str) -> Result<Span, String> {
    let s = s.trim();
    let usage =
        "expected a number and a unit: d (days), w (weeks), m (months), y (years), e.g. 90d or 6m";
    let unit = s.chars().last().ok_or(usage)?;
    let per_unit = match unit.to_ascii_lowercase() {
        'd' => 1,
        'w' => 7,
        'm' => 30,
        'y' => 365,
        _ => return Err(usage.to_string()),
    };
    let n: u32 = s[..s.len() - unit.len_utf8()]
        .parse()
        .map_err(|_| usage.to_string())?;
    if n == 0 {
        return Err("the window must be at least one day".to_string());
    }
    let days = n
        .checked_mul(per_unit)
        .filter(|d| *d <= 100 * 365)
        .ok_or("the window must be at most 100 years")?;
    Ok(Span {
        days,
        label: format!("{}{}", n, unit.to_ascii_lowercase()),
    })
}

/// Change history of one file within the window.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FileHeat {
    pub commits: u32,
    pub added: u64,
    pub deleted: u64,
    /// Committer time of the most recent commit, in Unix seconds.
    pub last_commit: i64,
}

impl FileHeat {
    pub fn churn(&self) -> u64 {
        self.added + self.deleted
    }
}

/// Per-file change history of a target directory.
#[derive(Debug, Clone)]
pub struct HeatMap {
    pub span: Span,
    files: HashMap<PathBuf, FileHeat>,
    /// Commits left out because they touched more than `BULK_COMMIT_FILES` files.
    pub skipped_bulk: usize,
    /// The repository is a shallow clone, so older history may be missing.
    pub shallow: bool,
}

impl HeatMap {
    /// History of the file at `rel_path` (relative to the target), if it
    /// changed within the window.
    pub fn get(&self, rel_path: &Path) -> Option<FileHeat> {
        self.files.get(rel_path).copied()
    }
}

/// Read the change history of `dir` from git.
///
/// Fails when `dir` is not a directory in a git work tree, when git is
/// missing, or when the repository has no commits yet.
pub fn collect(dir: &Path, span: &Span) -> Result<HeatMap, String> {
    if !dir.is_dir() {
        return Err("the target is not a directory".to_string());
    }
    let output = git(dir)
        .args([
            "log",
            "--no-merges",
            "--no-renames",
            "--no-color",
            "--no-textconv",
            "--no-ext-diff",
            "--numstat",
            "-z",
            "--relative",
            "--format=%x01%ct",
        ])
        .arg(format!("--since={}.days.ago", span.days))
        .args(["--", "."])
        .output()
        .map_err(|e| match e.kind() {
            std::io::ErrorKind::NotFound => "git was not found".to_string(),
            _ => format!("could not run git: {}", e),
        })?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let reason = stderr
            .lines()
            .find(|l| !l.trim().is_empty())
            .map(|l| l.trim().trim_start_matches("fatal: ").to_string())
            .unwrap_or_else(|| format!("git log exited with {}", output.status));
        return Err(reason);
    }

    let (files, skipped_bulk) = parse_log(&output.stdout);
    Ok(HeatMap {
        span: span.clone(),
        files,
        skipped_bulk,
        shallow: is_shallow(dir),
    })
}

/// A git command in `dir` that ignores user settings which would change
/// `git log`'s output: signatures printed into it, or `--follow` applied to
/// the single `.` pathspec.
fn git(dir: &Path) -> Command {
    let mut cmd = Command::new("git");
    cmd.arg("-C")
        .arg(dir)
        .args(["-c", "log.showSignature=false", "-c", "log.follow=false"])
        .stdin(Stdio::null());
    cmd
}

fn is_shallow(dir: &Path) -> bool {
    git(dir)
        .args(["rev-parse", "--is-shallow-repository"])
        .output()
        .map(|o| o.status.success() && o.stdout.trim_ascii() == b"true")
        .unwrap_or(false)
}

/// Parse `git log --numstat -z --format=%x01%ct` output.
///
/// The output is a NUL-separated token stream: a commit header `\x01<time>`
/// followed by one `<added>\t<deleted>\t<path>` token per file (the first one
/// prefixed by a newline). Binary files report `-` for both counts. Returns
/// the per-file history and the number of bulk commits skipped.
pub fn parse_log(out: &[u8]) -> (HashMap<PathBuf, FileHeat>, usize) {
    let mut files: HashMap<PathBuf, FileHeat> = HashMap::new();
    let mut skipped_bulk = 0;
    let mut commit: Option<Commit> = None;

    for token in out.split(|b| *b == 0) {
        if let Some(header) = token.strip_prefix(b"\x01") {
            if let Some(done) = commit.take() {
                record_commit(done, &mut files, &mut skipped_bulk);
            }
            let time = std::str::from_utf8(header)
                .ok()
                .and_then(|s| s.trim().parse().ok())
                .unwrap_or(0);
            commit = Some(Commit {
                time,
                entries: Vec::new(),
            });
            continue;
        }
        let token = token.strip_prefix(b"\n").unwrap_or(token);
        if let (Some(commit), Some(entry)) = (commit.as_mut(), parse_numstat(token)) {
            commit.entries.push(entry);
        }
    }
    if let Some(done) = commit {
        record_commit(done, &mut files, &mut skipped_bulk);
    }

    (files, skipped_bulk)
}

/// One commit of the log: its committer time and `(path, added, deleted)` per file.
struct Commit {
    time: i64,
    entries: Vec<(PathBuf, u64, u64)>,
}

fn record_commit(commit: Commit, files: &mut HashMap<PathBuf, FileHeat>, skipped_bulk: &mut usize) {
    if commit.entries.len() > BULK_COMMIT_FILES {
        *skipped_bulk += 1;
        return;
    }
    for (path, added, deleted) in commit.entries {
        if is_noise(&path) {
            continue;
        }
        let heat = files.entry(path).or_default();
        heat.commits += 1;
        heat.added += added;
        heat.deleted += deleted;
        heat.last_commit = heat.last_commit.max(commit.time);
    }
}

fn parse_numstat(token: &[u8]) -> Option<(PathBuf, u64, u64)> {
    let mut parts = token.splitn(3, |b| *b == b'\t');
    let added = parts.next()?;
    let deleted = parts.next()?;
    let path = parts.next().filter(|p| !p.is_empty())?;
    // `-` marks a binary file: it changed, but has no line counts.
    let count = |field: &[u8]| std::str::from_utf8(field).ok()?.parse::<u64>().ok();
    let path = PathBuf::from(std::str::from_utf8(path).ok()?);
    Some((path, count(added).unwrap_or(0), count(deleted).unwrap_or(0)))
}

/// Whether a file's changes are bookkeeping (lockfiles, changelogs) rather
/// than editing.
pub fn is_noise(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    if NOISE_FILE_NAMES.contains(&name) {
        return true;
    }
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase();
    NOISE_STEMS.contains(&stem.as_str())
}

/// Human-friendly age of a commit: `today`, `12d ago`, `3mo ago`, `2y ago`.
pub fn format_age(commit_time: i64, now: i64) -> String {
    let days = (now - commit_time).max(0) / 86_400;
    match days {
        0 => "today".to_string(),
        1..=29 => format!("{}d ago", days),
        30..=364 => format!("{}mo ago", days / 30),
        _ => format!("{}y ago", days / 365),
    }
}

/// Current time in Unix seconds.
pub fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_span_units() {
        assert_eq!(parse_span("90d").unwrap().days, 90);
        assert_eq!(parse_span("2w").unwrap().days, 14);
        assert_eq!(parse_span("6m").unwrap().days, 180);
        assert_eq!(parse_span("1y").unwrap().days, 365);
        assert_eq!(parse_span("3M").unwrap().label, "3m");
        assert_eq!(parse_span(" 30d ").unwrap().label, "30d");
    }

    #[test]
    fn parse_span_rejects_bad_input() {
        for bad in [
            "", "d", "90", "abc", "0d", "-3d", "1.5m", "90x", "101y", "æ—¥",
        ] {
            assert!(parse_span(bad).is_err(), "{:?} should be rejected", bad);
        }
    }

    fn log(commits: &[(i64, &[&str])]) -> Vec<u8> {
        let mut out = Vec::new();
        for (time, entries) in commits {
            out.extend_from_slice(format!("\x01{}\0\n", time).as_bytes());
            // Only the first entry of a commit follows a newline.
            for entry in entries.iter() {
                out.extend_from_slice(entry.as_bytes());
                out.push(0);
            }
        }
        out
    }

    #[test]
    fn parse_log_counts_commits_and_churn() {
        let out = log(&[
            (300, &["5\t2\tsrc/a.rs", "1\t0\tsrc/b.rs"]),
            (200, &["3\t3\tsrc/a.rs"]),
            (100, &["-\t-\tlogo.png"]),
        ]);
        let (files, skipped) = parse_log(&out);
        assert_eq!(skipped, 0);

        let a = files[Path::new("src/a.rs")];
        assert_eq!(
            (a.commits, a.added, a.deleted, a.last_commit),
            (2, 8, 5, 300)
        );
        assert_eq!(files[Path::new("src/b.rs")].commits, 1);

        let logo = files[Path::new("logo.png")];
        assert_eq!((logo.commits, logo.churn()), (1, 0));
    }

    #[test]
    fn parse_log_keeps_tabs_in_paths() {
        let out = log(&[(1, &["1\t1\tweird\tname.txt"])]);
        let (files, _) = parse_log(&out);
        assert!(files.contains_key(Path::new("weird\tname.txt")));
    }

    #[test]
    fn parse_log_skips_bulk_commits() {
        let bulk: Vec<String> = (0..=BULK_COMMIT_FILES)
            .map(|i| format!("1\t1\tf{}.rs", i))
            .collect();
        let bulk: Vec<&str> = bulk.iter().map(|s| s.as_str()).collect();
        let out = log(&[(2, &bulk), (1, &["1\t0\tf0.rs"])]);
        let (files, skipped) = parse_log(&out);
        assert_eq!(skipped, 1);
        assert_eq!(files[Path::new("f0.rs")].commits, 1);
        assert!(!files.contains_key(Path::new("f1.rs")));
    }

    #[test]
    fn parse_log_ignores_noise_files() {
        let out = log(&[(
            1,
            &[
                "1\t1\tCargo.lock",
                "1\t1\tweb/package-lock.json",
                "1\t1\tCHANGELOG.md",
                "1\t1\tsrc/main.rs",
            ],
        )]);
        let (files, _) = parse_log(&out);
        assert_eq!(files.len(), 1);
        assert!(files.contains_key(Path::new("src/main.rs")));
    }

    #[test]
    fn parse_log_handles_empty_output() {
        let (files, skipped) = parse_log(b"");
        assert!(files.is_empty());
        assert_eq!(skipped, 0);
    }

    #[test]
    fn noise_detection() {
        assert!(is_noise(Path::new("Cargo.lock")));
        assert!(is_noise(Path::new("a/b/yarn.lock")));
        assert!(is_noise(Path::new("CHANGELOG.md")));
        assert!(is_noise(Path::new("docs/changes.rst")));
        assert!(!is_noise(Path::new("src/changelog_parser.rs")));
        assert!(!is_noise(Path::new("Cargo.toml")));
    }

    #[test]
    fn age_formatting() {
        let day = 86_400;
        let now = 1_000 * day;
        assert_eq!(format_age(now - 3_600, now), "today");
        assert_eq!(format_age(now - 2 * day, now), "2d ago");
        assert_eq!(format_age(now - 95 * day, now), "3mo ago");
        assert_eq!(format_age(now - 800 * day, now), "2y ago");
        assert_eq!(format_age(now + day, now), "today");
    }
}