tokmd-context-git 1.8.0

Git-derived hotspot and churn scoring for context ranking.
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
//! BDD-style scenario tests for git-based context selection.
//!
//! Each test follows the Given-When-Then naming convention to document
//! expected behaviour of `compute_git_scores`.

#[cfg(feature = "git")]
mod with_git {
    use std::process::Command;
    use tokmd_context_git::{GitScores, compute_git_scores};
    use tokmd_types::{FileKind, FileRow};

    // ── helpers ─────────────────────────────────────────────────────

    fn make_row(path: &str, lines: usize) -> FileRow {
        FileRow {
            path: path.to_string(),
            module: "(root)".to_string(),
            lang: "Rust".to_string(),
            kind: FileKind::Parent,
            code: lines,
            comments: 0,
            blanks: 0,
            lines,
            bytes: lines * 10,
            tokens: lines * 5,
        }
    }

    fn make_child_row(path: &str, lines: usize) -> FileRow {
        FileRow {
            path: path.to_string(),
            module: "(root)".to_string(),
            lang: "Rust".to_string(),
            kind: FileKind::Child,
            code: lines,
            comments: 0,
            blanks: 0,
            lines,
            bytes: lines * 10,
            tokens: lines * 5,
        }
    }

    fn git(root: &std::path::Path, args: &[&str]) -> Option<()> {
        let out = Command::new("git")
            .args(args)
            .current_dir(root)
            .output()
            .ok()?;
        if out.status.success() { Some(()) } else { None }
    }

    /// Create a repo with:
    ///   main.rs  – 2 commits, 4 final lines
    ///   lib.rs   – 1 commit, 5 lines
    ///   util.rs  – 1 commit, 2 lines (committed alongside lib.rs)
    fn create_test_repo() -> Option<tempfile::TempDir> {
        let dir = tempfile::tempdir().ok()?;
        let root = dir.path();

        git(root, &["init"])?;
        git(root, &["config", "user.email", "test@test.com"])?;
        git(root, &["config", "user.name", "Test"])?;

        // Commit 1: main.rs (3 lines)
        std::fs::write(root.join("main.rs"), "1\n2\n3").ok()?;
        git(root, &["add", "."])?;
        git(root, &["commit", "-m", "c1"])?;

        // Commit 2: main.rs grows to 4 lines
        std::fs::write(root.join("main.rs"), "1\n2\n3\n4").ok()?;
        git(root, &["add", "."])?;
        git(root, &["commit", "-m", "c2"])?;

        // Commit 3: lib.rs (5 lines) + util.rs (2 lines)
        std::fs::write(root.join("lib.rs"), "1\n2\n3\n4\n5").ok()?;
        std::fs::write(root.join("util.rs"), "1\n2").ok()?;
        git(root, &["add", "."])?;
        git(root, &["commit", "-m", "c3"])?;

        Some(dir)
    }

    /// Create an empty repo (git init, but no commits)
    fn create_empty_repo() -> Option<tempfile::TempDir> {
        let dir = tempfile::tempdir().ok()?;
        let root = dir.path();
        git(root, &["init"])?;
        git(root, &["config", "user.email", "test@test.com"])?;
        git(root, &["config", "user.name", "Test"])?;
        Some(dir)
    }

    // ── scenario: recently changed files are prioritised ────────────

    #[test]
    fn given_files_with_git_history_when_context_is_selected_then_recently_changed_files_are_prioritised()
     {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![
            make_row("main.rs", 4),
            make_row("lib.rs", 5),
            make_row("util.rs", 2),
        ];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        // main.rs has 2 commits → hotspot = 4 × 2 = 8
        // lib.rs has 1 commit  → hotspot = 5 × 1 = 5
        // util.rs has 1 commit → hotspot = 2 × 1 = 2
        // Most-changed file (main.rs) gets highest hotspot score.
        let main_hotspot = scores.hotspots["main.rs"];
        let lib_hotspot = scores.hotspots["lib.rs"];
        let util_hotspot = scores.hotspots["util.rs"];
        assert!(
            main_hotspot > lib_hotspot,
            "main.rs ({main_hotspot}) should rank above lib.rs ({lib_hotspot})"
        );
        assert!(
            lib_hotspot > util_hotspot,
            "lib.rs ({lib_hotspot}) should rank above util.rs ({util_hotspot})"
        );
    }

    // ── scenario: commit counts are accurate ────────────────────────

    #[test]
    fn given_files_with_varying_commits_when_scores_computed_then_commit_counts_are_correct() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![
            make_row("main.rs", 4),
            make_row("lib.rs", 5),
            make_row("util.rs", 2),
        ];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        assert_eq!(scores.commit_counts["main.rs"], 2);
        assert_eq!(scores.commit_counts["lib.rs"], 1);
        assert_eq!(scores.commit_counts["util.rs"], 1);
    }

    // ── scenario: hotspot = lines × commits ─────────────────────────

    #[test]
    fn given_known_line_counts_when_scores_computed_then_hotspot_equals_lines_times_commits() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![
            make_row("main.rs", 4),
            make_row("lib.rs", 5),
            make_row("util.rs", 2),
        ];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        assert_eq!(scores.hotspots["main.rs"], 4 * 2);
        assert_eq!(scores.hotspots["lib.rs"], 5);
        assert_eq!(scores.hotspots["util.rs"], 2);
    }

    // ── scenario: child rows are excluded ───────────────────────────

    #[test]
    fn given_child_file_rows_when_scores_computed_then_children_are_excluded() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![
            make_child_row("main.rs", 4), // Child – should be filtered
            make_row("lib.rs", 5),        // Parent – should be included
        ];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        assert!(
            !scores.commit_counts.contains_key("main.rs"),
            "child row should be excluded from commit_counts"
        );
        assert!(
            !scores.hotspots.contains_key("main.rs"),
            "child row should be excluded from hotspots"
        );
        assert!(scores.commit_counts.contains_key("lib.rs"));
    }

    // ── scenario: files not tracked by git are absent ───────────────

    #[test]
    fn given_file_not_in_git_when_scores_computed_then_file_is_absent_from_results() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        // "nonexistent.rs" was never committed
        let rows = vec![make_row("nonexistent.rs", 10)];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        assert!(
            !scores.commit_counts.contains_key("nonexistent.rs"),
            "untracked file should not appear in commit_counts"
        );
        assert!(scores.hotspots.is_empty());
    }

    // ── scenario: non-repo directory returns None ───────────────────

    #[test]
    fn given_non_git_directory_when_scores_computed_then_none_is_returned() {
        let dir = tempfile::tempdir().unwrap();
        let rows = vec![make_row("foo.rs", 10)];
        assert!(compute_git_scores(dir.path(), &rows, 100, 100).is_none());
    }

    // ── scenario: empty commit history ──────────────────────────────

    #[test]
    fn given_empty_commit_history_when_scores_computed_then_empty_maps_returned() {
        let repo = match create_empty_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![make_row("foo.rs", 10)];

        // An empty repo (no commits) may return None or Some with empty maps
        // depending on git log behaviour. Either is acceptable.
        match compute_git_scores(repo.path(), &rows, 100, 100) {
            None => {} // acceptable – git log fails on empty repo
            Some(scores) => {
                assert!(scores.commit_counts.is_empty());
                assert!(scores.hotspots.is_empty());
            }
        }
    }

    // ── scenario: empty rows list ───────────────────────────────────

    #[test]
    fn given_empty_file_rows_when_scores_computed_then_empty_maps_returned() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows: Vec<FileRow> = vec![];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        assert!(scores.commit_counts.is_empty());
        assert!(scores.hotspots.is_empty());
    }

    // ── scenario: max_commits limits history depth ──────────────────

    #[test]
    fn given_max_commits_of_two_when_scores_computed_then_older_commits_excluded() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![
            make_row("main.rs", 4),
            make_row("lib.rs", 5),
            make_row("util.rs", 2),
        ];

        // With max_commits=2, only c3 and c2 should be considered
        let scores = match compute_git_scores(repo.path(), &rows, 2, 100) {
            Some(s) => s,
            None => return, // git history collection may not support limit
        };

        // main.rs appears in c2 (1 commit in window), not in c1 (truncated)
        let main_count = scores.commit_counts.get("main.rs").copied().unwrap_or(0);
        assert!(
            main_count <= 2,
            "main.rs should have at most 2 commits in window, got {main_count}"
        );
        // lib.rs and util.rs appear in c3 (within window)
        assert!(scores.commit_counts.contains_key("lib.rs"));
        assert!(scores.commit_counts.contains_key("util.rs"));
    }

    // ── scenario: hotspot map is subset of commit_counts ────────────

    #[test]
    fn given_any_repo_when_scores_computed_then_hotspot_keys_are_subset_of_commit_count_keys() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        let rows = vec![
            make_row("main.rs", 4),
            make_row("lib.rs", 5),
            make_row("util.rs", 2),
        ];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        for key in scores.hotspots.keys() {
            assert!(
                scores.commit_counts.contains_key(key),
                "hotspot key {key:?} must also appear in commit_counts"
            );
        }
    }

    // ── scenario: files with zero lines produce zero hotspot ────────

    #[test]
    fn given_file_with_zero_lines_when_scores_computed_then_hotspot_is_zero() {
        let repo = match create_test_repo() {
            Some(r) => r,
            None => return,
        };
        // main.rs exists in git but we report 0 lines
        let rows = vec![make_row("main.rs", 0)];

        let Some(scores) = compute_git_scores(repo.path(), &rows, 100, 100) else {
            return;
        };

        assert_eq!(
            scores.hotspots.get("main.rs"),
            Some(&0),
            "0 lines × any commits = 0"
        );
    }

    // ── scenario: GitScores struct fields are accessible ────────────

    #[test]
    fn given_git_scores_struct_when_accessed_then_both_fields_are_btreemaps() {
        let scores = GitScores {
            hotspots: Default::default(),
            commit_counts: Default::default(),
        };
        // Ensure the struct is constructible and fields are BTreeMaps
        assert!(scores.hotspots.is_empty());
        assert!(scores.commit_counts.is_empty());
    }

    // ── scenario: subdirectory paths normalised correctly ────────────

    #[test]
    fn given_file_in_subdirectory_when_scores_computed_then_path_normalised() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();

        // Set up repo with a subdirectory file
        if git(root, &["init"]).is_none() {
            return;
        }
        if git(root, &["config", "user.email", "test@test.com"]).is_none() {
            return;
        }
        if git(root, &["config", "user.name", "Test"]).is_none() {
            return;
        }

        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src").join("main.rs"), "fn main() {}").unwrap();
        if git(root, &["add", "."]).is_none() {
            return;
        }
        if git(root, &["commit", "-m", "init"]).is_none() {
            return;
        }

        let rows = vec![make_row("src/main.rs", 1)];

        let Some(scores) = compute_git_scores(root, &rows, 100, 100) else {
            return;
        };

        assert!(
            scores.commit_counts.contains_key("src/main.rs"),
            "normalised forward-slash path should match"
        );
    }
}

// ── scenario: without git feature ───────────────────────────────

#[cfg(not(feature = "git"))]
mod without_git {
    use tokmd_context_git::compute_git_scores;

    #[test]
    fn given_no_git_feature_when_compute_called_then_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let rows = vec![];
        assert!(compute_git_scores(dir.path(), &rows, 100, 100).is_none());
    }
}