kodo 0.6.2

A CLI tool for analyzing Git commit statistics with TUI visualization
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
//! Statistics collection from commits

#![allow(clippy::cast_possible_truncation)]

use crate::cli::args::Period;
use crate::git::CommitInfo;
use crate::stats::timezone::TimeZoneMode;
use crate::stats::types::{ActivityStats, AnalysisResult, DateRange, PeriodStats};
use chrono::{Datelike, NaiveDate, Timelike};
use std::collections::HashMap;

/// Collect statistics from a list of commits
///
/// Groups commits by the specified period and calculates aggregate statistics.
/// Days with no commits are included with zero values.
#[must_use]
pub fn collect_stats(
    repo_name: &str,
    commits: Vec<CommitInfo>,
    range: DateRange,
    period: Period,
    extensions: Option<&[String]>,
    timezone: &TimeZoneMode,
) -> AnalysisResult {
    // Group commits by date
    let mut daily_stats: HashMap<NaiveDate, PeriodStats> = HashMap::new();

    for commit in commits {
        let date = timezone.date_naive(commit.timestamp);

        // Filter by extensions if specified
        let (additions, deletions, files_changed) = if let Some(exts) = extensions {
            let filtered: Vec<_> = commit
                .diff
                .files
                .iter()
                .filter(|f| f.matches_extensions(exts))
                .collect();

            (
                filtered.iter().map(|f| f.additions).sum(),
                filtered.iter().map(|f| f.deletions).sum(),
                filtered.len() as u32,
            )
        } else {
            (
                commit.diff.additions,
                commit.diff.deletions,
                commit.diff.files_changed,
            )
        };

        let entry = daily_stats
            .entry(date)
            .or_insert_with(|| PeriodStats::new(date));
        entry.commits += 1;
        entry.additions += additions;
        entry.deletions += deletions;
        entry.files_changed += files_changed;
        entry.update_net_lines();
    }

    // Fill in missing days with zero stats
    for date in range.iter_days() {
        daily_stats
            .entry(date)
            .or_insert_with(|| PeriodStats::new(date));
    }

    // Convert to sorted vector
    let mut stats: Vec<_> = daily_stats.into_values().collect();
    stats.sort_by_key(|s| s.date);

    // Apply period aggregation if not daily
    let stats = match period {
        Period::Daily => stats,
        Period::Weekly => aggregate_by_week(stats),
        Period::Monthly => aggregate_by_month(stats),
        Period::Yearly => aggregate_by_year(stats),
    };

    AnalysisResult::new(
        repo_name.to_string(),
        period.to_string(),
        range.from,
        range.to,
        stats,
    )
}

/// Aggregate daily stats by ISO week
fn aggregate_by_week(daily_stats: Vec<PeriodStats>) -> Vec<PeriodStats> {
    let mut weekly: HashMap<(i32, u32), PeriodStats> = HashMap::new();

    for stat in daily_stats {
        let week = stat.date.iso_week();
        let key = (week.year(), week.week());

        let entry = weekly.entry(key).or_insert_with(|| {
            PeriodStats::with_label(stat.date, format!("{}-W{:02}", week.year(), week.week()))
        });
        entry.merge(&stat);
    }

    let mut result: Vec<_> = weekly.into_values().collect();
    result.sort_by_key(|s| s.date);
    result
}

/// Aggregate daily stats by month
fn aggregate_by_month(daily_stats: Vec<PeriodStats>) -> Vec<PeriodStats> {
    let mut monthly: HashMap<(i32, u32), PeriodStats> = HashMap::new();

    for stat in daily_stats {
        let key = (stat.date.year(), stat.date.month());

        let entry = monthly.entry(key).or_insert_with(|| {
            PeriodStats::with_label(
                stat.date,
                format!("{}-{:02}", stat.date.year(), stat.date.month()),
            )
        });
        entry.merge(&stat);
    }

    let mut result: Vec<_> = monthly.into_values().collect();
    result.sort_by_key(|s| s.date);
    result
}

/// Aggregate daily stats by year
fn aggregate_by_year(daily_stats: Vec<PeriodStats>) -> Vec<PeriodStats> {
    let mut yearly: HashMap<i32, PeriodStats> = HashMap::new();

    for stat in daily_stats {
        let year = stat.date.year();

        let entry = yearly
            .entry(year)
            .or_insert_with(|| PeriodStats::with_label(stat.date, year.to_string()));
        entry.merge(&stat);
    }

    let mut result: Vec<_> = yearly.into_values().collect();
    result.sort_by_key(|s| s.date);
    result
}

/// Collect activity statistics (commits by weekday and hour) from commits
///
/// Groups commits by weekday (Mon-Sun) and hour (0-23) based on the selected timezone.
#[must_use]
pub fn collect_activity_stats(commits: &[CommitInfo], timezone: &TimeZoneMode) -> ActivityStats {
    let mut stats = ActivityStats::default();

    for commit in commits {
        let local_time = timezone.datetime(commit.timestamp);

        // chrono::Weekday: Mon=0, Tue=1, ..., Sun=6
        let weekday_index = local_time.weekday().num_days_from_monday() as usize;
        let hour_index = local_time.hour() as usize;

        stats.weekday[weekday_index] += 1;
        stats.hourly[hour_index] += 1;
    }

    stats
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::stats::timezone::TimeZoneMode;
    use crate::git::{DiffStats, FileChange};
    use chrono::{TimeZone, Utc};

    fn make_commit(date: NaiveDate, additions: u64, deletions: u64) -> CommitInfo {
        let timestamp = Utc.from_utc_datetime(&date.and_hms_opt(12, 0, 0).unwrap());
        CommitInfo {
            id: "abc1234".to_string(),
            timestamp,
            is_merge: false,
            diff: DiffStats::new(additions, deletions, 1),
        }
    }

    #[test]
    fn test_collect_stats_empty() {
        let range = DateRange::new(
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 1, 3).unwrap(),
        );

        let result = collect_stats("test", vec![], range, Period::Daily, None, &TimeZoneMode::Local);

        assert_eq!(result.repository, "test");
        assert_eq!(result.stats.len(), 3); // 3 days with zeros
        assert_eq!(result.total.commits, 0);
    }

    #[test]
    fn test_collect_stats_with_commits() {
        let date1 = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let date2 = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();

        let commits = vec![
            make_commit(date1, 100, 10),
            make_commit(date1, 50, 5),
            make_commit(date2, 30, 3),
        ];

        let range = DateRange::new(date1, date2);
        let result = collect_stats("test", commits, range, Period::Daily, None, &TimeZoneMode::Local);

        assert_eq!(result.stats.len(), 2);
        assert_eq!(result.total.commits, 3);
        assert_eq!(result.total.additions, 180);
        assert_eq!(result.total.deletions, 18);
    }

    #[test]
    fn test_collect_stats_with_extension_filter() {
        let date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let timestamp = Utc.from_utc_datetime(&date.and_hms_opt(12, 0, 0).unwrap());

        let mut diff = DiffStats::default();
        diff.add_file(FileChange::new("src/main.rs".to_string(), 100, 10));
        diff.add_file(FileChange::new("src/lib.ts".to_string(), 50, 5));
        diff.add_file(FileChange::new("README.md".to_string(), 20, 2));

        let commit = CommitInfo {
            id: "abc1234".to_string(),
            timestamp,
            is_merge: false,
            diff,
        };

        let range = DateRange::new(date, date);
        let extensions = vec!["rs".to_string()];
        let result = collect_stats(
            "test",
            vec![commit],
            range,
            Period::Daily,
            Some(&extensions),
            &TimeZoneMode::Local,
        );

        // Only .rs file should be counted
        assert_eq!(result.total.additions, 100);
        assert_eq!(result.total.deletions, 10);
        assert_eq!(result.total.files_changed, 1);
    }

    #[test]
    fn test_aggregate_by_week() {
        // Create stats for two weeks
        let week1_day1 = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(); // Monday
        let week1_day2 = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
        let week2_day1 = NaiveDate::from_ymd_opt(2024, 1, 8).unwrap(); // Next Monday

        let daily = vec![
            PeriodStats {
                date: week1_day1,
                commits: 2,
                additions: 100,
                deletions: 10,
                ..Default::default()
            },
            PeriodStats {
                date: week1_day2,
                commits: 3,
                additions: 50,
                deletions: 5,
                ..Default::default()
            },
            PeriodStats {
                date: week2_day1,
                commits: 1,
                additions: 20,
                deletions: 2,
                ..Default::default()
            },
        ];

        let weekly = aggregate_by_week(daily);

        assert_eq!(weekly.len(), 2);
        // First week: 2 + 3 commits
        assert_eq!(weekly[0].commits, 5);
        // Second week: 1 commit
        assert_eq!(weekly[1].commits, 1);
    }

    #[test]
    fn test_aggregate_by_month() {
        let jan = NaiveDate::from_ymd_opt(2024, 1, 15).unwrap();
        let feb = NaiveDate::from_ymd_opt(2024, 2, 15).unwrap();

        let daily = vec![
            PeriodStats {
                date: jan,
                commits: 5,
                additions: 100,
                ..Default::default()
            },
            PeriodStats {
                date: feb,
                commits: 3,
                additions: 50,
                ..Default::default()
            },
        ];

        let monthly = aggregate_by_month(daily);

        assert_eq!(monthly.len(), 2);
        assert!(monthly[0].label.contains("2024-01"));
        assert!(monthly[1].label.contains("2024-02"));
    }

    #[test]
    fn test_collect_activity_stats_empty() {
        let commits: Vec<CommitInfo> = vec![];
        let stats = collect_activity_stats(&commits, &TimeZoneMode::Local);

        assert_eq!(stats.weekday, [0; 7]);
        assert_eq!(stats.hourly, [0; 24]);
    }

    #[test]
    fn test_collect_activity_stats_single_commit() {
        // Create a commit with a known UTC timestamp
        let date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let timestamp = Utc.from_utc_datetime(&date.and_hms_opt(10, 30, 0).unwrap());
        let commit = CommitInfo {
            id: "abc1234".to_string(),
            timestamp,
            is_merge: false,
            diff: DiffStats::default(),
        };

        let stats = collect_activity_stats(&[commit], &TimeZoneMode::Local);

        // Verify exactly one commit is counted across all weekdays and hours
        let total_weekday: u32 = stats.weekday.iter().sum();
        let total_hourly: u32 = stats.hourly.iter().sum();
        assert_eq!(total_weekday, 1);
        assert_eq!(total_hourly, 1);

        // The specific weekday/hour depends on local timezone, but exactly one slot should have 1
        assert_eq!(stats.weekday.iter().filter(|&&x| x == 1).count(), 1);
        assert_eq!(stats.hourly.iter().filter(|&&x| x == 1).count(), 1);
    }

    #[test]
    fn test_collect_activity_stats_multiple_commits() {
        let commits: Vec<CommitInfo> = vec![
            // Two commits at the same UTC hour
            {
                let date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
                let timestamp = Utc.from_utc_datetime(&date.and_hms_opt(10, 0, 0).unwrap());
                CommitInfo {
                    id: "a".to_string(),
                    timestamp,
                    is_merge: false,
                    diff: DiffStats::default(),
                }
            },
            {
                let date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
                let timestamp = Utc.from_utc_datetime(&date.and_hms_opt(10, 30, 0).unwrap());
                CommitInfo {
                    id: "b".to_string(),
                    timestamp,
                    is_merge: false,
                    diff: DiffStats::default(),
                }
            },
            // Another commit at a different time
            {
                let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
                let timestamp = Utc.from_utc_datetime(&date.and_hms_opt(14, 0, 0).unwrap());
                CommitInfo {
                    id: "c".to_string(),
                    timestamp,
                    is_merge: false,
                    diff: DiffStats::default(),
                }
            },
            // Late night commit
            {
                let date = NaiveDate::from_ymd_opt(2024, 1, 7).unwrap();
                let timestamp = Utc.from_utc_datetime(&date.and_hms_opt(23, 59, 0).unwrap());
                CommitInfo {
                    id: "d".to_string(),
                    timestamp,
                    is_merge: false,
                    diff: DiffStats::default(),
                }
            },
        ];

        let stats = collect_activity_stats(&commits, &TimeZoneMode::Local);

        // Verify total commits are counted correctly
        let total_weekday: u32 = stats.weekday.iter().sum();
        let total_hourly: u32 = stats.hourly.iter().sum();
        assert_eq!(total_weekday, 4);
        assert_eq!(total_hourly, 4);

        // Verify that the two commits at the same hour are grouped together
        // (regardless of timezone, they should be in the same local hour)
        assert!(stats.hourly.contains(&2));
    }
}