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
//! Reading change history from `git log`.

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

/// A counted commit (inside the window, not a bulk commit).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CommitMeta {
    /// Committer time, in Unix seconds.
    pub time: i64,
    /// Author, as an index into the authors seen (emails are not kept).
    pub author: u32,
}

/// The counted commits that touched one file, and the lines they changed.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FileLog {
    /// Indices into `Log::commits`.
    pub commits: Vec<u32>,
    pub added: u64,
    pub deleted: u64,
}

/// Parsed `git log`: counted commits and, per file, which of them touched it.
/// Files are keyed by their current name: changes made before a rename count
/// toward the renamed file.
#[derive(Debug, Default)]
pub struct Log {
    pub commits: Vec<CommitMeta>,
    pub files: HashMap<PathBuf, FileLog>,
    /// Commits left out because they touched more than `BULK_COMMIT_FILES` files.
    pub skipped_bulk: usize,
    /// Author email → index.
    authors: HashMap<String, u32>,
    /// Former path → current path, for renames seen so far (newer commits).
    renamed: HashMap<PathBuf, PathBuf>,
}

/// Read the change history of `dir` within the last `days` days.
///
/// Fails when `dir` is not a directory in a git work tree, when git is
/// missing, or when the repository has no commits yet. Returns the log and
/// whether the repository is a shallow clone.
pub fn read_log(dir: &Path, days: u32) -> Result<(Log, bool), String> {
    if !dir.is_dir() {
        return Err("the target is not a directory".to_string());
    }
    let output = git(dir)
        .args([
            "log",
            "--no-merges",
            "--find-renames",
            "--no-color",
            "--no-textconv",
            "--no-ext-diff",
            "--numstat",
            "-z",
            "--relative",
            "--format=%x01%ct%x02%aE",
        ])
        .arg(format!("--since={}.days.ago", 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);
    }
    Ok((parse_log(&output.stdout), 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 --find-renames --format=%x01%ct%x02%aE` output.
///
/// The output is a NUL-separated token stream. A commit starts with a header
/// `\x01<time>\x02<author email>`, followed by one `<added>\t<deleted>\t<path>`
/// token per file (the first one prefixed by a newline). A renamed file has
/// an empty path there, and its old and new paths follow as two tokens of
/// their own. Binary files report `-` for both counts.
///
/// git lists the newest commit first, so by the time a commit is recorded
/// every later rename is known, and its files are recorded under their
/// current names.
pub fn parse_log(out: &[u8]) -> Log {
    let mut log = Log::default();
    let mut commit: Option<Commit> = None;
    let mut tokens = out.split(|b| *b == 0);

    while let Some(token) = tokens.next() {
        if let Some(header) = token.strip_prefix(b"\x01") {
            if let Some(done) = commit.take() {
                log.record(done);
            }
            let header = String::from_utf8_lossy(header);
            let (time, author) = header.split_once('\x02').unwrap_or((&header, ""));
            commit = Some(Commit {
                time: time.trim().parse().unwrap_or(0),
                author: author.trim().to_string(),
                entries: Vec::new(),
            });
            continue;
        }
        let Some(commit) = commit.as_mut() else {
            continue;
        };
        let token = token.strip_prefix(b"\n").unwrap_or(token);
        let Some((added, deleted, path)) = parse_numstat(token) else {
            continue;
        };
        let entry = if path.is_empty() {
            let (Some(from), Some(to)) = (tokens.next(), tokens.next()) else {
                break;
            };
            Entry {
                path: to_path(to),
                renamed_from: Some(to_path(from)),
                added,
                deleted,
            }
        } else {
            Entry {
                path: to_path(path),
                renamed_from: None,
                added,
                deleted,
            }
        };
        commit.entries.push(entry);
    }
    if let Some(done) = commit {
        log.record(done);
    }
    log
}

/// One commit of the log.
struct Commit {
    time: i64,
    author: String,
    entries: Vec<Entry>,
}

/// One file changed by a commit.
struct Entry {
    path: PathBuf,
    renamed_from: Option<PathBuf>,
    added: u64,
    deleted: u64,
}

impl Log {
    fn record(&mut self, commit: Commit) {
        // Name every file as it is called today, then note this commit's
        // renames for the older commits still to come. Doing it in that
        // order keeps a file created under a name another file was renamed
        // away from in the same commit apart from it.
        let current: Vec<PathBuf> = commit
            .entries
            .iter()
            .map(|e| self.renamed.get(&e.path).unwrap_or(&e.path).clone())
            .collect();
        for (entry, name) in commit.entries.iter().zip(&current) {
            if let Some(from) = &entry.renamed_from {
                self.renamed.insert(from.clone(), name.clone());
            }
        }

        // A bulk commit is not counted, but its renames (a moved directory)
        // still carry the older history over.
        if commit.entries.len() > BULK_COMMIT_FILES {
            self.skipped_bulk += 1;
            return;
        }
        let entries: Vec<(PathBuf, &Entry)> = current
            .into_iter()
            .zip(&commit.entries)
            .filter(|(name, _)| !is_noise(name))
            .collect();
        if entries.is_empty() {
            return;
        }

        let next_author = self.authors.len() as u32;
        let author = *self
            .authors
            .entry(commit.author.clone())
            .or_insert(next_author);
        let id = self.commits.len() as u32;
        self.commits.push(CommitMeta {
            time: commit.time,
            author,
        });
        for (name, entry) in entries {
            let file = self.files.entry(name).or_default();
            // A path listed twice in one commit still counts the commit once.
            if file.commits.last() != Some(&id) {
                file.commits.push(id);
            }
            file.added += entry.added;
            file.deleted += entry.deleted;
        }
    }
}

/// Split a numstat token into its counts and path (empty for a rename).
fn parse_numstat(token: &[u8]) -> Option<(u64, u64, &[u8])> {
    let mut parts = token.splitn(3, |b| *b == b'\t');
    let added = parts.next()?;
    let deleted = parts.next()?;
    let path = parts.next()?;
    // `-` marks a binary file: it changed, but has no line counts.
    let count = |field: &[u8]| {
        std::str::from_utf8(field)
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .unwrap_or(0)
    };
    Some((count(added), count(deleted), path))
}

fn to_path(bytes: &[u8]) -> PathBuf {
    PathBuf::from(String::from_utf8_lossy(bytes).into_owned())
}

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

    /// Build `git log` output: per commit, its time and numstat entries, all
    /// by one author. A rename entry is written `"<a>\t<d>\t\0<old>\0<new>"`.
    pub fn log_bytes(commits: &[(i64, &[&str])]) -> Vec<u8> {
        let commits: Vec<_> = commits
            .iter()
            .map(|(time, entries)| (*time, "dev@example.com", *entries))
            .collect();
        log_bytes_by(&commits)
    }

    /// Like `log_bytes`, with each commit's author email.
    pub fn log_bytes_by(commits: &[(i64, &str, &[&str])]) -> Vec<u8> {
        let mut out = Vec::new();
        for (time, author, entries) in commits {
            out.extend_from_slice(format!("\x01{}\x02{}\0\n", time, author).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
    }

    fn file<'a>(log: &'a Log, path: &str) -> &'a FileLog {
        &log.files[Path::new(path)]
    }

    #[test]
    fn parse_log_records_commits_per_file() {
        let log = parse_log(&log_bytes(&[
            (300, &["5\t2\tsrc/a.rs", "1\t0\tsrc/b.rs"]),
            (200, &["3\t3\tsrc/a.rs"]),
            (100, &["-\t-\tlogo.png"]),
        ]));
        assert_eq!(log.skipped_bulk, 0);
        assert_eq!(
            log.commits.iter().map(|c| c.time).collect::<Vec<_>>(),
            [300, 200, 100]
        );

        let a = file(&log, "src/a.rs");
        assert_eq!(
            (a.commits.as_slice(), a.added, a.deleted),
            (&[0, 1][..], 8, 5)
        );
        assert_eq!(file(&log, "src/b.rs").commits, [0]);
        let logo = file(&log, "logo.png");
        assert_eq!((logo.commits.as_slice(), logo.added), (&[2][..], 0));
    }

    #[test]
    fn parse_log_keeps_tabs_in_paths() {
        let log = parse_log(&log_bytes(&[(1, &["1\t1\tweird\tname.txt"])]));
        assert!(log.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 log = parse_log(&log_bytes(&[(2, &bulk), (1, &["1\t0\tf0.rs"])]));
        assert_eq!(log.skipped_bulk, 1);
        assert_eq!(log.commits.len(), 1);
        assert_eq!(file(&log, "f0.rs").commits, [0]);
        assert!(!log.files.contains_key(Path::new("f1.rs")));
    }

    #[test]
    fn parse_log_ignores_noise_files() {
        let log = parse_log(&log_bytes(&[
            (
                2,
                &[
                    "1\t1\tCargo.lock",
                    "1\t1\tweb/package-lock.json",
                    "1\t1\tCHANGELOG.md",
                    "1\t1\tsrc/main.rs",
                ],
            ),
            // A commit that only touched noise files is not counted at all.
            (1, &["1\t1\tCargo.lock"]),
        ]));
        assert_eq!(log.files.len(), 1);
        assert!(log.files.contains_key(Path::new("src/main.rs")));
        assert_eq!(log.commits.len(), 1);
    }

    #[test]
    fn parse_log_carries_history_over_renames() {
        let log = parse_log(&log_bytes(&[
            (4, &["1\t0\tsrc/c.rs"]),
            (3, &["0\t0\t\0src/b.rs\0src/c.rs"]),
            (2, &["2\t1\t\0src/a.rs\0src/b.rs"]),
            (1, &["5\t0\tsrc/a.rs"]),
        ]));
        let c = file(&log, "src/c.rs");
        assert_eq!(
            (c.commits.as_slice(), c.added, c.deleted),
            (&[0, 1, 2, 3][..], 8, 1)
        );
        assert_eq!(log.files.len(), 1);
    }

    #[test]
    fn parse_log_keeps_a_new_file_apart_from_the_one_renamed_away() {
        // One commit renames a.rs to b.rs and creates a new a.rs.
        let log = parse_log(&log_bytes(&[
            (2, &["0\t0\t\0a.rs\0b.rs", "1\t0\ta.rs"]),
            (1, &["3\t0\ta.rs"]),
        ]));
        assert_eq!(file(&log, "a.rs").commits, [0]);
        assert_eq!(file(&log, "b.rs").commits, [0, 1]);
    }

    #[test]
    fn parse_log_follows_renames_in_skipped_bulk_commits() {
        let moves: Vec<String> = (0..=BULK_COMMIT_FILES)
            .map(|i| format!("0\t0\t\0old/f{}.rs\0new/f{}.rs", i, i))
            .collect();
        let moves: Vec<&str> = moves.iter().map(|s| s.as_str()).collect();
        let log = parse_log(&log_bytes(&[(2, &moves), (1, &["4\t0\told/f0.rs"])]));
        assert_eq!(log.skipped_bulk, 1);
        assert_eq!(file(&log, "new/f0.rs").commits, [0]);
        assert!(!log.files.contains_key(Path::new("old/f0.rs")));
    }

    #[test]
    fn parse_log_numbers_authors() {
        let log = parse_log(&log_bytes_by(&[
            (3, "a@x", &["1\t0\tf.rs"]),
            (2, "b@x", &["1\t0\tf.rs"]),
            (1, "a@x", &["1\t0\tf.rs"]),
        ]));
        let authors: Vec<u32> = log.commits.iter().map(|c| c.author).collect();
        assert_eq!(authors, [0, 1, 0]);
    }

    #[test]
    fn parse_log_handles_empty_output() {
        let log = parse_log(b"");
        assert!(log.files.is_empty());
        assert!(log.commits.is_empty());
    }
}