gitlimes 0.1.0

Fast, low-memory git history CLI: colored log, branches, author stats and a unicode commit graph
Documentation
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
use crate::cli;
use gitlimes::fmt::{fit, parse_ts, rel_compact, short_email, span_label, sparkline};
use gitlimes::json::Obj;
use gitlimes::pager;
use gitlimes::repo::{self, Records, WHO_FORMAT};
use gitlimes::style::{c, BOLD, CYAN, DIM, GREEN, RESET, YELLOW};
use std::collections::HashMap;
use std::io::{self, Write};

pub const HELP: &str = "\
gitlimes who - author and contribution stats

USAGE:
    gitlimes who [PATH] [OPTIONS]

OPTIONS:
        --since <DATE>   only count commits more recent than DATE
        --limit <N>      show only the top N authors
        --lines          also count added/removed lines (slower)
        --all            include all refs, not just HEAD
        --json           one JSON object per author (newline delimited)
    -h, --help           show this help

The activity sparkline spans the whole history shown, oldest block first.
";

/// The activity sparkline spans the whole history rather than a fixed recent
/// window, so a repository that went quiet years ago still shows its shape
/// instead of twelve blanks.
///
/// The span is not known up front - git yields commits newest first, so the
/// oldest is seen last - and remembering every timestamp to find it would make
/// memory scale with history, which is the one thing this tool does not do.
/// Instead the buckets start one day wide and double whenever a commit falls
/// off the left edge, merging neighbours as they go. That is a fixed
/// `BUCKETS` slots per author, one pass, and it ends up spanning the full
/// history at the coarsest resolution that fits.
const BUCKETS: usize = 12;
const START_WIDTH_SECS: i64 = 86_400;

#[derive(Default)]
struct Author {
    name: String,
    email: String,
    commits: u32,
    first: i64,
    last: i64,
    added: u64,
    removed: u64,
    activity: [u32; BUCKETS],
}

#[derive(Default)]
struct Opts {
    since: Option<String>,
    limit: Option<usize>,
    lines: bool,
    all: bool,
    json: bool,
    paths: Vec<String>,
}

fn parse(args: Vec<String>) -> Result<Option<Opts>, String> {
    let mut o = Opts::default();
    let mut it = args.into_iter();
    let mut after_ddash = false;
    while let Some(a) = it.next() {
        if after_ddash {
            o.paths.push(a);
            continue;
        }
        let (key, inline) = match cli::split_eq(&a) {
            Some((k, v)) if k.starts_with("--") => (k.to_string(), Some(v.to_string())),
            _ => (a.clone(), None),
        };
        let value = |it: &mut std::vec::IntoIter<String>| match inline.clone() {
            Some(v) => Ok(v),
            None => it.next().ok_or_else(|| format!("{} needs a value", key)),
        };
        match key.as_str() {
            "--" => after_ddash = true,
            "-h" | "--help" => {
                print!("{}", HELP);
                return Ok(None);
            }
            "--since" => o.since = Some(value(&mut it)?),
            "--limit" => {
                let v = value(&mut it)?;
                o.limit = Some(
                    v.parse::<usize>()
                        .map_err(|_| format!("--limit expects a number, got '{}'", v))?,
                );
            }
            "--lines" => {
                cli::no_value(&key, &inline)?;
                o.lines = true
            }
            "--all" => {
                cli::no_value(&key, &inline)?;
                o.all = true
            }
            "--json" => {
                cli::no_value(&key, &inline)?;
                o.json = true
            }
            s if s.starts_with('-') => return Err(cli::Unknown(s.to_string()).to_string()),
            s => o.paths.push(s.to_string()),
        }
    }
    Ok(Some(o))
}

pub fn run(args: Vec<String>) -> io::Result<()> {
    let o = match parse(args) {
        Ok(None) => return Ok(()),
        Ok(Some(o)) => o,
        Err(e) => {
            eprintln!("gitlimes: {}", e);
            std::process::exit(2);
        }
    };

    // WHO_FORMAT has no message-body field today, so --encoding=UTF-8 has
    // nothing to do yet; it costs nothing and protects a future field the
    // same way log/graph are protected now.
    let mut argv = repo::log_argv(WHO_FORMAT);
    if let Some(s) = &o.since {
        argv.push(format!("--since={}", s));
    }
    if o.all {
        argv.push("--all".into());
    }
    if o.lines {
        argv.push("--numstat".into());
    }
    argv.push("--".into());
    argv.extend(o.paths.iter().cloned());

    let refs: Vec<&str> = argv.iter().map(String::as_str).collect();
    let mut rec = Records::spawn_lines(repo::git(&refs))?;

    // Bounded by the number of distinct authors, not by history length.
    let mut authors: HashMap<String, Author> = HashMap::new();
    let mut total = 0u32;
    // The newest commit anchors the sparkline; buckets grow to reach the oldest.
    let mut anchor: Option<i64> = None;
    let mut width = START_WIDTH_SECS;
    // With --numstat, a commit's changed-file lines follow its own line as
    // separate records. This is the key of the author they belong to.
    let mut current: Option<String> = None;

    while let Some(line) = rec.next_record()? {
        // A commit's own line has exactly two FS bytes (name, email,
        // timestamp); a --numstat line has none, since a path can no more
        // contain NUL than an ident can. That makes the two unambiguous to
        // tell apart without a reserved delimiter of their own.
        if line.matches(repo::FS).count() != 2 {
            if let Some(key) = current.as_deref() {
                if let Some(e) = authors.get_mut(key) {
                    let (a, r) = sum_numstat(&line);
                    e.added += a;
                    e.removed += r;
                }
            }
            continue;
        }

        let mut f = line.split(repo::FS);
        let (Some(name), Some(email), Some(ts)) = (f.next(), f.next(), f.next()) else {
            current = None;
            continue;
        };
        let ts = parse_ts(ts);

        // Settle the scale before touching any author, so widening - which
        // rewrites every author's buckets - has the map to itself.
        //
        // Author dates do not have to descend the way commit dates do, so a
        // commit newer than the anchor is clamped into the first bucket rather
        // than producing a negative index.
        let anchor = *anchor.get_or_insert(ts);
        let age = (anchor - ts).max(0);
        while age / width >= BUCKETS as i64 {
            for a in authors.values_mut() {
                widen(&mut a.activity);
            }
            width *= 2;
        }
        let bucket = (age / width) as usize;

        let key = email.to_ascii_lowercase();
        let e = authors.entry(key.clone()).or_insert_with(|| Author {
            name: name.to_string(),
            email: email.to_string(),
            first: ts,
            last: ts,
            ..Default::default()
        });
        e.commits += 1;
        total += 1;
        e.first = e.first.min(ts);
        e.last = e.last.max(ts);
        e.activity[bucket.min(BUCKETS - 1)] += 1;
        current = Some(key);
    }
    rec.finish()?;

    if authors.is_empty() {
        eprintln!("gitlimes: no commits");
        return Ok(());
    }

    let mut list: Vec<Author> = authors.into_values().collect();
    list.sort_by(|a, b| b.commits.cmp(&a.commits).then(b.last.cmp(&a.last)));
    if let Some(n) = o.limit {
        list.truncate(n);
    }

    if o.json {
        let mut w = pager::out();
        for a in &list {
            let mut obj = Obj::new();
            obj.str("name", &a.name)
                .str("email", &a.email)
                .num("commits", a.commits as i64)
                .num("first", a.first)
                .num("last", a.last)
                // Oldest bucket first, matching the rendered sparkline.
                .nums("activity", a.activity.iter().rev().map(|v| *v as i64))
                .num("bucket_seconds", width);
            if o.lines {
                obj.num("added", a.added as i64)
                    .num("removed", a.removed as i64);
            }
            writeln!(w, "{}", obj.finish())?;
        }
        return w.finish();
    }

    let name_w = list
        .iter()
        .map(|a| a.name.chars().count())
        .max()
        .unwrap_or(12)
        .clamp(12, 28);
    // --limit 0 leaves this empty, and the guard above ran before truncation.
    // Folded like every other width so there is nothing left to index into.
    let count_w = list
        .iter()
        .map(|a| a.commits.to_string().len())
        .max()
        .unwrap_or(0)
        .max(7);
    // One person often commits under several identities; the email is what
    // actually distinguishes them, so it gets its own column.
    let mail_w = list
        .iter()
        .map(|a| short_email(&a.email).chars().count())
        .max()
        .unwrap_or(10)
        .clamp(10, 24);

    let mut w = pager::out();

    write!(
        w,
        "{}{}  {}  {}  {}  {}  {}{}",
        c(BOLD),
        fit("COMMITS", count_w),
        fit("AUTHOR", name_w),
        fit("EMAIL", mail_w),
        fit("SHARE", 5),
        fit("LAST", 5),
        fit("FIRST", 5),
        c(RESET),
    )?;
    if o.lines {
        write!(w, "  {}  {}", fit("+LINES", 8), fit("-LINES", 8))?;
    }
    // Say what a block is worth: the scale adapts to the history, so leaving
    // it implicit would make two repositories look comparable when they are not.
    writeln!(
        w,
        "  ACTIVITY (oldest to newest, 1 block = {})",
        span_label(width)
    )?;

    for a in &list {
        let share = format!("{:.0}%", (a.commits as f64 / total as f64) * 100.0);
        write!(
            w,
            "{}{}{}  {}{}{}  {}{}{}  {}{}{}  {}  {}  ",
            c(YELLOW),
            fit(&a.commits.to_string(), count_w),
            c(RESET),
            c(CYAN),
            fit(&a.name, name_w),
            c(RESET),
            c(DIM),
            fit(short_email(&a.email), mail_w),
            c(RESET),
            c(DIM),
            fit(&share, 5),
            c(RESET),
            fit(&rel_compact(a.last), 5),
            fit(&rel_compact(a.first), 5),
        )?;
        if o.lines {
            write!(
                w,
                "{}{}{}  {}{}{}  ",
                c(GREEN),
                fit(&format!("+{}", a.added), 8),
                c(RESET),
                c(DIM),
                fit(&format!("-{}", a.removed), 8),
                c(RESET),
            )?;
        }
        // Oldest bucket first so the line reads left-to-right as time passing.
        let mut series = a.activity;
        series.reverse();
        writeln!(w, "{}{}{}", c(GREEN), sparkline(&series), c(RESET))?;
    }
    w.finish()
}

/// Halves the resolution: each pair of neighbouring buckets becomes one, so the
/// same slots now cover twice the time. Counts are preserved, never dropped.
fn widen(activity: &mut [u32; BUCKETS]) {
    let mut merged = [0u32; BUCKETS];
    for i in 0..BUCKETS / 2 {
        merged[i] = activity[2 * i] + activity[2 * i + 1];
    }
    *activity = merged;
}

/// Parses one `--numstat` row: `added<TAB>removed<TAB>path`, with `-` in
/// place of a number for a binary file, which `parse` turns into a no-op 0
/// rather than a hard error - a binary file's line count is meaningless, not
/// a reason to lose the rest of the commit's stats.
fn sum_numstat(line: &str) -> (u64, u64) {
    let mut f = line.split('\t');
    let (Some(a), Some(r)) = (f.next(), f.next()) else {
        return (0, 0);
    };
    (a.parse().unwrap_or(0), r.parse().unwrap_or(0))
}

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

    #[test]
    fn a_commit_line_and_a_numstat_line_are_told_apart_by_fs_count() {
        // The whole scheme rests on this being unambiguous: a commit's own
        // line always has exactly two FS bytes, a --numstat line - author-less,
        // just added\tremoved\tpath - never has any.
        let commit_line = format!("Alice{}a@e.com{}1700000000", repo::FS, repo::FS);
        assert_eq!(commit_line.matches(repo::FS).count(), 2);

        for numstat_line in ["3\t1\tsrc/main.rs", "0\t0\tREADME.md", "-\t-\tbinary.png"] {
            assert_eq!(numstat_line.matches(repo::FS).count(), 0);
        }
    }

    #[test]
    fn sum_numstat_parses_one_row_and_treats_binary_as_zero() {
        assert_eq!(sum_numstat("12\t7\tsrc/lib.rs"), (12, 7));
        assert_eq!(
            sum_numstat("-\t-\tbinary.png"),
            (0, 0),
            "a binary file's '-' must not abort the whole line"
        );
        assert_eq!(sum_numstat(""), (0, 0));
    }

    #[test]
    fn widening_halves_resolution_without_losing_commits() {
        let mut a = [1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        let before: u32 = a.iter().sum();
        widen(&mut a);
        assert_eq!(a[..6], [3, 7, 11, 15, 19, 23], "neighbours merge in pairs");
        assert_eq!(a[6..], [0; 6], "the freed half is cleared");
        assert_eq!(a.iter().sum::<u32>(), before, "no commit is dropped");
    }

    #[test]
    fn repeated_widening_still_conserves_the_total() {
        let mut a = [0u32; BUCKETS];
        a[0] = 5;
        a[BUCKETS - 1] = 7;
        for _ in 0..4 {
            widen(&mut a);
        }
        assert_eq!(a.iter().sum::<u32>(), 12);
        assert_eq!(a[0], 12, "everything collapses into the newest bucket");
    }

    /// The scale must be chosen so the oldest commit lands inside the window.
    #[test]
    fn buckets_widen_until_the_whole_span_fits() {
        let day = 86_400i64;
        for span_days in [1i64, 5, 30, 400, 4_000] {
            let mut width = START_WIDTH_SECS;
            while span_days * day / width >= BUCKETS as i64 {
                width *= 2;
            }
            let bucket = span_days * day / width;
            assert!(
                bucket < BUCKETS as i64,
                "a {}-day span still overflows at width {}",
                span_days,
                width
            );
        }
    }
}