Skip to main content

git_policy_cli/
event_hints.rs

1//! What:
2//!  The hint that follows a finding, an engine failure or a warn-unsafe notice: a guess at what the person was
3//!  trying to do, and the concrete next step.
4//! Why:
5//!  A block that only states a rule leaves the next move to guesswork. Every block and every divergence from real
6//!  Git's behavior names the likely intent and a way forward, so a rejected command is a step toward the goal.
7//!  Messages built with their own hint (the discard, branch, add, root and commit-only rejections) are listed as
8//!  self-hinted, and a guard test fails when a code has neither.
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! const hint = hints.get(`${policy}/${code}`); if (hint) event.hint = hint;
13//! ```
14
15use super::json_record::quote;
16
17/// The policy codes whose messages already carry their own intent guess and next step.
18pub const SELF_HINTED: &[(&str, &str)] = &[
19    ("require-root", "not-at-root"),
20    ("linked-worktree-only", "linked-worktree-required"),
21    ("branch-worktree-only", "branch-creation-requires-worktree"),
22];
23
24/// What:
25///  The hint for a policy finding, or none when the message carries its own.
26///  `&'static str` is text compiled into the program.
27/// Why:
28///   A finding's wording is the rule; the hint is the guess about the goal and the way to reach it.
29///
30/// In TS you'd write (pseudocode):
31/// ```ts
32/// function findingHint(policy: string, code: string, fixAvailable: boolean): string | undefined;
33/// ```
34pub fn finding_hint(policy: &str, code: &str, fix_available: bool) -> Option<&'static str> {
35    match (policy, code, fix_available) {
36        ("add-explicit", "bulk-add-rejected", _) => {
37            return Some(
38                "Hint: if you meant to stage everything you changed, run `git status --short` to list it and name \
39                 each path, as in `git add -- <path> <path>`; if you meant only files git already tracks, name those \
40                 paths the same way.",
41            );
42        }
43        ("final-newline", "noncanonical-final-newline", true) => {
44            return Some(
45                "Hint: if you are committing or checking this file, a commit corrects the ending for you; \
46                 to correct it now without committing, run `git cli-git fix -- <path>`.",
47            );
48        }
49        ("final-newline", "noncanonical-final-newline", false) => {
50            return Some(
51                "Hint: if you are committing or checking this file, edit it so it ends with exactly one newline, \
52                 then stage it again.",
53            );
54        }
55        ("markdown/autofix", "markdown-autofix", _) => {
56            return Some(
57                "Hint: if you are committing this Markdown, the commit applies the linter's corrections itself; \
58                 to apply them now, run `git cli-git fix -- <path>`.",
59            );
60        }
61        ("markdown/autofix", "markdown-violation", _) => {
62            return Some(
63                "Hint: if you are committing this Markdown, the linter cannot repair this rule by itself; \
64                 edit the file at the reported line and column, stage it again, and retry.",
65            );
66        }
67        ("mono/forbidden-root-context", "root-context-forbidden", _) => {
68            return Some(
69                "Hint: if you meant to keep project notes or terms for later readers, put them in a file under doc/; \
70                 to drop CONTEXT.md from this commit and keep the file on disk, run `git rm --cached CONTEXT.md`.",
71            );
72        }
73        ("mono/dependent-version-bump", "dependent-version-stale", _) => {
74            return Some(
75                "Hint: if you changed a package that others depend on, raise its dependents' version ranges to match \
76                 the new version in the same commit, then stage those files; `git cli-git fix -- <path>` applies the \
77                 correction when one is available.",
78            );
79        }
80        ("mono/dependent-version-bump", "dependent-version-unsupported", _) => {
81            return Some(
82                "Hint: if you edited a dependency declaration of a shape this check does not read, update the \
83                 dependents by hand in the same commit; the message names the file.",
84            );
85        }
86        ("security/forbidden-strings", "forbidden-string", _) => {
87            return Some(
88                "Hint: if you are committing text or a path that contains a secret or a banned term, remove or \
89                 replace it where the message points and stage the file again; if you believe the rule is wrong, \
90                 review it in the rules file named by the configuration instead of splitting the commit.",
91            );
92        }
93        _ => return None,
94    }
95}
96
97/// What:
98///  The hint for an engine failure, by the code's wire spelling.
99/// Why:
100///   An engine failure stops the command before Git runs; the person needs to know whether to retry, fix a file, or
101///  report a defect.
102///
103/// In TS you'd write (pseudocode):
104/// ```ts
105/// function engineFailureHint(code: string): string | undefined;
106/// ```
107pub fn engine_failure_hint(code: &str) -> Option<&'static str> {
108    match code {
109        "config-invalid" => {
110            return Some(
111                "Hint: if you just edited cli-git.config.jsonc, fix the key the message names or revert the edit; \
112                 an unknown key, a wrong type or an unknown policy id fails before any policy runs.",
113            );
114        }
115        "core-incomplete" => {
116            return Some(
117                "Hint: if another session was changing the repository at the same moment (a commit, a checkout or a \
118                 rebase running elsewhere), run the command again; if it repeats, run `git status` to check that the \
119                 repository is healthy.",
120            );
121        }
122        "content-unavailable" => {
123            return Some(
124                "Hint: if you are committing or pushing content that is not in this clone (a missing object, a \
125                 shallow history, or a file removed during the command), fetch the history with `git fetch`, make \
126                 sure the files exist, and retry.",
127            );
128        }
129        "policy-incomplete" => {
130            return Some(
131                "Hint: if you are committing or pushing, a policy could not finish reading the content, so it \
132                 decided nothing; fix the cause the message names (an unreadable file, a path with a line break) \
133                 and retry.",
134            );
135        }
136        "patch-invalid" | "patch-conflict" => {
137            return Some(
138                "Hint: if you are committing files that changed while the command ran or that another policy also \
139                 rewrites, save your edits, run `git cli-git fix -- <path>` to apply the corrections, review the \
140                 result with `git diff`, and commit again.",
141            );
142        }
143        "fix-cycle" | "fix-pass-limit" => {
144            return Some(
145                "Hint: two corrections keep undoing each other on this file; apply one of them by hand, stage the \
146                 file, and commit again. Report the pair of policies if the file is ordinary text.",
147            );
148        }
149        "transaction-failed" => {
150            return Some(
151                "Hint: if you were committing, run `git status` and `git log --oneline -3` to see whether the \
152                 commit landed before you retry; staged files stay staged unless the message says otherwise, and the \
153                 message names the step that failed.",
154            );
155        }
156        "index-lock-unproven-owner" => {
157            return Some(
158                "Hint: if no other Git command is running in this repository, a crashed command left the lock \
159                 behind: check with `ps` that no Git process uses this repository, then remove the .git/index.lock \
160                 file the message names and retry.",
161            );
162        }
163        "legacy-config-ignored" => {
164            return Some(
165                "Hint: if you are still keeping the old configuration files, delete them once \
166                 cli-git.config.jsonc holds the settings; they are no longer read.",
167            );
168        }
169        _ => return None,
170    }
171}
172
173/// What:
174///  The hint for a warn-unsafe notice.
175/// Why:
176///   The person who set a policy to warn wanted commits to keep flowing; the notice says what that costs and what to
177///  choose instead.
178///
179/// In TS you'd write (pseudocode):
180/// ```ts
181/// const warnUnsafeHint: string;
182/// ```
183pub const WARN_UNSAFE_HINT: &str = "Hint: if you set it to warn to keep commits flowing, note that this policy \
184     changes or misses content when it only warns; set its severity to error to enforce it, or to off to disable it, \
185     in cli-git.config.jsonc.";
186
187/// The hint that follows a post-commit gate block.
188pub const POST_COMMIT_BLOCKED_HINT: &str = "Hint: if you wanted this commit backed up, fix what the gate reported \
189     and run `git push` yourself; the commit stays in your local history until then.";
190
191/// The hint that follows a replay that dropped signature headers.
192pub const REPLAY_HEADERS_DROPPED_HINT: &str = "Hint: if this commit must carry your original signature, run \
193     `git commit --amend --no-edit -S` after the replay to sign the replayed commit again.";
194
195/// What:
196///  Append the `hint` field to a JSON event line when a hint exists.
197///  `&mut String` lends the line for appending.
198/// Why:
199///   The `message` field stays byte-identical to the retired wrapper's; the hint is an additive field that readers of
200///  the line see without any change to the message.
201///
202/// In TS you'd write (pseudocode):
203/// ```ts
204/// if (hint !== undefined) event.hint = hint;
205/// ```
206pub fn push_hint_field(line: &mut String, hint: Option<&str>) {
207    if let Some(text) = hint {
208        line.push_str(",\"hint\":");
209        line.push_str(quote(text).as_str());
210    }
211}
212
213/// The guard that every code has a hint or its own.
214#[cfg(test)]
215#[path = "event_hints_tests.rs"]
216mod tests;