monochromatic-git-policy-cli 0.1.2

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
//! What:
//!  Each shipped policy's outcome from scripted facts,
//!  and which facts it asked for.
//! Why:
//!  A check that asks Git for nothing must start no process;
//!  a check whose fact could
//!      not be read must fail,
//!  not pass;
//!  and a content policy must never look clean where
//!      candidates exist but cannot be read.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! // expect(await checks.check('require-root', 'pre-forward')).toEqual({ kind: 'findings', findings: [] });
//! ```

/// The adapter under test,
///  the engine types it returns and the scripted facts.
use super::{ShippedChecks, shipped_checks};
use crate::candidate_prediction::CandidateRequest;
use crate::command_test_support::os_arguments;
use crate::diagnostics::EngineFailureCode;
use crate::policy_content::LifecycleContent;
use crate::policy_engine::{PolicyChecks, PolicyFinding, PolicyOutcome};
use crate::policy_registry::PolicyId;
use crate::policy_test_support::{
    ScriptedFacts, linked_worktree, main_worktree, outside_worktree, scripted_facts,
};
use crate::policy_trigger::Trigger;
use crate::rule_linked_worktree::{
    GuardedCommand, main_worktree_message, outside_worktree_message,
};
use crate::test_support::{fixture, remove};
use crate::worktree_identity::WorktreeIdentity;
use std::path::PathBuf;

/// The shipped checks over a command,
///  the given facts and no candidates.
fn checks(values: &[&str], facts: ScriptedFacts) -> ShippedChecks<ScriptedFacts> {
    return shipped_checks(
        facts,
        os_arguments(values),
        LifecycleContent::None,
        Vec::<PathBuf>::new(),
    );
}

/// Run one pre-forward check and return its outcome with the facts it asked for.
fn pre_forward(
    policy: PolicyId,
    values: &[&str],
    facts: ScriptedFacts,
) -> (PolicyOutcome, Vec<String>) {
    let mut shipped: ShippedChecks<ScriptedFacts> = checks(values, facts);
    let outcome: PolicyOutcome = shipped.check(policy, Trigger::PreForward);
    return (outcome, shipped.facts.asked);
}

/// The outcome "nothing found".
fn clean() -> PolicyOutcome {
    return PolicyOutcome::Findings(Vec::<PolicyFinding>::new());
}

/// The outcome "one finding with this code and message".
fn one(code: &'static str, message: &str) -> PolicyOutcome {
    return PolicyOutcome::Findings(vec![PolicyFinding {
        code,
        message: String::from(message),
        path: None,
        location: None,
        fix_available: false,
    }]);
}

/// Facts whose location is the given one.
fn located(location: crate::repository_location::RepositoryLocation) -> ScriptedFacts {
    let mut facts: ScriptedFacts = scripted_facts();
    facts.location = Ok(location);
    return facts;
}

/// Facts whose location could not be read.
fn unlocatable() -> ScriptedFacts {
    let mut facts: ScriptedFacts = scripted_facts();
    facts.location = Err(String::from("git could not be asked"));
    return facts;
}

/// The location is asked for once.
fn location_only() -> Vec<String> {
    return vec![String::from("location")];
}

/// require-root:
///  exempt commands ask nothing;
///  other commands pass at the top level and outside a worktree.
#[test]
fn require_root_passes_exempt_commands_and_the_top_level() {
    for values in [
        vec![],
        vec!["--version"],
        vec!["help"],
        vec!["init"],
        vec!["clone", "url"],
        vec!["config", "--global", "user.name", "x"],
        vec!["config", "list"],
    ] {
        assert_eq!(
            pre_forward(PolicyId::RequireRoot, values.as_slice(), unlocatable()),
            (clean(), Vec::<String>::new()),
            "{values:?}"
        );
    }
    for location in [
        main_worktree("/r", ""),
        linked_worktree("/r", "/w"),
        outside_worktree(),
    ] {
        assert_eq!(
            pre_forward(PolicyId::RequireRoot, &["status"], located(location)),
            (clean(), location_only())
        );
    }
}

/// require-root:
///  below the top level the finding names the root and the directory Git reported.
#[test]
fn require_root_rejects_a_directory_below_the_top_level() {
    assert_eq!(
        pre_forward(
            PolicyId::RequireRoot,
            &["status"],
            located(main_worktree("/r", "sub/dir/"))
        ),
        (
            one(
                "not-at-root",
                "cli-git: not at the root of the git repository. Repo root is /r but effective cwd \
                 is /r/sub/dir. Tip: cd to /r or pass -C /r before the subcommand."
            ),
            location_only()
        )
    );
    // A repository-local `git config` is not exempt.
    let (outcome, _) = pre_forward(
        PolicyId::RequireRoot,
        &["config", "user.name", "x"],
        located(main_worktree("/r", "a/")),
    );
    assert!(matches!(outcome, PolicyOutcome::Findings(found) if found.len() == 1));
    assert_eq!(
        pre_forward(PolicyId::RequireRoot, &["status"], unlocatable()),
        (
            PolicyOutcome::Failed {
                code: EngineFailureCode::ContentUnavailable,
                message: String::from("git could not be asked"),
                path: None,
            },
            location_only()
        )
    );
}

/// require-root as a direct check has no command to exempt:
///  it always measures.
#[test]
fn require_root_direct_check_always_measures() {
    for values in [vec![], vec!["-C", "dir"]] {
        let mut at_root: ShippedChecks<ScriptedFacts> =
            checks(values.as_slice(), located(main_worktree("/r", "")));
        assert_eq!(
            at_root.check(PolicyId::RequireRoot, Trigger::DirectCheck),
            clean()
        );
        assert_eq!(at_root.facts.asked, location_only());
        let mut below: ShippedChecks<ScriptedFacts> =
            checks(values.as_slice(), located(main_worktree("/r", "sub/")));
        assert!(matches!(
            below.check(PolicyId::RequireRoot, Trigger::DirectCheck),
            PolicyOutcome::Findings(found) if found.len() == 1 && found[0].code == "not-at-root"
        ));
    }
}

/// linked-worktree-only:
///  harmless commands ask nothing;
///  guarded ones are judged by the worktree kind.
#[test]
fn linked_worktree_judges_guarded_commands_by_worktree_kind() {
    for values in [vec!["status"], vec!["clean", "-n"], vec!["reset", "--soft"]] {
        assert_eq!(
            pre_forward(
                PolicyId::LinkedWorktreeOnly,
                values.as_slice(),
                unlocatable()
            ),
            (clean(), Vec::<String>::new()),
            "{values:?}"
        );
    }
    assert_eq!(
        pre_forward(
            PolicyId::LinkedWorktreeOnly,
            &["reset", "--hard"],
            located(main_worktree("/r", ""))
        ),
        (
            one(
                "linked-worktree-required",
                main_worktree_message(GuardedCommand::Reset)
            ),
            location_only()
        )
    );
    assert_eq!(
        pre_forward(
            PolicyId::LinkedWorktreeOnly,
            &["stash"],
            located(outside_worktree())
        ),
        (
            one(
                "linked-worktree-required",
                outside_worktree_message(GuardedCommand::Stash)
            ),
            location_only()
        )
    );
    assert_eq!(
        pre_forward(
            PolicyId::LinkedWorktreeOnly,
            &["clean", "-fd"],
            located(linked_worktree("/r", "/w"))
        ),
        (clean(), location_only())
    );
    assert_eq!(
        pre_forward(
            PolicyId::LinkedWorktreeOnly,
            &["clean", "-fd"],
            unlocatable()
        ),
        (
            PolicyOutcome::Failed {
                code: EngineFailureCode::ContentUnavailable,
                message: String::from("git could not be asked"),
                path: None,
            },
            location_only()
        )
    );
}

/// linked-worktree-only:
///  a main worktree whose Git directory lies under an exempt tool cache passes.
#[test]
fn linked_worktree_exempts_an_allowed_tool_cache() {
    let root: PathBuf = fixture("checks-tool-cache");
    let cache: PathBuf = root.join("cache");
    let clone: PathBuf = cache.join("clone");
    std::fs::create_dir_all(clone.join(".git")).expect("cache clone");
    let mut facts: ScriptedFacts = scripted_facts();
    facts.location = Ok(crate::repository_location::RepositoryLocation {
        identity: WorktreeIdentity::MainWorktree {
            common_dir: clone.join(".git"),
            git_dir: clone.join(".git"),
            worktree_root: clone,
        },
        prefix: Vec::<u8>::new(),
    });
    let mut exempt: ShippedChecks<ScriptedFacts> = checks(&["reset", "--hard"], facts.clone());
    exempt.allowed_worktree_dirs = vec![cache];
    assert_eq!(
        exempt.check(PolicyId::LinkedWorktreeOnly, Trigger::PreForward),
        clean()
    );
    // The same repository without the exemption is an ordinary main worktree.
    let mut guarded: ShippedChecks<ScriptedFacts> = checks(&["reset", "--hard"], facts);
    assert_eq!(
        guarded.check(PolicyId::LinkedWorktreeOnly, Trigger::PreForward),
        one(
            "linked-worktree-required",
            main_worktree_message(GuardedCommand::Reset)
        )
    );
    remove(root.as_path());
}

/// branch-worktree-only:
///  explicit creation is rejected without a query;
///  a bare name asks once.
#[test]
fn branch_worktree_rejects_creation_and_guessed_creation() {
    assert_eq!(
        pre_forward(PolicyId::BranchWorktreeOnly, &["status"], scripted_facts()),
        (clean(), Vec::<String>::new())
    );
    assert_eq!(
        pre_forward(
            PolicyId::BranchWorktreeOnly,
            &["switch", "-c", "topic"],
            scripted_facts()
        ),
        (
            one(
                "branch-creation-requires-worktree",
                "cli-git: git switch branch creation is rejected in the current worktree. Use \
                 `git worktree add -b <branch> <path> [<start-point>]` so new branch work starts \
                 in its own checkout, or pass --no-enforce-worktree-branch to bypass for this \
                 invocation."
            ),
            Vec::<String>::new()
        )
    );
    let asked: Vec<String> = vec![String::from("remote-guess:topic")];
    assert_eq!(
        pre_forward(
            PolicyId::BranchWorktreeOnly,
            &["switch", "topic"],
            scripted_facts()
        ),
        (clean(), asked.clone())
    );
    let mut guessing: ScriptedFacts = scripted_facts();
    guessing.remote_guess = Ok(true);
    assert_eq!(
        pre_forward(
            PolicyId::BranchWorktreeOnly,
            &["checkout", "topic"],
            guessing
        ),
        (
            one(
                "branch-creation-requires-worktree",
                "cli-git: git checkout for topic branch creation is rejected in the current \
                 worktree. Use `git worktree add -b <branch> <path> [<start-point>]` so new \
                 branch work starts in its own checkout, or pass --no-enforce-worktree-branch to \
                 bypass for this invocation."
            ),
            asked.clone()
        )
    );
    let mut failing: ScriptedFacts = scripted_facts();
    failing.remote_guess = Err(String::from("no git"));
    assert_eq!(
        pre_forward(PolicyId::BranchWorktreeOnly, &["switch", "topic"], failing),
        (
            PolicyOutcome::Failed {
                code: EngineFailureCode::ContentUnavailable,
                message: String::from("no git"),
                path: None,
            },
            asked
        )
    );
}

/// add-explicit:
///  decided from arguments alone.
#[test]
fn add_explicit_never_asks_for_a_fact() {
    assert_eq!(
        pre_forward(PolicyId::AddExplicit, &["add", "file"], unlocatable()),
        (clean(), Vec::<String>::new())
    );
    let (outcome, asked) = pre_forward(PolicyId::AddExplicit, &["add", "-A"], unlocatable());
    assert!(matches!(
        outcome,
        PolicyOutcome::Findings(found)
            if found.len() == 1 && found[0].code == "bulk-add-rejected" && found[0].message.contains("(-A)")
    ));
    assert_eq!(asked, Vec::<String>::new());
}

/// The candidates of `git add file`.
fn add_candidates() -> LifecycleContent {
    return LifecycleContent::Requested(CandidateRequest::Add(os_arguments(&["file"])));
}

/// The content-unavailable failure of candidates these scripted facts cannot prepare.
fn unprepared() -> PolicyOutcome {
    return PolicyOutcome::Failed {
        code: EngineFailureCode::ContentUnavailable,
        message: String::from("the scripted facts prepare no candidates"),
        path: None,
    };
}

/// Content policies report nothing without candidates;
///  with candidates the ported ones
/// read them and the unported one refuses without reading.
///  The dependent-version policy
/// reads nothing for `git add`,
///  the one forwarded command with candidates,
///  as the installed
/// wrapper's policy plans only for a forwarded `commit`.
#[test]
fn content_policies_follow_the_lifecycle_content() {
    for policy in [
        PolicyId::FinalNewline,
        PolicyId::MarkdownAutofix,
        PolicyId::ForbiddenRootContext,
        PolicyId::DependentVersionBump,
        PolicyId::ForbiddenStrings,
    ] {
        for trigger in [
            Trigger::PreForward,
            Trigger::DirectCheck,
            Trigger::DirectFix,
        ] {
            let mut without: ShippedChecks<ScriptedFacts> = checks(&["status"], unlocatable());
            assert_eq!(without.check(policy, trigger), clean(), "{policy:?}");
            assert_eq!(without.facts.asked, Vec::<String>::new());
        }
    }
    let mut with: ShippedChecks<ScriptedFacts> = checks(&["add", "file"], unlocatable());
    with.candidates = add_candidates();
    assert_eq!(
        with.check(PolicyId::DependentVersionBump, Trigger::PreForward),
        clean()
    );
    assert_eq!(with.facts.asked, Vec::<String>::new());
    for policy in [
        PolicyId::FinalNewline,
        PolicyId::MarkdownAutofix,
        PolicyId::ForbiddenRootContext,
        PolicyId::ForbiddenStrings,
        PolicyId::DependentVersionBump,
    ] {
        for trigger in [
            Trigger::PreForward,
            Trigger::DirectCheck,
            Trigger::DirectFix,
        ] {
            if policy == PolicyId::DependentVersionBump && trigger == Trigger::PreForward {
                continue;
            }
            let mut read: ShippedChecks<ScriptedFacts> = checks(&["add", "file"], unlocatable());
            read.candidates = add_candidates();
            assert_eq!(read.check(policy, trigger), unprepared(), "{policy:?}");
            // A second content policy shares the one failed attempt and does not retry it.
            assert_eq!(read.check(policy, trigger), unprepared(), "{policy:?}");
            assert_eq!(read.facts.asked, vec![String::from("candidates")]);
        }
    }
    // A command policy is not a content policy: the lifecycle content does not touch it.
    let mut command: ShippedChecks<ScriptedFacts> = checks(&["add", "file"], scripted_facts());
    command.candidates = add_candidates();
    assert_eq!(
        command.check(PolicyId::AddExplicit, Trigger::PreForward),
        clean()
    );
    assert_eq!(command.facts.asked, Vec::<String>::new());
}