monochromatic-git-policy-cli 0.5.28

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
//! What:
//!  Which `git commit` command lines the resident service lands, and the message such a line stands for.
//! Why:
//!  The service lands the scoped commit an agent or a person types most (`git commit -m <message> -- <paths>`), with the
//!  options that only shape the message or the identity: `-F <file>`, `--author`, `--date`, `--trailer`, `--cleanup`,
//!  `--allow-empty-message`, `-s`, `--amend` and `--reset-author`. Every other option (editor, signing, templates) still
//!  goes through the transaction until the service covers it, so this module answers "is this line one the service covers" before anything
//!  is prepared, and builds the message with the clean-up Git applies when no editor opens.
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! const parsed = parseServiceCommit(args); // undefined when the line needs native git commit
//! ```

use std::ffi::OsString;

/// What a covered command line asked for.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ServiceCommitArgs {
    /// The `-m` texts, in order; each is a paragraph.
    pub messages: Vec<String>,
    /// The `-F` file, read by the caller relative to the working directory; never standard input.
    pub file: Option<OsString>,
    /// Whether `--quiet` was given.
    pub quiet: bool,
    /// The `--author` text, always of the form `Name <email>`.
    pub author: Option<String>,
    /// The `--date` text, left to Git to parse.
    pub date: Option<String>,
    /// The `--trailer` texts, in order.
    pub trailers: Vec<String>,
    /// Whether `--cleanup=verbatim` keeps the message exactly as given.
    pub verbatim: bool,
    /// Whether an empty message is allowed.
    pub allow_empty_message: bool,
    /// Whether `-s` asks for a `Signed-off-by` trailer of the committer.
    pub signoff: bool,
    /// The commit whose message `-C` reuses, with its authorship.
    pub reuse: Option<String>,
    /// The commit `--fixup` or `--squash` names, and which of the two.
    pub fixup: Option<(FixupKind, String)>,
    /// Whether `--cleanup=strip` also removes comment lines.
    pub strip: bool,
    /// Whether `--no-edit` was given.
    pub no_edit: bool,
    /// Whether `--amend` replaces the last commit: its parents, its message (without a message option) and its author.
    pub amend: bool,
    /// Whether `--reset-author` makes the committer the author of an amend, with a new author date.
    pub reset_author: bool,
}

/// Which message prefix `--fixup` and `--squash` make.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FixupKind {
    /// `--fixup=<commit>`: the message is `fixup! <subject>`. (`--squash` always opens an editor, so it is not covered.)
    Fixup,
}

/// Short option letters that take no value and change nothing the service must do.
const FLAG_LETTERS: [char; 7] = ['q', 'n', 'o', 'a', 's', 'i', 'p'];

/// Long options that take no value and change nothing the service must do.
const FLAG_WORDS: [&str; 16] = [
    "--quiet", "--no-verify", "--only", "--no-status", "--no-post-rewrite", "--no-edit", "--no-gpg-sign", "--all", "--signoff", "--allow-empty",
    "--amend", "--reset-author", "--include", "--patch", "--interactive", "--pathspec-file-nul",
];

/// Long options that take one value, with the field they fill.
const VALUE_WORDS: [&str; 9] = ["--message", "--file", "--author", "--date", "--trailer", "--cleanup", "--reuse-message", "--fixup", "--pathspec-from-file"];

/// The value of a long option given as `--name=value` or `--name value`; `index` moves past a separate value.
fn long_value<'a>(token: &'a str, name: &str, arguments: &'a [OsString], index: &mut usize) -> Option<Option<&'a str>> {
    if token == name {
        let value: &str = arguments.get(*index)?.to_str()?;
        *index += 1;
        return Some(Some(value));
    }
    return token.strip_prefix(name).and_then(|rest| { return rest.strip_prefix('='); }).map(Some);
}

/// What:
///  Reads the arguments after `commit` and says whether the service covers them.
/// Why:
///   Anything not listed here is refused, so a new Git option is never silently dropped.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// parseServiceCommit(args)
/// ```
pub fn parse_service_commit(arguments: &[OsString]) -> Option<ServiceCommitArgs> {
    let mut parsed: ServiceCommitArgs = ServiceCommitArgs::default();
    let mut index: usize = 0;
    while index < arguments.len() {
        let token: &str = arguments[index].to_str()?;
        index += 1;
        if token == "--" {
            break;
        }
        if !token.starts_with('-') || token == "-" {
            // A pathspec given without the separator; the region already holds it.
            continue;
        }
        if token.starts_with("--") {
            if FLAG_WORDS.contains(&token) {
                parsed.quiet |= token == "--quiet";
                parsed.signoff |= token == "--signoff";
                parsed.no_edit |= token == "--no-edit";
                parsed.amend |= token == "--amend";
                parsed.reset_author |= token == "--reset-author";
            } else if token == "--allow-empty-message" {
                parsed.allow_empty_message = true;
            } else {
                let mut matched: bool = false;
                for name in VALUE_WORDS {
                    let Some(Some(value)) = long_value(token, name, arguments, &mut index) else { continue };
                    matched = true;
                    match name {
                        "--message" => parsed.messages.push(value.to_string()),
                        "--file" => parsed.file = Some(OsString::from(value)),
                        "--author" => parsed.author = Some(value.to_string()),
                        "--date" => parsed.date = Some(value.to_string()),
                        "--trailer" => parsed.trailers.push(value.to_string()),
                        "--reuse-message" => parsed.reuse = Some(value.to_string()),
                        // The private index already holds the paths the file names; the message does not depend on them.
                        "--pathspec-from-file" => {}
                        "--fixup" => {
                            // `amend:` and `reword:` open an editor or change parents; only a plain commit name is covered.
                            if value.contains(':') || value.is_empty() {
                                return None;
                            }
                            parsed.fixup = Some((FixupKind::Fixup, value.to_string()));
                        }
                        _ => match value {
                            "verbatim" => parsed.verbatim = true,
                            "strip" => parsed.strip = true,
                            "whitespace" | "default" => {
                                parsed.verbatim = false;
                                parsed.strip = false;
                            }
                            _ => return None,
                        },
                    }
                    break;
                }
                if !matched {
                    return None;
                }
            }
        } else {
            let letters: Vec<char> = token.chars().skip(1).collect();
            let mut at: usize = 0;
            while at < letters.len() {
                let letter: char = letters[at];
                at += 1;
                if letter == 'm' || letter == 'F' || letter == 'C' {
                    let inline: String = letters[at..].iter().collect();
                    let value: String = if inline.is_empty() {
                        index += 1;
                        arguments.get(index - 1)?.to_str()?.to_string()
                    } else {
                        inline
                    };
                    match letter {
                        'm' => parsed.messages.push(value),
                        'F' => parsed.file = Some(OsString::from(value)),
                        _ => parsed.reuse = Some(value),
                    }
                    at = letters.len();
                } else if FLAG_LETTERS.contains(&letter) {
                    parsed.quiet |= letter == 'q';
                    parsed.signoff |= letter == 's';
                } else {
                    return None;
                }
            }
        }
    }
    // Standard input is read by Git itself; a message from both places is Git's to refuse.
    let sources: usize = usize::from(!parsed.messages.is_empty())
        + usize::from(parsed.file.is_some())
        + usize::from(parsed.reuse.is_some())
        + usize::from(parsed.fixup.is_some());
    // An amend with no message option and `--no-edit` keeps the message of the commit it replaces; with neither, an editor
    //  opens, which is not covered.
    let has_text: bool = sources == 1 || (parsed.amend && parsed.no_edit && sources == 0);
    let author_ok: bool = parsed.author.as_deref().is_none_or(|author| { return author.contains('<') && author.trim_end().ends_with('>'); });
    // `-C` takes the author and its date from the reused commit, and `--reset-author` is not covered.
    let reuse_ok: bool = parsed.reuse.is_none() || (parsed.author.is_none() && parsed.date.is_none());
    // `--reset-author` names its own author, so it is covered only for an amend that sets no author, no date and no reused commit.
    let reset_ok: bool = !parsed.reset_author || (parsed.amend && parsed.reuse.is_none() && parsed.author.is_none() && parsed.date.is_none());
    return if has_text && reuse_ok && reset_ok && author_ok && parsed.file.as_deref().is_none_or(|file| { return file != "-"; }) { Some(parsed) } else { None };
}

/// Long options with no value that never decide whether an editor opens.
const NEUTRAL_LONG: [&str; 15] = [
    "--quiet", "--no-verify", "--only", "--no-status", "--no-post-rewrite", "--no-gpg-sign", "--all", "--signoff", "--allow-empty",
    "--amend", "--reset-author", "--allow-empty-message", "--verbose", "--include", "--pathspec-file-nul",
];

/// Long options with a value that never decide whether an editor opens.
const NEUTRAL_VALUE_LONG: [&str; 7] = ["--author", "--date", "--trailer", "--cleanup", "--gpg-sign", "--template", "--pathspec-from-file"];

/// What:
///  Whether `git commit` with these arguments may open an editor.
/// Why:
///   The answer decides what happens to a commit Git built when the branch moved meanwhile: with no editor it is built
///  again on the new tip, with an editor the typed message is saved for the person instead of being lost. It errs towards
///  "may open": an option this reading does not know, or a spelling Git accepts as an abbreviation, counts as an editor,
///  because a message saved without need costs nothing and a message lost costs the person's typing.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// opensEditor(args)
/// ```
pub fn opens_editor(arguments: &[OsString]) -> bool {
    let mut message_source: bool = false;
    let mut edit: Option<bool> = None;
    let mut index: usize = 0;
    while index < arguments.len() {
        let Some(token) = arguments[index].to_str() else { return true };
        index += 1;
        if token == "--" {
            break;
        }
        if !token.starts_with('-') || token == "-" {
            continue;
        }
        if let Some(long) = token.strip_prefix("--") {
            let (name, value): (&str, Option<&str>) = match long.split_once('=') {
                Some((name, value)) => (name, Some(value)),
                None => (long, None),
            };
            let dashed: String = format!("--{name}");
            let takes_value: bool = ["--message", "--file", "--reuse-message", "--reedit-message", "--fixup", "--squash"].contains(&dashed.as_str())
                || NEUTRAL_VALUE_LONG.contains(&dashed.as_str());
            // A separate value is the next token, except for the options whose value may be attached only.
            let detached: Option<&str> = if takes_value && value.is_none() && !["--gpg-sign", "--squash"].contains(&dashed.as_str()) {
                index += 1;
                arguments.get(index - 1).and_then(|next| { return next.to_str(); })
            } else {
                None
            };
            let given: Option<&str> = value.or(detached);
            match dashed.as_str() {
                "--edit" => edit = Some(true),
                "--no-edit" => edit = Some(false),
                "--message" | "--file" | "--reuse-message" => message_source = true,
                "--reedit-message" | "--squash" => return true,
                "--fixup" => {
                    if given.is_none_or(|text| { return text.contains(':'); }) {
                        return true;
                    }
                    message_source = true;
                }
                other if NEUTRAL_LONG.contains(&other) || NEUTRAL_VALUE_LONG.contains(&other) => {}
                _ => return true,
            }
        } else {
            let letters: Vec<char> = token.chars().skip(1).collect();
            let mut at: usize = 0;
            while at < letters.len() {
                let letter: char = letters[at];
                at += 1;
                match letter {
                    'e' => edit = Some(true),
                    'c' => return true,
                    'm' | 'F' | 'C' | 't' => {
                        message_source |= letter != 't';
                        if at == letters.len() {
                            index += 1;
                        }
                        at = letters.len();
                    }
                    'S' => at = letters.len(),
                    'q' | 'n' | 'o' | 'a' | 's' | 'v' | 'i' => {}
                    _ => return true,
                }
            }
        }
    }
    return match edit {
        Some(wanted) => wanted,
        None => !message_source,
    };
}

/// What:
///  The commit message Git makes of the given texts when no editor opens.
/// Why:
///   Each text is a paragraph; Git strips trailing whitespace from every line, drops leading and trailing blank lines,
///  squeezes runs of blank lines into one and ends the message with a newline. An empty result is no message.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// cleanupMessage(['subject', 'body'])
/// ```
pub fn cleanup_message(messages: &[String]) -> Option<String> {
    let joined: String = messages.join("\n\n");
    let mut lines: Vec<&str> = Vec::new();
    let mut previous_blank: bool = true;
    for line in joined.split('\n') {
        let trimmed: &str = line.trim_end();
        let blank: bool = trimmed.is_empty();
        if blank && previous_blank {
            continue;
        }
        lines.push(trimmed);
        previous_blank = blank;
    }
    while lines.last().is_some_and(|line| { return line.is_empty(); }) {
        lines.pop();
    }
    if lines.is_empty() {
        return None;
    }
    return Some(format!("{}\n", lines.join("\n")));
}

/// Long options that name where the message comes from, or edit it, or add to it.
const MESSAGE_VALUE_LONG: [&str; 5] = ["--message", "--file", "--template", "--trailer", "--cleanup"];

/// Long options without a value that open the editor or add a sign-off.
const MESSAGE_FLAG_LONG: [&str; 4] = ["--edit", "--no-edit", "--signoff", "--no-signoff"];

/// Long options that take the author, or the parents, or the whole commit from another commit.
const BORROWING_LONG: [&str; 5] = ["--reedit-message", "--reuse-message", "--squash", "--fixup", "--amend"];

/// What:
///  The arguments of a commit Git built, rewritten so that the message the person already typed is used as it is and no
///  editor opens.
/// Why:
///   After the editor has run the message is fixed, so a commit built on a tip that has since moved is built again from
///  `-F <file>` with the message kept verbatim. A line that takes its author or its parents from another commit (`-c`, `-C`,
///  `--fixup`, `--squash`, `--amend`) cannot be rebuilt that way, and an abbreviated option that may be one of the dropped
///  ones is not guessed at: both give nothing, and the caller saves the message and stops.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// withFixedMessage(args, subcommandIndex, file) // undefined when the line cannot be rebuilt from the message alone
/// ```
pub fn with_fixed_message(arguments: &[OsString], subcommand_index: usize, file: &std::path::Path) -> Option<Vec<OsString>> {
    let text: Vec<String> = arguments.iter().map(|token| { return token.to_string_lossy().into_owned(); }).collect();
    let region: Vec<String> = super::commit_args::normalise_commit_args(text.get(subcommand_index + 1..)?);
    let split: usize = super::commit_args::separator_index(region.as_slice()).unwrap_or(region.len());
    let (options, tail): (&[String], &[String]) = region.split_at(split);
    let mut kept: Vec<OsString> = arguments[..=subcommand_index].to_vec();
    let mut index: usize = 0;
    while index < options.len() {
        let token: &str = options[index].as_str();
        index += 1;
        if let Some(long) = token.strip_prefix("--") {
            let (name, attached): (String, bool) = match long.split_once('=') {
                Some((name, _)) => (format!("--{name}"), true),
                None => (format!("--{long}"), false),
            };
            let all: Vec<&str> = MESSAGE_VALUE_LONG.iter().chain(&MESSAGE_FLAG_LONG).chain(&BORROWING_LONG).copied().collect();
            if BORROWING_LONG.contains(&name.as_str()) || (!all.contains(&name.as_str()) && all.iter().any(|known| { return known.starts_with(name.as_str()); })) {
                return None;
            }
            if MESSAGE_VALUE_LONG.contains(&name.as_str()) {
                if !attached {
                    index += 1;
                }
                continue;
            }
            if MESSAGE_FLAG_LONG.contains(&name.as_str()) {
                continue;
            }
            kept.push(OsString::from(token));
            continue;
        }
        if token.starts_with('-') && token.len() > 1 {
            let mut cluster: String = String::from("-");
            let mut value_next: bool = false;
            let letters: Vec<char> = token.chars().skip(1).collect();
            for (at, letter) in letters.iter().enumerate() {
                match letter {
                    'c' | 'C' => return None,
                    'm' | 'F' | 't' => value_next = true,
                    'e' | 's' => {}
                    'S' => {
                        cluster.extend(letters[at..].iter());
                        break;
                    }
                    other => cluster.push(*other),
                }
            }
            if cluster != "-" {
                kept.push(OsString::from(cluster));
            }
            if value_next {
                index += 1;
            }
            continue;
        }
        kept.push(OsString::from(token));
    }
    kept.push(OsString::from("-F"));
    kept.push(file.as_os_str().to_os_string());
    kept.push(OsString::from("--cleanup=verbatim"));
    kept.push(OsString::from("--no-edit"));
    kept.extend(tail.iter().map(OsString::from));
    return Some(kept);
}

/// Argument controls stay out of the release executable.
#[cfg(test)]
#[path = "service_commit_args_tests.rs"]
mod tests;