monochromatic-git-policy-cli 0.1.0

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Controls for single-flight push coordination against real disposable repositories.
//! The TypeScript corpus is `src/auto-push-single-flight.unit.test.ts`;
//! every case there has a test below with the same behavior, and the injected push counts invocations.

use super::*;
use crate::owner_lock::{SilentWait, acquire_owner_lock as acquire_lock};
use crate::owner_lock_record::{
    OWNER_LOCK_RECORD_FILENAME, OwnerLockRecord, encode_owner_lock_record,
};
use crate::test_support::{fixture, git, remove};
use std::sync::mpsc;

/// The branch every case pushes.
const BRANCH: &str = "refs/heads/main";

/// Environment of the fixture Git, matching the test support fixtures.
fn fixture_environment() -> Vec<(OsString, OsString)> {
    return [
        ("PATH", "/usr/bin:/bin"),
        ("GIT_CONFIG_NOSYSTEM", "1"),
        ("GIT_CONFIG_GLOBAL", "/nonexistent-global-config"),
        ("GIT_AUTHOR_NAME", "Fixture"),
        ("GIT_AUTHOR_EMAIL", "fixture@example.invalid"),
        ("GIT_COMMITTER_NAME", "Fixture"),
        ("GIT_COMMITTER_EMAIL", "fixture@example.invalid"),
    ]
    .iter()
    .map(|(name, value)| {
        return (OsString::from(name), OsString::from(value));
    })
    .collect();
}

/// Coordinator Git for a fixture repository.
fn push_git(root: &Path) -> PushGit {
    return PushGit {
        real_git: PathBuf::from("/usr/bin/git"),
        cwd: root.to_path_buf(),
        environment: fixture_environment(),
    };
}

/// A new empty fixture repository on `main`.
fn repository(name: &str) -> PathBuf {
    let root = fixture(name);
    git(&root, &["init", "--quiet", "--initial-branch=main"]);
    commit(&root, "base");
    return root;
}

/// Land an empty commit with real Git and return its OID.
fn commit(root: &Path, message: &str) -> String {
    let message_argument = format!("--message={message}");
    git(
        root,
        &[
            "commit",
            "--quiet",
            "--allow-empty",
            message_argument.as_str(),
        ],
    );
    return head_of(root, "HEAD");
}

/// The OID a revision names in a fixture.
fn head_of(root: &Path, revision: &str) -> String {
    return String::from_utf8_lossy(&git(root, &["rev-parse", revision]).stdout)
        .trim()
        .to_owned();
}

/// The successful attempt every counting push reports.
fn success() -> PushAttempt {
    return PushAttempt {
        exit_code: 0,
        output: "remote: ok\n".to_owned(),
    };
}

/// The coordination paths of the fixture branch.
fn paths_of(root: &Path) -> PushCoordinationPaths {
    return resolve_push_coordination_paths(&push_git(root), BRANCH).expect("paths");
}

/// Run the coordinator with a push closure and no wait observer.
fn coordinate(
    root: &Path,
    landed: &str,
    push: &mut dyn FnMut() -> Result<PushAttempt, SingleFlightError>,
) -> Result<SingleFlightOutcome, SingleFlightError> {
    return run_single_flight_push(&push_git(root), BRANCH, landed, push, &mut || {});
}

/// A record naming `tip` with the given outcome and owner.
fn record(
    tip: &str,
    outcome: LastPushedOutcome,
    owner_token: &str,
    output: &str,
) -> LastPushedRecord {
    return LastPushedRecord {
        tip: tip.to_owned(),
        outcome,
        owner_token: owner_token.to_owned(),
        owner_pid: 1,
        exit_code: if outcome == LastPushedOutcome::Pushed {
            0
        } else {
            1
        },
        output: output.to_owned(),
    };
}

/// Read the record of the fixture branch, which must exist.
fn read_record(root: &Path) -> LastPushedRecord {
    return match read_last_pushed_record(&paths_of(root).record_path).expect("reads") {
        LastPushedRead::Record(record) => record,
        LastPushedRead::Absent => panic!("record absent"),
    };
}

/// Entries of the coordination directory.
fn entries(root: &Path) -> Vec<String> {
    let directory = paths_of(root)
        .record_path
        .parent()
        .expect("directory")
        .to_path_buf();
    let mut names: Vec<String> = std::fs::read_dir(directory)
        .expect("list")
        .map(|entry| {
            return entry
                .expect("entry")
                .file_name()
                .to_string_lossy()
                .into_owned();
        })
        .collect();
    names.sort();
    return names;
}

/// Plant a lock directory whose owner exited, as the incumbent's dead-pusher case does.
fn plant_dead_lock(lock_directory: &Path) {
    let mut child = std::process::Command::new("/bin/true")
        .spawn()
        .expect("spawn");
    let pid = i64::from(child.id());
    child.wait().expect("wait");
    std::fs::create_dir(lock_directory).expect("planted lock");
    let planted = OwnerLockRecord {
        token: "dead".to_owned(),
        owner_pid: pid,
        owner_birth_identity: "dead-identity".to_owned(),
        transaction_id: None,
    };
    std::fs::write(
        lock_directory.join(OWNER_LOCK_RECORD_FILENAME),
        encode_owner_lock_record(&planted),
    )
    .expect("planted record");
}

/// The first push of a fresh repository records the tip it pushed.
#[test]
fn pushes_the_branch_tip_itself_when_no_push_was_recorded() {
    let root = repository("sf-first-push");
    let landed = commit(&root, "one");
    let mut tips: Vec<String> = Vec::new();
    let outcome = coordinate(&root, &landed, &mut || {
        tips.push(head_of(&root, BRANCH));
        return Ok(success());
    })
    .expect("coordinates");
    assert_eq!(
        outcome,
        SingleFlightOutcome {
            kind: SingleFlightKind::Pushed,
            tip: landed.clone(),
            exit_code: 0,
            output: "remote: ok\n".to_owned(),
            covered: true,
        }
    );
    assert_eq!(tips, vec![landed.clone()]);
    let written = read_record(&root);
    assert_eq!(written.tip, landed);
    assert_eq!(written.outcome, LastPushedOutcome::Pushed);
    assert_eq!(written.output, "");
    assert_eq!(written.owner_pid, i64::from(std::process::id()));
    assert_eq!(
        entries(&root),
        vec!["refs%2Fheads%2Fmain.last-pushed.json".to_owned()]
    );
    remove(&root);
}

/// A recorded successful push that covers the commit joins without taking the lock.
#[test]
fn joins_a_recorded_successful_push_covering_the_commit_without_taking_the_lock() {
    let root = repository("sf-fast-join");
    let older = commit(&root, "older");
    let tip = commit(&root, "tip");
    let paths = paths_of(&root);
    write_last_pushed_record(
        &paths.record_path,
        &record(&tip, LastPushedOutcome::Pushed, "earlier", ""),
    )
    .expect("write");
    let held =
        acquire_lock(&paths.lock_directory, DEFAULT_POLL_DELAY, &mut SilentWait).expect("held");
    let mut pushes = 0;
    let outcome = coordinate(&root, &older, &mut || {
        pushes += 1;
        return Ok(success());
    })
    .expect("joins");
    assert_eq!(
        outcome,
        SingleFlightOutcome {
            kind: SingleFlightKind::JoinedPushed,
            tip,
            exit_code: 0,
            output: String::new(),
            covered: true,
        }
    );
    assert_eq!(pushes, 0);
    drop(held);
    remove(&root);
}

/// A recorded success that does not cover the commit leads to a push of its own.
#[test]
fn pushes_itself_when_the_recorded_successful_push_does_not_cover_the_commit() {
    let root = repository("sf-not-covering");
    let pushed = commit(&root, "pushed");
    let landed = commit(&root, "newer");
    write_last_pushed_record(
        &paths_of(&root).record_path,
        &record(&pushed, LastPushedOutcome::Pushed, "earlier", ""),
    )
    .expect("write");
    let mut tips: Vec<String> = Vec::new();
    let outcome = coordinate(&root, &landed, &mut || {
        tips.push(head_of(&root, BRANCH));
        return Ok(success());
    })
    .expect("coordinates");
    assert_eq!(outcome.kind, SingleFlightKind::Pushed);
    assert_eq!(tips, vec![landed]);
    remove(&root);
}

/// A failed push recorded before the commit waited is not reported as this commit's outcome.
#[test]
fn retries_a_failed_push_recorded_before_it_waited() {
    let root = repository("sf-stale-failure");
    let landed = commit(&root, "one");
    write_last_pushed_record(
        &paths_of(&root).record_path,
        &record(&landed, LastPushedOutcome::Failed, "earlier", "old failure"),
    )
    .expect("write");
    let mut pushes = 0;
    let outcome = coordinate(&root, &landed, &mut || {
        pushes += 1;
        return Ok(success());
    })
    .expect("coordinates");
    assert_eq!(outcome.kind, SingleFlightKind::Pushed);
    assert_eq!(pushes, 1);
    remove(&root);
}

/// Run a coordinator behind a lock the test holds: returns once the coordinator reports the wait.
///
/// The test releases the lock after it writes whatever record the case needs,
/// so the coordinator then reads that record, as a live pusher would leave it.
fn coordinate_behind_lock<F>(root: &Path, landed: &str, prepare: F) -> SingleFlightOutcome
where
    F: FnOnce(&Path, &str),
{
    let paths = paths_of(root);
    let held =
        acquire_lock(&paths.lock_directory, DEFAULT_POLL_DELAY, &mut SilentWait).expect("held");
    let (wait_tx, wait_rx) = mpsc::channel::<()>();
    let git_context = push_git(root);
    let landed_oid = landed.to_owned();
    let outcome = std::thread::scope(|scope| {
        let handle = scope.spawn(|| {
            let mut pushes = 0;
            return run_single_flight_push(
                &git_context,
                BRANCH,
                &landed_oid,
                &mut || {
                    pushes += 1;
                    return Ok(success());
                },
                &mut || {
                    let _sent = wait_tx.send(());
                },
            );
        });
        let _waiting = wait_rx.recv();
        prepare(&paths.record_path, held.token());
        drop(held);
        return handle
            .join()
            .expect("coordinator thread")
            .expect("coordinates");
    });
    return outcome;
}

/// A live pusher's successful push that covers the commit is joined, not repeated.
#[test]
fn waits_for_a_live_pusher_and_joins_its_successful_push_when_it_covers_the_commit() {
    let root = repository("sf-join-success");
    let landed = commit(&root, "one");
    let outcome = coordinate_behind_lock(&root, &landed, |record_path, token| {
        write_last_pushed_record(
            record_path,
            &record(&landed, LastPushedOutcome::Pushed, token, ""),
        )
        .expect("write");
    });
    assert_eq!(
        outcome,
        SingleFlightOutcome {
            kind: SingleFlightKind::JoinedPushed,
            tip: landed.clone(),
            exit_code: 0,
            output: String::new(),
            covered: true,
        }
    );
    remove(&root);
}

/// A live pusher's failed push that covers the commit is reported with its output.
#[test]
fn waits_for_a_live_pusher_and_reports_its_failed_push_when_it_covered_the_commit() {
    let root = repository("sf-join-failure");
    let landed = commit(&root, "one");
    let outcome = coordinate_behind_lock(&root, &landed, |record_path, token| {
        write_last_pushed_record(
            record_path,
            &LastPushedRecord {
                exit_code: 1,
                ..record(
                    &landed,
                    LastPushedOutcome::Failed,
                    token,
                    "pre-push hook declined\n",
                )
            },
        )
        .expect("write");
    });
    assert_eq!(
        outcome,
        SingleFlightOutcome {
            kind: SingleFlightKind::JoinedFailed,
            tip: landed.clone(),
            exit_code: 1,
            output: "pre-push hook declined\n".to_owned(),
            covered: true,
        }
    );
    remove(&root);
}

/// A live pusher's failed push that does not cover the commit leaves the commit to push itself.
#[test]
fn pushes_itself_after_a_live_pusher_failed_a_push_that_did_not_cover_the_commit() {
    let root = repository("sf-failure-not-covering");
    let failed_tip = commit(&root, "failed");
    let landed = commit(&root, "newer");
    let outcome = coordinate_behind_lock(&root, &landed, |record_path, token| {
        write_last_pushed_record(
            record_path,
            &record(&failed_tip, LastPushedOutcome::Failed, token, "declined\n"),
        )
        .expect("write");
    });
    assert_eq!(outcome.kind, SingleFlightKind::Pushed);
    assert_eq!(outcome.tip, landed);
    remove(&root);
}

/// A lock holder that released without recording a push leaves the commit to push itself.
#[test]
fn pushes_itself_when_the_lock_holder_released_without_recording_a_push() {
    let root = repository("sf-holder-nothing");
    let landed = commit(&root, "one");
    let outcome = coordinate_behind_lock(&root, &landed, |_record_path, _token| {});
    assert_eq!(outcome.kind, SingleFlightKind::Pushed);
    assert_eq!(outcome.tip, landed);
    remove(&root);
}

/// The lock of a dead pusher is retired and the commit pushes itself.
#[test]
fn takes_over_the_push_lock_of_a_dead_pusher_and_pushes_itself() {
    let root = repository("sf-dead-pusher");
    let landed = commit(&root, "one");
    plant_dead_lock(&paths_of(&root).lock_directory);
    let mut pushes = 0;
    let outcome = coordinate(&root, &landed, &mut || {
        pushes += 1;
        return Ok(success());
    })
    .expect("coordinates");
    assert_eq!(outcome.kind, SingleFlightKind::Pushed);
    assert_eq!(pushes, 1);
    assert_eq!(
        entries(&root),
        vec!["refs%2Fheads%2Fmain.last-pushed.json".to_owned()]
    );
    remove(&root);
}

/// A failed push of this commit is recorded with its complete output and reported.
#[test]
fn records_and_reports_its_own_failed_push_with_the_complete_output() {
    let root = repository("sf-own-failure");
    let landed = commit(&root, "one");
    let outcome = coordinate(&root, &landed, &mut || {
        return Ok(PushAttempt {
            exit_code: 1,
            output: "error: failed to push some refs\n".to_owned(),
        });
    })
    .expect("coordinates");
    assert_eq!(
        outcome,
        SingleFlightOutcome {
            kind: SingleFlightKind::Failed,
            tip: landed.clone(),
            exit_code: 1,
            output: "error: failed to push some refs\n".to_owned(),
            covered: true,
        }
    );
    let written = read_record(&root);
    assert_eq!(written.outcome, LastPushedOutcome::Failed);
    assert_eq!(written.output, "error: failed to push some refs\n");
    assert_eq!(written.exit_code, 1);
    remove(&root);
}

/// A pushed tip that no longer contains the landed commit is reported as uncovered.
#[test]
fn reports_a_pushed_tip_that_no_longer_contains_the_landed_commit_as_uncovered() {
    let root = repository("sf-uncovered");
    let landed = commit(&root, "dropped");
    git(&root, &["reset", "--quiet", "--hard", "HEAD~1"]);
    let outcome = coordinate(&root, &landed, &mut || {
        return Ok(success());
    })
    .expect("coordinates");
    assert_eq!(outcome.kind, SingleFlightKind::Pushed);
    assert!(!outcome.covered);
    remove(&root);
}

/// Concurrent landings coalesce: the first push covers all five commits and the others join it.
#[test]
fn coalesces_concurrent_landings_into_fewer_pushes_than_commits() {
    let root = repository("sf-coalesce");
    let landed: Vec<String> = ["c1", "c2", "c3", "c4", "c5"]
        .iter()
        .map(|message| {
            return commit(&root, message);
        })
        .collect();
    let pushes = std::sync::atomic::AtomicUsize::new(0);
    let git_context = push_git(&root);
    let outcomes: Vec<SingleFlightOutcome> = std::thread::scope(|scope| {
        let handles: Vec<_> = landed
            .iter()
            .map(|oid| {
                let context = &git_context;
                let counter = &pushes;
                return scope.spawn(move || {
                    return run_single_flight_push(
                        context,
                        BRANCH,
                        oid,
                        &mut || {
                            counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                            std::thread::sleep(std::time::Duration::from_millis(200));
                            return Ok(success());
                        },
                        &mut || {},
                    )
                    .expect("coordinates");
                });
            })
            .collect();
        return handles
            .into_iter()
            .map(|handle| {
                return handle.join().expect("thread");
            })
            .collect();
    });
    assert_eq!(pushes.load(std::sync::atomic::Ordering::SeqCst), 1);
    assert!(outcomes.iter().all(|outcome| {
        return outcome.covered
            && matches!(
                outcome.kind,
                SingleFlightKind::Pushed | SingleFlightKind::JoinedPushed
            );
    }));
    remove(&root);
}

/// Ancestry is answered for ancestors and equal tips, and a Git failure is an error.
#[test]
fn tip_contains_reports_ancestry_and_rethrows_other_git_failures() {
    let root = repository("sf-tip-contains");
    let older = commit(&root, "older");
    let newer = commit(&root, "newer");
    let context = push_git(&root);
    assert!(tip_contains(&context, &older, &newer).expect("ancestor"));
    assert!(tip_contains(&context, &newer, &newer).expect("equal"));
    assert!(!tip_contains(&context, &newer, &older).expect("not ancestor"));
    assert!(tip_contains(&context, &"f".repeat(40), &newer).is_err());
    remove(&root);
}

/// A linked worktree resolves its coordination files under the shared common Git directory.
#[test]
fn coordination_files_live_under_the_common_git_directory_shared_by_linked_worktrees() {
    let root = repository("sf-linked");
    commit(&root, "one");
    let linked = root.with_extension("linked");
    git(
        &root,
        &[
            "worktree",
            "add",
            "--quiet",
            "-b",
            "side",
            linked.to_str().expect("utf-8 path"),
        ],
    );
    let paths =
        resolve_push_coordination_paths(&push_git(&linked), "refs/heads/side").expect("paths");
    let common = root.join(".git").join("cli-git").join("push");
    assert_eq!(
        paths.lock_directory,
        common.join("refs%2Fheads%2Fside.lock")
    );
    assert_eq!(
        paths.record_path,
        common.join("refs%2Fheads%2Fside.last-pushed.json")
    );
    remove(&linked);
    remove(&root);
}