kimun 0.31.2

Code metrics tool — health score, complexity, duplication, hotspots, ownership
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use super::*;
use std::fs;

use git2::Repository;

fn create_test_repo() -> (tempfile::TempDir, Repository) {
    let dir = tempfile::tempdir().unwrap();
    let repo = Repository::init(dir.path()).unwrap();
    let mut config = repo.config().unwrap();
    config.set_str("user.name", "Test").unwrap();
    config.set_str("user.email", "test@test.com").unwrap();
    (dir, repo)
}

/// Commit `files` as written and `removed` as deletions; returns the commit id.
fn commit(repo: &Repository, files: &[(&str, &str)], removed: &[&str]) -> String {
    let sig =
        git2::Signature::new("Test", "test@test.com", &git2::Time::new(1_700_000_000, 0)).unwrap();
    let workdir = repo.workdir().unwrap();
    let mut index = repo.index().unwrap();
    for (path, content) in files {
        let full = workdir.join(path);
        fs::create_dir_all(full.parent().unwrap()).unwrap();
        fs::write(full, content).unwrap();
        index.add_path(Path::new(path)).unwrap();
    }
    for path in removed {
        fs::remove_file(workdir.join(path)).unwrap();
        index.remove_path(Path::new(path)).unwrap();
    }
    index.write().unwrap();
    let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
    let parent = repo.head().ok().and_then(|h| h.peel_to_commit().ok());
    let parents: Vec<&git2::Commit> = parent.iter().collect();
    repo.commit(Some("HEAD"), &sig, &sig, "commit", &tree, &parents)
        .unwrap()
        .to_string()
}

fn refs(since: &str, until: Option<&str>) -> DiffSource {
    DiffSource::Refs {
        since: since.to_string(),
        until: until.map(str::to_string),
    }
}

fn paths(change: &Change) -> Vec<&str> {
    let mut paths: Vec<&str> = change
        .diff
        .iter()
        .map(|c| c.path.to_str().unwrap())
        .collect();
    paths.sort();
    paths
}

fn roots(graph: &ProjectGraph) -> Vec<String> {
    let mut roots: Vec<String> = graph.projects.iter().map(|p| p.display_root()).collect();
    roots.sort();
    roots
}

const PATCH: &str = "\
diff --git a/src/a.rs b/src/a.rs
index 1111111..2222222 100644
--- a/src/a.rs
+++ b/src/a.rs
@@ -1,2 +1,3 @@
 one
-two
+TWO
+three
diff --git a/new.rs b/new.rs
new file mode 100644
index 0000000..3333333
--- /dev/null
+++ b/new.rs
@@ -0,0 +1,2 @@
+x
+y
";

#[test]
fn against_a_ref_measures_up_to_the_working_tree() {
    let (dir, repo) = create_test_repo();
    commit(
        &repo,
        &[
            ("a.rs", "a\n"),
            ("Cargo.toml", "[package]\nname = \"app\"\n"),
        ],
        &[],
    );
    fs::write(dir.path().join("a.rs"), "changed\n").unwrap();
    fs::write(dir.path().join("untracked.rs"), "new\n").unwrap();
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let change = Change::resolve(&git_repo, &refs("HEAD", None)).unwrap();

    assert_eq!(change.label, "diff against HEAD");
    assert_eq!(paths(&change), ["a.rs", "untracked.rs"]);
    assert!(change.has_file(&git_repo, Path::new("untracked.rs")));
    assert_eq!(roots(&change.graph(&git_repo).unwrap()), ["."]);
}

#[test]
fn between_two_refs_ignores_what_is_checked_out() {
    let (dir, repo) = create_test_repo();
    let base = commit(&repo, &[("a.rs", "a\n"), ("old.rs", "old\n")], &[]);
    let feature = commit(
        &repo,
        &[
            ("a.rs", "feature\n"),
            ("lib/Cargo.toml", "[package]\nname = \"lib\"\n"),
        ],
        &["old.rs"],
    );
    // Back at the base, with unrelated work in the tree.
    let base_commit = repo
        .find_commit(git2::Oid::from_str(&base).unwrap())
        .unwrap();
    repo.reset(base_commit.as_object(), git2::ResetType::Hard, None)
        .unwrap();
    fs::write(dir.path().join("scratch.rs"), "wip\n").unwrap();
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let change = Change::resolve(&git_repo, &refs(&base, Some(&feature))).unwrap();

    assert_eq!(change.label, format!("diff {base}...{feature}"));
    assert_eq!(paths(&change), ["a.rs", "lib/Cargo.toml", "old.rs"]);
    // The state after the change is the tree of the feature commit.
    assert!(change.has_file(&git_repo, Path::new("lib/Cargo.toml")));
    assert!(!change.has_file(&git_repo, Path::new("old.rs")));
    assert!(!change.has_file(&git_repo, Path::new("scratch.rs")));
    assert!(!change.has_file(&git_repo, Path::new("lib")));
    assert_eq!(roots(&change.graph(&git_repo).unwrap()), ["lib"]);
}

#[test]
fn between_two_refs_starts_where_they_diverged() {
    let (_dir, repo) = create_test_repo();
    let base = commit(&repo, &[("a.rs", "a\n")], &[]);
    let upstream = commit(&repo, &[("upstream.rs", "u\n")], &[]);
    let base_commit = repo
        .find_commit(git2::Oid::from_str(&base).unwrap())
        .unwrap();
    repo.reset(base_commit.as_object(), git2::ResetType::Hard, None)
        .unwrap();
    let feature = commit(&repo, &[("feature.rs", "f\n")], &[]);
    let git_repo = GitRepo::open(repo.workdir().unwrap()).unwrap();

    let change = Change::resolve(&git_repo, &refs(&upstream, Some(&feature))).unwrap();

    // What upstream added since is not a deletion made by the feature.
    assert_eq!(paths(&change), ["feature.rs"]);
}

#[test]
fn a_patch_file_is_measured_against_the_working_tree() {
    let (dir, repo) = create_test_repo();
    commit(
        &repo,
        &[
            ("src/a.rs", "one\ntwo\n"),
            ("Cargo.toml", "[package]\nname = \"app\"\n"),
        ],
        &[],
    );
    let patch = dir.path().join("change.patch");
    fs::write(&patch, PATCH).unwrap();
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let source = DiffSource::Patch {
        file: patch.clone(),
        base: None,
    };
    let change = Change::resolve(&git_repo, &source).unwrap();

    assert_eq!(change.label, format!("patch from {}", patch.display()));
    assert_eq!(paths(&change), ["new.rs", "src/a.rs"]);
    let a = change
        .diff
        .iter()
        .find(|c| c.path.ends_with("a.rs"))
        .unwrap();
    assert_eq!((a.added, a.deleted), (2, 1));
    // The patch is not applied: what it adds is not in the tree.
    assert!(!change.has_file(&git_repo, Path::new("new.rs")));
    assert!(change.has_file(&git_repo, Path::new("src/a.rs")));
    assert_eq!(roots(&change.graph(&git_repo).unwrap()), ["."]);
}

#[test]
fn a_missing_patch_file_is_an_error() {
    let (dir, repo) = create_test_repo();
    commit(&repo, &[("a.rs", "a\n")], &[]);
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let source = DiffSource::Patch {
        file: dir.path().join("nope.patch"),
        base: None,
    };
    let err = Change::resolve(&git_repo, &source)
        .err()
        .unwrap()
        .to_string();
    assert!(err.contains("cannot read the patch"), "{err}");
}

#[test]
fn text_that_is_not_a_patch_is_an_error() {
    let (dir, repo) = create_test_repo();
    commit(&repo, &[("a.rs", "a\n")], &[]);
    let file = dir.path().join("notes.txt");
    fs::write(&file, "just some notes\n").unwrap();
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let source = DiffSource::Patch { file, base: None };
    let err = Change::resolve(&git_repo, &source)
        .err()
        .unwrap()
        .to_string();
    assert!(err.contains("cannot read the patch"), "{err}");
}

#[test]
fn an_empty_patch_has_no_changes() {
    let (dir, repo) = create_test_repo();
    commit(&repo, &[("a.rs", "a\n")], &[]);
    let file = dir.path().join("empty.patch");
    fs::write(&file, "").unwrap();
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let source = DiffSource::Patch { file, base: None };
    assert!(Change::resolve(&git_repo, &source).unwrap().diff.is_empty());
}

/// Commits a and b together `times` times.
fn co_change(repo: &Repository, times: usize) {
    for i in 0..times {
        let text = format!("v{i}\n");
        commit(repo, &[("a.rs", &text), ("b.rs", &text)], &[]);
    }
}

fn shared_with_a(change: &Change, git_repo: &GitRepo) -> usize {
    let targets: HashSet<PathBuf> = [PathBuf::from("a.rs")].into();
    let history = change.history(git_repo, None, &targets, 30).unwrap();
    history.commits.get(Path::new("a.rs")).copied().unwrap_or(0)
}

#[test]
fn history_of_a_patch_ends_at_head_or_where_the_base_diverged() {
    let (dir, repo) = create_test_repo();
    co_change(&repo, 2);
    let base = repo
        .head()
        .unwrap()
        .peel_to_commit()
        .unwrap()
        .id()
        .to_string();
    co_change(&repo, 3);
    let patch = dir.path().join("p.patch");
    fs::write(&patch, PATCH).unwrap();
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let at_head = DiffSource::Patch {
        file: patch.clone(),
        base: None,
    };
    let change = Change::resolve(&git_repo, &at_head).unwrap();
    assert_eq!(shared_with_a(&change, &git_repo), 5);

    let at_base = DiffSource::Patch {
        file: patch,
        base: Some(base),
    };
    let change = Change::resolve(&git_repo, &at_base).unwrap();
    assert_eq!(shared_with_a(&change, &git_repo), 2);
}

#[test]
fn history_between_two_refs_ends_where_they_diverged() {
    let (dir, repo) = create_test_repo();
    co_change(&repo, 2);
    let base = repo
        .head()
        .unwrap()
        .peel_to_commit()
        .unwrap()
        .id()
        .to_string();
    co_change(&repo, 3);
    let git_repo = GitRepo::open(dir.path()).unwrap();

    let change = Change::resolve(&git_repo, &refs(&base, Some("HEAD"))).unwrap();
    assert_eq!(shared_with_a(&change, &git_repo), 2);
}

#[cfg(unix)]
mod pull_requests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    /// A program that answers `pr view` with `view` and `pr diff` with `diff`.
    fn fake_gh(dir: &Path, view: &str, diff: &str) -> String {
        fs::write(dir.join("view.json"), view).unwrap();
        fs::write(dir.join("pr.patch"), diff).unwrap();
        let program = dir.join("fake-gh");
        fs::write(
            &program,
            "#!/bin/sh\nhere=$(dirname \"$0\")\ncase \"$2\" in\n  view) cat \"$here/view.json\" ;;\n  diff) cat \"$here/pr.patch\" ;;\nesac\n",
        )
        .unwrap();
        fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
        program.to_str().unwrap().to_string()
    }

    fn view(base: &str, head: &str, merge: Option<&str>) -> String {
        let merge = merge.map_or("null".to_string(), |m| format!("{{\"oid\":\"{m}\"}}"));
        format!("{{\"baseRefOid\":\"{base}\",\"headRefOid\":\"{head}\",\"mergeCommit\":{merge}}}")
    }

    #[test]
    fn an_open_pull_request_is_measured_from_its_commits() {
        let (dir, repo) = create_test_repo();
        let base = commit(&repo, &[("a.rs", "a\n")], &[]);
        let head = commit(&repo, &[("a.rs", "pr\n"), ("pr.rs", "new\n")], &[]);
        let tools = tempfile::tempdir().unwrap();
        let gh = fake_gh(tools.path(), &view(&base, &head, None), "unused");
        let git_repo = GitRepo::open(dir.path()).unwrap();

        let change = Change::from_pull_request(&git_repo, &gh, 42).unwrap();

        assert_eq!(change.label, "PR #42");
        assert_eq!(paths(&change), ["a.rs", "pr.rs"]);
        assert!(change.has_file(&git_repo, Path::new("pr.rs")));
    }

    /// A head that was never fetched, as after a squash or a rebase.
    const GONE: &str = "0123456789012345678901234567890123456789";

    #[test]
    fn a_squash_merged_pull_request_is_its_patch_and_nothing_else() {
        let (dir, repo) = create_test_repo();
        // The base GitHub reports is behind: another pull request was
        // merged between it and this one.
        let base = commit(&repo, &[("src/a.rs", "one\ntwo\n")], &[]);
        commit(&repo, &[("other_pr.rs", "someone else's\n")], &[]);
        let merge = commit(
            &repo,
            &[("src/a.rs", "one\nTWO\nthree\n"), ("new.rs", "x\ny\n")],
            &[],
        );
        commit(&repo, &[("later.rs", "after the merge\n")], &["new.rs"]);
        let tools = tempfile::tempdir().unwrap();
        let gh = fake_gh(tools.path(), &view(&base, GONE, Some(&merge)), PATCH);
        let git_repo = GitRepo::open(dir.path()).unwrap();

        let change = Change::from_pull_request(&git_repo, &gh, 7).unwrap();

        assert_eq!(change.label, "PR #7");
        // What was merged in between is not part of it.
        assert_eq!(paths(&change), ["new.rs", "src/a.rs"]);
        // The state after it is the tree of the merge, whatever came later.
        assert!(change.has_file(&git_repo, Path::new("new.rs")));
        assert!(!change.has_file(&git_repo, Path::new("later.rs")));
        // That tree holds the patch, so its lines are those after it.
        let a = change
            .diff
            .iter()
            .find(|c| c.path.ends_with("a.rs"))
            .unwrap();
        let merged_text = "one\nTWO\nthree\n";
        assert_eq!(a.lines_in(merged_text), [2, 3]);
    }

    #[test]
    fn the_history_of_a_merged_pull_request_ends_before_its_merge() {
        let (dir, repo) = create_test_repo();
        co_change(&repo, 2);
        let base = repo
            .head()
            .unwrap()
            .peel_to_commit()
            .unwrap()
            .id()
            .to_string();
        co_change(&repo, 1);
        let merge = commit(&repo, &[("a.rs", "merged\n"), ("b.rs", "merged\n")], &[]);
        co_change(&repo, 3);
        let tools = tempfile::tempdir().unwrap();
        let gh = fake_gh(tools.path(), &view(&base, GONE, Some(&merge)), PATCH);
        let git_repo = GitRepo::open(dir.path()).unwrap();

        let change = Change::from_pull_request(&git_repo, &gh, 8).unwrap();

        // Three commits precede the merge; the merge and what follows do not count.
        assert_eq!(shared_with_a(&change, &git_repo), 3);
    }

    #[test]
    fn a_pull_request_merged_with_a_merge_commit_is_measured_from_its_head() {
        let (dir, repo) = create_test_repo();
        let base = commit(&repo, &[("a.rs", "a\n")], &[]);
        let head = commit(&repo, &[("pr.rs", "new\n")], &[]);
        let merge = commit(&repo, &[("unrelated.rs", "resolved by hand\n")], &[]);
        let tools = tempfile::tempdir().unwrap();
        let gh = fake_gh(tools.path(), &view(&base, &head, Some(&merge)), "unused");
        let git_repo = GitRepo::open(dir.path()).unwrap();

        let change = Change::from_pull_request(&git_repo, &gh, 5).unwrap();

        assert_eq!(paths(&change), ["pr.rs"]);
    }

    #[test]
    fn a_pull_request_without_local_commits_is_measured_from_its_patch() {
        let (dir, repo) = create_test_repo();
        commit(&repo, &[("src/a.rs", "one\ntwo\n")], &[]);
        let tools = tempfile::tempdir().unwrap();
        let gh = fake_gh(tools.path(), &view("1111111", "2222222", None), PATCH);
        let git_repo = GitRepo::open(dir.path()).unwrap();

        let change = Change::from_pull_request(&git_repo, &gh, 9).unwrap();

        assert_eq!(change.label, "PR #9");
        assert_eq!(paths(&change), ["new.rs", "src/a.rs"]);
        // Measured against the working tree, where the patch is not applied.
        assert!(!change.has_file(&git_repo, Path::new("new.rs")));
    }

    #[test]
    fn a_missing_gh_stops_the_resolution() {
        let (dir, repo) = create_test_repo();
        commit(&repo, &[("a.rs", "a\n")], &[]);
        let git_repo = GitRepo::open(dir.path()).unwrap();

        let err = Change::from_pull_request(&git_repo, "kimun-no-such-gh", 1)
            .err()
            .unwrap()
            .to_string();
        assert!(err.contains("requires the GitHub CLI"), "{err}");
    }
}