post-push-party 0.1.12

Push code, earn points, throw a party!
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
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;

/// Returns all remote tracking branches and their SHAs.
/// e.g., {"main" => "abc123", "feature" => "def456"}
pub fn get_all_remote_refs(repo_path: &Path) -> HashMap<String, String> {
    let output = Command::new("git")
        .args([
            "for-each-ref",
            "--format=%(refname:short) %(objectname)",
            "refs/remotes/origin/",
        ])
        .current_dir(repo_path)
        .output()
        .ok();

    let mut refs = HashMap::new();
    if let Some(output) = output
        && output.status.success()
    {
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            // format: "origin/main abc123..."
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                // strip "origin/" prefix
                if let Some(branch) = parts[0].strip_prefix("origin/") {
                    // skip HEAD
                    if branch != "HEAD" {
                        refs.insert(branch.to_string(), parts[1].to_string());
                    }
                }
            }
        }
    }
    refs
}

/// Returns all local tracking branches and their SHAs.
/// e.g., {"main" => "abc123", "feature" => "def456"}
pub fn get_all_local_refs(repo_path: &Path) -> HashMap<String, String> {
    let output = Command::new("git")
        .args([
            "for-each-ref",
            "--format=%(refname:short) %(objectname)",
            "refs/heads",
        ])
        .current_dir(repo_path)
        .output()
        .ok();

    let mut refs = HashMap::new();
    if let Some(output) = output
        && output.status.success()
    {
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            // format: "branch-name abc123..."
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                let branch = parts[0];
                let sha = parts[1];
                refs.insert(branch.to_string(), sha.to_string());
            }
        }
    }
    refs
}

pub fn get_remote_url(repo_path: &Path) -> Option<String> {
    let output = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(repo_path)
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        None
    }
}

/// List commits in range old_sha..new_sha (commits reachable from new but not old).
pub fn list_commits_in_range(repo_path: &Path, old_sha: &str, new_sha: &str) -> Vec<String> {
    let output = Command::new("git")
        .args(["rev-list", &format!("{}..{}", old_sha, new_sha)])
        .current_dir(repo_path)
        .output();

    match output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .map(|s| s.to_string())
            .collect(),
        _ => Vec::new(),
    }
}

/// Check if a commit is reachable from any remote branch OTHER than the specified ones.
/// Used to filter out commits that came from fetch but are in the push range due to rebasing.
pub fn is_reachable_from_other_remote(
    repo_path: &Path,
    sha: &str,
    exclude_branches: &[&str],
) -> bool {
    // Get all remote branches except the ones we're pushing
    let refs_output = Command::new("git")
        .args([
            "for-each-ref",
            "--format=%(refname)",
            "refs/remotes/origin/",
        ])
        .current_dir(repo_path)
        .output();

    let other_refs: Vec<String> = match refs_output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .filter(|r| {
                let dominated = exclude_branches
                    .iter()
                    .any(|b| r.ends_with(&format!("/{}", b)));
                !dominated && !r.ends_with("/HEAD")
            })
            .map(|s| s.to_string())
            .collect(),
        _ => return false,
    };

    if other_refs.is_empty() {
        return false;
    }

    // Check if commit is reachable from any of these refs
    // git merge-base --is-ancestor <sha> <ref> returns 0 if sha is ancestor of ref
    for ref_name in &other_refs {
        let result = Command::new("git")
            .args(["merge-base", "--is-ancestor", sha, ref_name])
            .current_dir(repo_path)
            .output();

        if let Ok(o) = result
            && o.status.success()
        {
            return true;
        }
    }

    false
}

/// List commits on the given branches that aren't reachable from any other remote branch.
/// Used for first-time pushes where we don't have an old SHA.
pub fn list_unique_commits(repo_path: &Path, branches: &[&str]) -> Vec<String> {
    // git rev-list origin/branch1 origin/branch2 ... --not --exclude=origin/branch1 --exclude=origin/branch2 ... --remotes=origin
    let mut args = vec!["rev-list".to_string()];

    // add all branches as positive refs
    for branch in branches {
        args.push(format!("refs/remotes/origin/{}", branch));
    }

    args.push("--not".to_string());

    // exclude all the branches we're including
    for branch in branches {
        args.push(format!("--exclude=origin/{}", branch));
    }

    args.push("--remotes=origin".to_string());

    let output = Command::new("git")
        .args(&args)
        .current_dir(repo_path)
        .output();

    match output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .map(|s| s.to_string())
            .collect(),
        _ => Vec::new(),
    }
}

/// Returns total lines changed (added + removed) for a commit.
pub fn get_lines_changed(repo_path: &Path, sha: &str) -> Option<u64> {
    // git show --stat --format="" <sha>
    // outputs lines like: " file.rs | 10 ++++----"
    // with summary: " 3 files changed, 10 insertions(+), 5 deletions(-)"
    let output = Command::new("git")
        .args(["show", "--stat", "--format=", sha])
        .current_dir(repo_path)
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    // parse the last line for the summary
    let last_line = stdout.lines().last()?;

    let mut insertions = 0u64;
    let mut deletions = 0u64;

    // look for "N insertion" and "N deletion" patterns
    for word in last_line.split_whitespace().collect::<Vec<_>>().windows(2) {
        if word[1].starts_with("insertion") {
            insertions = word[0].parse().unwrap_or(0);
        } else if word[1].starts_with("deletion") {
            deletions = word[0].parse().unwrap_or(0);
        }
    }

    Some(insertions + deletions)
}

/// Get the patch-id for a commit. Returns None if the commit has no diff (e.g., merge commits).
pub fn get_patch_id(repo_path: &Path, sha: &str) -> Option<String> {
    // git show <sha> | git patch-id --stable
    let show = Command::new("git")
        .args(["show", sha])
        .current_dir(repo_path)
        .output()
        .ok()?;

    if !show.status.success() {
        return None;
    }

    let patch_id = Command::new("git")
        .args(["patch-id", "--stable"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .current_dir(repo_path)
        .spawn()
        .ok()?;

    use std::io::Write;
    patch_id.stdin.as_ref()?.write_all(&show.stdout).ok()?;
    let output = patch_id.wait_with_output().ok()?;

    if output.status.success() {
        let line = String::from_utf8_lossy(&output.stdout);
        // format: "<patch-id> <commit-sha>"
        line.split_whitespace().next().map(|s| s.to_string())
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::fs;
    use std::process::Command;
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    struct TestRepo {
        path: std::path::PathBuf,
    }

    impl TestRepo {
        fn new() -> Self {
            let id = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
            let path =
                std::env::temp_dir().join(format!("party-test-{}-{}", std::process::id(), id));
            fs::create_dir_all(&path).unwrap();

            // init repo
            Command::new("git")
                .args(["init"])
                .current_dir(&path)
                .output()
                .unwrap();

            // configure user (required for commits)
            Command::new("git")
                .args(["config", "user.email", "test@test.com"])
                .current_dir(&path)
                .output()
                .unwrap();
            Command::new("git")
                .args(["config", "user.name", "Test"])
                .current_dir(&path)
                .output()
                .unwrap();

            Self { path }
        }

        fn write_file(&self, name: &str, content: &str) {
            fs::write(self.path.join(name), content).unwrap();
        }

        fn commit(&self, msg: &str) -> String {
            Command::new("git")
                .args(["add", "."])
                .current_dir(&self.path)
                .output()
                .unwrap();

            Command::new("git")
                .args(["commit", "-m", msg])
                .current_dir(&self.path)
                .output()
                .unwrap();

            // get the sha
            let output = Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(&self.path)
                .output()
                .unwrap();

            String::from_utf8_lossy(&output.stdout).trim().to_string()
        }

        fn current_branch_name(&self) -> String {
            let output = Command::new("git")
                .args(["rev-parse", "--abbrev-ref", "HEAD"])
                .current_dir(&self.path)
                .output()
                .unwrap();

            String::from_utf8_lossy(&output.stdout).trim().to_string()
        }

        fn checkout(&self, branch: &str) {
            Command::new("git")
                .args(["checkout", "-b", branch])
                .current_dir(&self.path)
                .output()
                .unwrap();
        }
    }

    impl Drop for TestRepo {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.path);
        }
    }

    #[test]
    fn lines_changed_counts_insertions() {
        let repo = TestRepo::new();
        repo.write_file("test.txt", "line1\nline2\nline3\n");
        let sha = repo.commit("add 3 lines");

        let lines = get_lines_changed(&repo.path, &sha);
        assert_eq!(lines, Some(3));
    }

    #[test]
    fn lines_changed_counts_deletions() {
        let repo = TestRepo::new();
        repo.write_file("test.txt", "line1\nline2\nline3\n");
        repo.commit("initial");

        repo.write_file("test.txt", "line1\n");
        let sha = repo.commit("delete 2 lines");

        let lines = get_lines_changed(&repo.path, &sha);
        assert_eq!(lines, Some(2));
    }

    #[test]
    fn lines_changed_counts_both() {
        let repo = TestRepo::new();
        repo.write_file("test.txt", "aaa\nbbb\nccc\n");
        repo.commit("initial");

        repo.write_file("test.txt", "aaa\nBBB\nccc\nddd\n");
        let sha = repo.commit("modify and add");

        // 1 deletion (bbb) + 2 insertions (BBB, ddd) = 3
        let lines = get_lines_changed(&repo.path, &sha);
        assert_eq!(lines, Some(3));
    }

    #[test]
    fn lines_changed_single_line_addition() {
        let repo = TestRepo::new();
        repo.write_file("test.txt", "line1\nline2\n");
        repo.commit("initial");

        repo.write_file("test.txt", "line1\nline2\nline3\n");
        let sha = repo.commit("add one line");

        let lines = get_lines_changed(&repo.path, &sha);
        assert_eq!(lines, Some(1));
    }

    #[test]
    fn lines_changed_invalid_sha_returns_none() {
        let repo = TestRepo::new();
        repo.write_file("test.txt", "content\n");
        repo.commit("initial");

        let lines = get_lines_changed(&repo.path, "invalid-sha");
        assert_eq!(lines, None);
    }

    #[test]
    fn test_get_all_local_refs() {
        let repo = TestRepo::new();

        repo.write_file("test0.txt", "content\n");
        repo.commit("commit0");

        // we have to do this after the first commit otherwise we get nothing
        let default_branch_name = repo.current_branch_name();

        repo.checkout("test-branch1");
        repo.write_file("test1.txt", "content\n");
        repo.commit("commit1");

        repo.checkout("test-branch2");
        repo.write_file("test2.txt", "content\n");
        repo.commit("commit2");

        let local_refs = get_all_local_refs(&repo.path);
        assert_eq!(
            local_refs.keys().collect::<HashSet<_>>(),
            HashSet::from([
                &default_branch_name,
                &"test-branch1".to_string(),
                &"test-branch2".to_string()
            ])
        )
    }
}