monochromatic-git-policy-cli 0.5.16

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
//! Controls for native preparation: real state unchanged, the shadow's shape, no hook of any kind run, and no shadow
//!  left behind.

use super::*;
use crate::capture_invocation::{capture_invocation_base, capture_invocation_layout};
use crate::private_index_request::CaptureIndexes;
use crate::commit_index::{IndexSelection, initialize_commit_index, write_private_tree};
use crate::shadow_create::create_shadow_repository;
use crate::test_support::{fixture, git, git_context, git_text, remove, repository};
use crate::transaction_journal::TransactionMode;
use crate::candidate_prediction::CandidateRequest;
use crate::command_test_support::os_arguments;
use crate::commit_convergence::{CommitConvergence, CommitConvergenceInput, converge_commit_policies};
use crate::config_schema::PolicyConfig;
use crate::policy_checks::shipped_checks;
use crate::policy_content::{Correction, LifecycleContent};
use crate::policy_convergence::Convergence;
use crate::policy_engine::StageRequest;
use crate::policy_trigger::Trigger;
use crate::private_index_stage::{PrivateStage, stage_correction};
use crate::candidate_object::CandidateMode;
use crate::repository_facts::git_facts;
use crate::signal_relay::SignalGuardActive;
use crate::test_support::REAL_GIT;
use crate::wrapper_controls::no_controls;
use std::ffi::OsString;
use std::path::PathBuf;
use std::rc::Rc;

/// A fixed transaction ID of the shape the registry accepts.
const TRANSACTION: &str = "0b6c2c1e-6f5b-4d0e-9a55-3f5d8e2f6a10";

/// Everything one preparation fixture produced.
struct Fixture {
    /// Repository the transaction selects.
    repo: PathBuf,
    /// Shadow repository of the transaction.
    shadow: PathBuf,
    /// Invocation capture.
    capture: InvocationCapture,
    /// Private commit index, staged for `a.txt` only.
    commit_index: PathBuf,
    /// Intended tree of the private index.
    intended_tree: String,
}

/// A repository with `a.txt` committed, the change to `a.txt` staged privately, and a shadow ready to prepare.
fn prepared_fixture(root: &Path) -> Fixture {
    let repo: PathBuf = repository(root, "repo");
    std::fs::write(repo.join("a.txt"), "a\n").expect("a");
    git(repo.as_path(), &["add", "a.txt"]);
    git(repo.as_path(), &["commit", "--quiet", "--message=a"]);
    git(repo.as_path(), &["remote", "add", "origin", "https://example.invalid/repo.git"]);
    let base: String = git_text(repo.as_path(), &["rev-parse", "HEAD"]);
    git(repo.as_path(), &["update-ref", "refs/remotes/origin/main", base.as_str()]);
    git(repo.as_path(), &["config", "branch.main.remote", "origin"]);
    git(repo.as_path(), &["config", "branch.main.merge", "refs/heads/main"]);
    std::fs::write(repo.join(".git").join("branch.config"), "[x]\n\tv = onbranch\n").expect("include");
    std::fs::OpenOptions::new()
        .append(true)
        .open(repo.join(".git").join("config"))
        .and_then(|mut file| {
            use std::io::Write;
            return file.write_all(b"[includeIf \"onbranch:main\"]\n\tpath = branch.config\n");
        })
        .expect("include config");
    std::fs::write(repo.join("a.txt"), "changed\n").expect("change a");
    let context = git_context();
    let layout = capture_invocation_layout(&context, repo.as_path(), false).expect("layout");
    let capture: InvocationCapture = capture_invocation_base(&context, repo.as_path(), layout).expect("capture");
    let transaction: PathBuf = root.join(format!("transaction-{TRANSACTION}"));
    std::fs::create_dir_all(&transaction).expect("transaction");
    let shadow: PathBuf = create_shadow_repository(&context, repo.as_path(), &capture, TRANSACTION, transaction.as_path())
        .expect("shadow");
    let indexes: CaptureIndexes = CaptureIndexes {
        captured_index: transaction.join("captured.index"),
        commit_index: transaction.join("commit.index"),
        object_directory: shadow.join("objects"),
    };
    let pathspecs: Vec<OsString> = vec![OsString::from("a.txt")];
    let selection: IndexSelection = IndexSelection {
        mode: TransactionMode::ExplicitPath,
        pathspecs: pathspecs.as_slice(),
        pathspec_file: None,
        pathspec_file_nul: false,
        stage_into_index: false,
        stage_tracked_changes: false,
        base_revision: base.as_str(),
    };
    initialize_commit_index(&context, repo.as_path(), capture.layout.real_index_path.as_path(), &indexes, &selection)
        .expect("private index");
    let intended_tree: String = write_private_tree(
        &context,
        repo.as_path(),
        indexes.commit_index.as_path(),
        indexes.object_directory.as_path(),
    )
    .expect("tree");
    return Fixture {
        repo,
        shadow,
        capture,
        commit_index: indexes.commit_index,
        intended_tree,
    };
}

/// Runs the preparation of a fixture.
fn prepare(fixture: &Fixture, commit_args: &[&str]) -> Result<PreparedCommit, PreparationError> {
    let commit_arguments: Vec<String> = commit_args.iter().map(|arg| { return String::from(*arg); }).collect();
    let request: PreparationRequest = PreparationRequest {
        capture: &fixture.capture,
        shadow: fixture.shadow.as_path(),
        commit_index: fixture.commit_index.as_path(),
        global_args: &[],
        commit_args: commit_arguments.as_slice(),
        object_directory: None,
    };
    let code: i32 = run_native_commit(&git_context(), fixture.repo.as_path(), &request)?;
    if code != 0 {
        return Err(PreparationError::Git(GitFailure(format!("git commit exited {code}"))));
    }
    return read_prepared_commit(&git_context(), fixture.shadow.as_path()).map_err(PreparationError::Git);
}

/// Preparation leaves the real refs, the real index and the worktree bytes unchanged,
///  and the prepared commit lives in the shadow.
#[test]
fn preparation_leaves_real_refs_index_and_worktree_unchanged() {
    let root: PathBuf = fixture("commit-preparation-success");
    let fixture: Fixture = prepared_fixture(root.as_path());
    let refs_before: String = git_text(fixture.repo.as_path(), &["for-each-ref"]);
    let index_before: Vec<u8> = std::fs::read(fixture.repo.join(".git").join("index")).expect("index");
    let head_before: String = git_text(fixture.repo.as_path(), &["rev-parse", "HEAD"]);
    let prepared: PreparedCommit = prepare(&fixture, &["-m", "message"]).expect("prepared");
    assert_eq!(git_text(fixture.repo.as_path(), &["for-each-ref"]), refs_before);
    assert_eq!(git_text(fixture.repo.as_path(), &["rev-parse", "HEAD"]), head_before);
    assert_eq!(std::fs::read(fixture.repo.join(".git").join("index")).expect("index"), index_before);
    assert_eq!(std::fs::read_to_string(fixture.repo.join("a.txt")).expect("worktree"), "changed\n");
    assert_eq!(prepared.tree_oid, fixture.intended_tree);
    assert!(!prepared.signed);
    assert_eq!(
        git_text(fixture.shadow.as_path(), &["rev-parse", "HEAD"]),
        prepared.oid
    );
    remove(root.as_path());
}

/// The native command names the shadow and turns traditional hooks off, and names no work tree.
#[test]
fn native_commit_arguments_name_the_shadow_and_turn_traditional_hooks_off() {
    let capture_root: PathBuf = fixture("commit-preparation-arguments");
    let repo: PathBuf = repository(capture_root.as_path(), "repo");
    let context = git_context();
    let layout = capture_invocation_layout(&context, repo.as_path(), false).expect("layout");
    let capture: InvocationCapture = capture_invocation_base(&context, repo.as_path(), layout).expect("capture");
    let commit_arguments: Vec<String> = vec![String::from("-m"), String::from("x")];
    let global: Vec<String> = vec![String::from("-c"), String::from("a.b=1")];
    let request: PreparationRequest = PreparationRequest {
        capture: &capture,
        shadow: Path::new("/s"),
        commit_index: Path::new("/i"),
        global_args: global.as_slice(),
        commit_args: commit_arguments.as_slice(),
        object_directory: None,
    };
    assert_eq!(
        native_commit_arguments(&request),
        vec![
            "-c",
            "a.b=1",
            "--git-dir=/s",
            "-c",
            "core.hooksPath=/dev/null/cli-git-no-hooks",
            "commit",
            "-m",
            "x",
        ]
    );
    remove(capture_root.as_path());
}

/// The prepared commit's signature is read from its header block only, not from the message.
#[test]
fn signature_is_read_from_the_header_block_only() {
    let root: PathBuf = fixture("commit-preparation-signed");
    let repo: PathBuf = repository(root.as_path(), "repo");
    let head: String = git_text(repo.as_path(), &["rev-parse", "HEAD"]);
    let shadow: PathBuf = root.join("shadow");
    std::fs::create_dir(&shadow).expect("shadow");
    git(&shadow, &["init", "--bare", "--quiet", "--template="]);
    std::fs::write(shadow.join("objects").join("info").join("alternates"), format!("{}\n", repo.join(".git").join("objects").display())).expect("alternates");
    git(&shadow, &["update-ref", "refs/heads/main", head.as_str()]);
    git(&shadow, &["symbolic-ref", "HEAD", "refs/heads/main"]);
    let prepared: PreparedCommit = read_prepared_commit(&git_context(), shadow.as_path()).expect("read");
    assert_eq!(prepared.oid, head);
    assert!(!prepared.signed);
    remove(root.as_path());
}

/// The shadow object store of a fixture, where the commit path writes its corrected blobs.
fn shadow_objects(fixture: &Fixture) -> PathBuf {
    return fixture.shadow.join("objects");
}

/// The exact bytes the prepared commit's tree holds for a path, read from the shadow repository.
fn shadow_text(fixture: &Fixture, commit: &str, path: &str) -> String {
    let shadow: String = fixture.shadow.display().to_string();
    let output: std::process::Output = git(
        fixture.repo.as_path(),
        &["--git-dir", shadow.as_str(), "show", format!("{commit}:{path}").as_str()],
    );
    return String::from_utf8_lossy(output.stdout.as_slice()).into_owned();
}

/// Runs the commit path's convergence over the fixture's private commit index.
fn converge_fixture(fixture: &Fixture) -> CommitConvergence {
    let objects: PathBuf = shadow_objects(fixture);
    let overlay: Vec<(OsString, OsString)> = vec![
        (OsString::from("GIT_DIR"), fixture.repo.join(".git").into_os_string()),
        (OsString::from("GIT_WORK_TREE"), fixture.repo.as_os_str().to_os_string()),
        (OsString::from("GIT_INDEX_FILE"), fixture.commit_index.as_os_str().to_os_string()),
        (OsString::from("GIT_OBJECT_DIRECTORY"), objects.as_os_str().to_os_string()),
    ];
    let facts = git_facts(std::path::Path::new(REAL_GIT), &[], overlay.as_slice());
    let mut checks = shipped_checks(
        facts,
        os_arguments(&[]),
        LifecycleContent::Requested(CandidateRequest::Staged(vec![OsString::from("a.txt")])),
        Vec::<PathBuf>::new(),
    );
    let request: StageRequest = StageRequest {
        trigger: Trigger::PreForward,
        config: PolicyConfig::defaults(),
        controls: no_controls(),
        selected: Vec::new(),
    };
    return converge_commit_policies(CommitConvergenceInput {
        request: &request,
        checks: &mut checks,
        stage: PrivateStage {
            context: &git_context(),
            cwd: fixture.repo.as_path(),
            index: fixture.commit_index.as_path(),
            object_directory: Some(objects.as_path()),
        },
    });
}

/// The final-newline correction the commit path writes reaches the prepared commit's tree.
#[test]
fn the_final_newline_correction_reaches_the_prepared_commit() {
    let root: PathBuf = fixture("preparation-final-newline");
    let mut prepared_for: Fixture = prepared_fixture(root.as_path());
    let objects: PathBuf = shadow_objects(&prepared_for);
    let uncorrected: Correction = Correction {
        path: b"a.txt".to_vec(),
        mode: CandidateMode::Regular,
        before: Rc::from(b"changed\n".as_slice()),
        after: Rc::from(b"changed".as_slice()),
    };
    let stage: PrivateStage<'_> = PrivateStage {
        context: &git_context(),
        cwd: prepared_for.repo.as_path(),
        index: prepared_for.commit_index.as_path(),
        object_directory: Some(objects.as_path()),
    };
    assert_eq!(stage_correction(&stage, &uncorrected), Ok(()), "the uncorrected bytes are staged");
    let outcome: CommitConvergence = converge_fixture(&prepared_for);
    assert_eq!(outcome.convergence, Convergence::Settled { changed_passes: 1 }, "{:?}", outcome.pass.events);
    prepared_for.intended_tree = write_private_tree(
        &git_context(),
        prepared_for.repo.as_path(),
        prepared_for.commit_index.as_path(),
        objects.as_path(),
    )
    .expect("the corrected tree");
    let prepared: PreparedCommit = prepare(&prepared_for, &["--quiet", "-m", "corrected"])
        .expect("the corrected commit prepares");
    assert_eq!(shadow_text(&prepared_for, prepared.oid.as_str(), "a.txt"), "changed\n");
    remove(root.as_path());
}

/// The wait for the guard ends with the first success, passes over only the "already active" failure, and gives up
///  after the limit with the failure itself. Every closure panics past its call cap, so a mutated guard that retries
///  too often fails the test at once instead of looping.
#[test]
fn the_guard_wait_retries_only_while_another_holder_is_active() {
    let delay = std::time::Duration::from_millis(1);
    let active = || { return std::io::Error::other(SignalGuardActive); };
    let mut calls: u32 = 0;
    let waited: std::io::Result<u32> = retry_while_active(
        || {
            calls += 1;
            assert!(calls <= 3, "the success on the third call ends the wait");
            if calls < 3 { return Err(active()); }
            return Ok(calls);
        },
        5,
        delay,
    );
    assert_eq!(waited.expect("success after two active failures"), 3);
    let mut other_calls: u32 = 0;
    let other: std::io::Result<u32> = retry_while_active(
        || {
            other_calls += 1;
            assert!(other_calls <= 1, "another failure is returned at once, never retried");
            return Err(std::io::Error::other("no handler could be installed"));
        },
        5,
        delay,
    );
    assert!(other.is_err());
    assert_eq!(other_calls, 1);
    let mut limited_calls: u32 = 0;
    let limited: std::io::Result<u32> = retry_while_active(
        || {
            limited_calls += 1;
            assert!(limited_calls <= 4, "the first try and three retries are all there is");
            return Err(active());
        },
        3,
        delay,
    );
    assert!(limited.is_err());
    assert_eq!(limited_calls, 4, "the first try and three retries");
    let mut zero_calls: u32 = 0;
    let zero: std::io::Result<u32> = retry_while_active(
        || {
            zero_calls += 1;
            assert!(zero_calls <= 1, "a limit of zero allows no retry");
            return Err(active());
        },
        0,
        delay,
    );
    assert!(zero.is_err());
    assert_eq!(zero_calls, 1);
}

/// Both signature header spellings mark the prepared commit as signed, and a signature-looking message line does not.
#[test]
fn either_signature_header_marks_the_commit_signed() {
    let root: PathBuf = fixture("commit-preparation-headers");
    let repo: PathBuf = repository(root.as_path(), "repo");
    let tree: String = git_text(repo.as_path(), &["rev-parse", "HEAD^{tree}"]);
    let parent: String = git_text(repo.as_path(), &["rev-parse", "HEAD"]);
    let shadow: PathBuf = root.join("shadow");
    std::fs::create_dir(&shadow).expect("shadow");
    git(&shadow, &["init", "--bare", "--quiet", "--template="]);
    std::fs::write(
        shadow.join("objects").join("info").join("alternates"),
        format!("{}\n", repo.join(".git").join("objects").display()),
    )
    .expect("alternates");
    git(&shadow, &["symbolic-ref", "HEAD", "refs/heads/main"]);
    let commit_with = |extra: &str, message: &str| -> String {
        let raw: String = format!(
            "tree {}\nparent {}\nauthor A <a@example.invalid> 1 +0000\ncommitter A <a@example.invalid> 1 +0000\n{extra}\n{message}\n",
            tree.trim(),
            parent.trim()
        );
        let mut child = std::process::Command::new(REAL_GIT)
            .current_dir(&repo)
            .args(["hash-object", "-t", "commit", "-w", "--stdin"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .expect("hash-object");
        std::io::Write::write_all(&mut child.stdin.take().expect("stdin"), raw.as_bytes()).expect("raw commit");
        return String::from_utf8_lossy(child.wait_with_output().expect("output").stdout.as_slice()).trim().to_string();
    };
    let signed_with = |extra: &str, message: &str| -> bool {
        let oid: String = commit_with(extra, message);
        git(&shadow, &["update-ref", "refs/heads/main", oid.as_str()]);
        return read_prepared_commit(&git_context(), shadow.as_path()).expect("read").signed;
    };
    assert!(signed_with("gpgsig -----BEGIN PGP SIGNATURE-----\n -----END PGP SIGNATURE-----\n", "m"));
    assert!(signed_with("gpgsig-sha256 -----BEGIN PGP SIGNATURE-----\n -----END PGP SIGNATURE-----\n", "m"));
    assert!(!signed_with("", "gpgsig in the message\n\ngpgsig-sha256 too"));
    remove(root.as_path());
}

/// Each preparation failure displays its own words.
#[test]
fn each_preparation_failure_displays_its_own_words() {
    assert_eq!(PreparationError::Git(GitFailure(String::from("git words"))).to_string(), "git words");
}

/// The wait recognizes the occupied guard by its type: an error that only repeats the wording is final (issue 1346).
#[test]
fn an_error_with_the_guard_wording_but_not_its_type_is_not_retried() {
    let mut calls: u32 = 0;
    let waited: std::io::Result<u32> = retry_while_active(
        || {
            calls += 1;
            assert!(calls <= 1, "a look-alike error is returned at once");
            return Err(std::io::Error::other("a signal guard is already active in this process"));
        },
        5,
        std::time::Duration::from_millis(1),
    );
    assert!(waited.is_err());
    assert_eq!(calls, 1);
}

/// The shadow shows what a policy and a commit need: `HEAD` at the base, the upstream, the `onbranch:` include, and its
///  own Git directory.
#[test]
fn the_shadow_shows_head_upstream_include_and_git_dir() {
    let root: PathBuf = fixture("commit-preparation-shadow-view");
    let prepared: Fixture = prepared_fixture(root.as_path());
    let base: String = git_text(prepared.repo.as_path(), &["rev-parse", "HEAD"]);
    let shadow: String = format!("--git-dir={}", prepared.shadow.display());
    let in_shadow = |arguments: &[&str]| {
        let mut all: Vec<&str> = vec![shadow.as_str()];
        all.extend_from_slice(arguments);
        return git_text(prepared.repo.as_path(), all.as_slice());
    };
    assert_eq!(in_shadow(&["rev-parse", "HEAD"]).trim(), base);
    assert_eq!(in_shadow(&["rev-parse", "--abbrev-ref", "@{upstream}"]).trim(), "origin/main");
    assert_eq!(in_shadow(&["config", "--get", "x.v"]).trim(), "onbranch");
    assert_eq!(in_shadow(&["rev-parse", "--git-dir"]).trim(), prepared.shadow.display().to_string());
    remove(root.as_path());
}

/// A configured hook for every hook event, whatever its name, does not run in the native commit, and the commit
///  succeeds: the shadow's own config switches every event off.
#[cfg(unix)]
#[test]
fn a_configured_hook_for_every_event_does_not_run_in_the_native_commit() {
    let root: PathBuf = fixture("commit-preparation-no-hooks");
    let prepared: Fixture = prepared_fixture(root.as_path());
    let marker: PathBuf = root.join("hook-ran");
    for (index, event) in crate::hooks_off::HOOK_EVENTS.iter().enumerate() {
        let script: String = format!("#!/bin/sh\necho {event} >> '{}'\nexit 7\n", marker.display());
        let path: PathBuf = root.join(format!("hook-{index}"));
        crate::test_support::executable(path.as_path(), script.as_bytes());
        git(prepared.repo.as_path(), &["config", format!("hook.named-{index}.event").as_str(), event]);
        git(prepared.repo.as_path(), &["config", format!("hook.named-{index}.command").as_str(), path.to_str().expect("UTF-8")]);
    }
    prepare(&prepared, &["--quiet", "-m", "message"]).expect("no hook runs, so none can refuse the commit");
    assert!(!marker.exists(), "a hook ran: {:?}", std::fs::read_to_string(&marker));
    remove(root.as_path());
}