Skip to main content

gitpoulpi_core/domain/rewrite/
recipe.rs

1//! The recipe: a scope, an ordered list of rules and run options. The same
2//! value is TOML on disk (shared in the repository or only for the user),
3//! JSON on the wire, and what the TUI workbench edits.
4//!
5//! [`validate_recipe`] is the one pure check the editor, the daemon and the
6//! CLI all run, so a recipe the editor accepts is a recipe the engine accepts.
7
8use std::collections::BTreeMap;
9use std::fmt;
10
11use serde::{Deserialize, Serialize};
12
13use super::dates::{window_problem, KeepClock, WhichDate, WorkWindowRule, MAX_OFFSET_MINUTES};
14use super::identity::{
15    anonymise_problem, set_problem, AnonymiseRule, CompiledMatch, IdentityRule, Who,
16};
17use super::message::{CompiledPattern, TextPattern, TextReplace};
18use super::paths::{validate_glob, ExtractMode, PathMove};
19use super::script::ScriptPolicy;
20use super::textconv::{LineEnding, TextEncoding};
21pub use super::trailers::TrailerIfExists;
22use crate::domain::Oid;
23
24/// The recipe format version this build reads and writes.
25pub const RECIPE_VERSION: u32 = 1;
26
27/// Why a rewrite was refused before anything changed. Fieldless and `Copy`
28/// so it crosses the IPC wire in [`crate::TypedError`]; the details (which
29/// rule, which path) travel in the error's text.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
31#[serde(rename_all = "snake_case")]
32pub enum RewriteRefusal {
33    /// A merge, rebase, cherry-pick, revert or bisect is in progress.
34    OperationInProgress,
35    /// An auto-stash is waiting to be restored.
36    AutoStashPending,
37    /// A shallow clone has incomplete history.
38    Shallow,
39    /// A partial clone, for rules that read file content.
40    PartialClone,
41    /// A SHA-256 repository (object ids here are 20 bytes).
42    UnsupportedObjectFormat,
43    /// The scope names no commit or ref.
44    EmptyScope,
45    /// No enabled rule.
46    NoRule,
47    /// A rule failed validation.
48    InvalidRule,
49    /// A path the rewrite would change has uncommitted edits.
50    DirtyPathsTouched,
51    /// A branch is checked out in another worktree and the run changes
52    /// content.
53    CheckedOutElsewhere,
54    /// A pushed protected branch is in the scope without being listed in
55    /// `include_protected`.
56    ProtectedRef,
57    /// The repository changed since the preview.
58    Stale,
59    /// A tool the recipe needs is missing.
60    ToolMissing,
61    /// A script failed.
62    ScriptFailed,
63    /// The undo data was purged.
64    Purged,
65    /// A script's language is switched off in the settings
66    /// (`rewrite.external_scripts`).
67    ScriptsDisabled,
68    /// An external script from the repository (or a shared recipe) has not
69    /// been trusted by the user; the trust is keyed by its content hash.
70    ScriptNotTrusted,
71    /// Signed commits are affected and the request carries no
72    /// `options.signatures` choice. There is no silent default.
73    SignatureChoiceNeeded,
74    /// An "extract subdirectory" rule carries no mode. Asked each time.
75    ExtractModeNeeded,
76    /// Re-signing was chosen and the signing smoke test failed (key
77    /// missing, agent locked, program refused); the detail says why.
78    SigningFailed,
79    /// An LFS export needs objects that are not in the local LFS store; the
80    /// detail lists them (one `<oid> <path>` per line) so they can be fetched.
81    LfsObjectsMissing,
82    /// A path rule would put a file where one already is (in some commit);
83    /// the detail lists the commits and paths. Never overwritten silently.
84    PathCollision,
85}
86
87impl RewriteRefusal {
88    /// A stable snake_case code for the CLI and MCP.
89    pub fn code(self) -> &'static str {
90        match self {
91            Self::OperationInProgress => "operation_in_progress",
92            Self::AutoStashPending => "auto_stash_pending",
93            Self::Shallow => "shallow",
94            Self::PartialClone => "partial_clone",
95            Self::UnsupportedObjectFormat => "unsupported_object_format",
96            Self::EmptyScope => "empty_scope",
97            Self::NoRule => "no_rule",
98            Self::InvalidRule => "invalid_rule",
99            Self::DirtyPathsTouched => "dirty_paths_touched",
100            Self::CheckedOutElsewhere => "checked_out_elsewhere",
101            Self::ProtectedRef => "protected_ref",
102            Self::Stale => "stale",
103            Self::ToolMissing => "tool_missing",
104            Self::ScriptFailed => "script_failed",
105            Self::Purged => "purged",
106            Self::ScriptsDisabled => "scripts_disabled",
107            Self::ScriptNotTrusted => "script_not_trusted",
108            Self::SignatureChoiceNeeded => "signature_choice_needed",
109            Self::ExtractModeNeeded => "extract_mode_needed",
110            Self::SigningFailed => "signing_failed",
111            Self::LfsObjectsMissing => "lfs_objects_missing",
112            Self::PathCollision => "path_collision",
113        }
114    }
115}
116
117/// Which refs move and which commits may change.
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(tag = "scope", rename_all = "snake_case")]
120pub enum Scope {
121    /// HEAD's branch, optionally limited to the commits after `since`.
122    CurrentBranch {
123        #[serde(default, skip_serializing_if = "Option::is_none")]
124        since: Option<Oid>,
125    },
126    /// Only these commits change (a Log multi-selection); their descendants
127    /// are replayed with new parents.
128    Selection { commits: Vec<Oid> },
129    /// The commits in `base..tip`.
130    Range { base: Oid, tip: Oid },
131    /// Explicit local branches and tags.
132    Refs { refs: Vec<String> },
133    /// Every local branch and tag.
134    AllLocal,
135}
136
137impl Default for Scope {
138    fn default() -> Self {
139        Scope::CurrentBranch { since: None }
140    }
141}
142
143/// Options on the scope that are not part of its kind.
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub struct ScopeOptions {
146    /// Move tags that point at rewritten commits (default on).
147    #[serde(default = "yes")]
148    pub include_tags: bool,
149    /// Protected branches that are already pushed are excluded unless listed
150    /// here, one by one ("check all" fills the list from the preview).
151    #[serde(default, skip_serializing_if = "Vec::is_empty")]
152    pub include_protected: Vec<String>,
153    /// More refs to move (the "add to scope" of the preview).
154    #[serde(default, skip_serializing_if = "Vec::is_empty")]
155    pub extra_refs: Vec<String>,
156    /// Branches the caller already knows are protected (read from a state
157    /// directory the backend cannot guess); added to the bases the repository's
158    /// `workflow.toml` marks `protected`.
159    #[serde(default, skip_serializing_if = "Vec::is_empty")]
160    pub protected_branches: Vec<String>,
161    /// What the host protects (S23), read client side when the repository is
162    /// linked: its patterns join the protected names of the preview, and the
163    /// rest explains how to get a blocked rewrite through.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub host_protection: Option<super::HostProtection>,
166}
167
168fn yes() -> bool {
169    true
170}
171
172impl Default for ScopeOptions {
173    fn default() -> Self {
174        Self {
175            include_tags: true,
176            include_protected: Vec::new(),
177            extra_refs: Vec::new(),
178            protected_branches: Vec::new(),
179            host_protection: None,
180        }
181    }
182}
183
184/// The committer line of rewritten commits.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
186#[serde(rename_all = "snake_case")]
187pub enum CommitterPolicy {
188    /// Keep the original committer and date (a bulk rewrite must not stamp
189    /// today on thousands of commits). Only a rule changes it.
190    #[default]
191    Keep,
192    /// "Me, now": the configured identity and the current time, as reword.
193    MeNow,
194}
195
196/// What happens to the signatures of rewritten commits. Asked each time
197/// signed commits are affected: [`RunOptions::signatures`] is an `Option`
198/// with no default and the engine refuses with
199/// [`RewriteRefusal::SignatureChoiceNeeded`] while it is `None`.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(rename_all = "snake_case")]
202pub enum SignaturePolicy {
203    /// Drop the signatures of rewritten commits (the count is shown first).
204    Strip,
205    /// Re-sign only the rewritten commits that were signed.
206    ResignSigned,
207    /// Re-sign every rewritten commit.
208    ResignAll,
209}
210
211/// Commits that become empty.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
213#[serde(rename_all = "snake_case")]
214pub enum PruneEmpty {
215    /// Drop a commit that a content rule emptied (never one that was empty
216    /// before).
217    #[default]
218    Auto,
219    Never,
220}
221
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
223pub struct RunOptions {
224    #[serde(default)]
225    pub committer: CommitterPolicy,
226    /// `None` until the user chose; see [`SignaturePolicy`].
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub signatures: Option<SignaturePolicy>,
229    #[serde(default)]
230    pub prune_empty: PruneEmpty,
231    /// Rewrite abbreviated commit ids (7+ hex characters) in messages to
232    /// the new ids. Off by default.
233    #[serde(default)]
234    pub update_message_hashes: bool,
235    /// Also keep visible `refs/backup/...` refs. Off by default: the undo
236    /// pins are the backup.
237    #[serde(default)]
238    pub keep_backup_refs: bool,
239}
240
241impl Default for RunOptions {
242    fn default() -> Self {
243        Self {
244            committer: CommitterPolicy::Keep,
245            signatures: None,
246            prune_empty: PruneEmpty::Auto,
247            update_message_hashes: false,
248            keep_backup_refs: false,
249        }
250    }
251}
252
253/// A secret literal typed by the user. Its `Debug` is redacted and a recipe
254/// that is saved ([`Recipe::saved`]) never contains it.
255#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
256#[serde(transparent)]
257pub struct SecretText(pub String);
258
259impl SecretText {
260    /// The scanner finding this names, when the rule scans: with
261    /// `scan: true`, a literal shaped like a finding id (`f-` and twelve hex
262    /// digits) selects that finding, and the daemon's backend resolves it to
263    /// the value. The TUI never holds the value, only the id.
264    pub fn finding_id(&self) -> Option<&str> {
265        super::secrets::is_finding_id(&self.0).then_some(self.0.as_str())
266    }
267}
268
269impl fmt::Debug for SecretText {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        f.write_str("SecretText(<redacted>)")
272    }
273}
274
275/// What a content rule looks for.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277#[serde(tag = "find", rename_all = "snake_case")]
278pub enum ContentFind {
279    Pattern {
280        #[serde(flatten)]
281        pattern: TextPattern,
282    },
283    /// Secret literals (replaced by `***REMOVED***` and never shown), and
284    /// optionally what the built-in scanner finds. The literals are not part
285    /// of a saved recipe.
286    ///
287    /// With `scan: true` the backend scans the recipe's scope when the
288    /// preview runs. A literal shaped like a finding id
289    /// ([`SecretText::finding_id`]) picks that finding; with no id at all,
290    /// every finding is removed. Ids are not secrets: a saved recipe keeps
291    /// them, and an id the scan no longer finds is an `InvalidRule`.
292    Secrets {
293        #[serde(default, skip_serializing_if = "Vec::is_empty")]
294        literals: Vec<SecretText>,
295        #[serde(default)]
296        scan: bool,
297    },
298}
299
300/// Replace text inside the files whose path matches.
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302pub struct ContentReplace {
303    /// Path globs; empty means every file.
304    #[serde(default)]
305    pub paths: Vec<String>,
306    #[serde(flatten)]
307    pub find: ContentFind,
308    #[serde(default)]
309    pub with: String,
310    /// Blobs larger than this are skipped.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub max_blob_bytes: Option<u64>,
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
316#[serde(rename_all = "snake_case")]
317pub enum TrailerAction {
318    /// Add `key: value` (what to do when the key is there: `if_exists`).
319    Add,
320    /// Remove every `key:` trailer (only those whose value matches `find`,
321    /// when it is set).
322    Remove,
323    /// Replace text matching `find` with `with` in the values of the `key`
324    /// trailers (an old email by a new one in `Signed-off-by`).
325    Map,
326}
327
328#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
329pub struct TrailerRule {
330    pub action: TrailerAction,
331    /// `Signed-off-by`, `Co-authored-by`... Matched without regard to case.
332    pub key: String,
333    /// `Add`: the value.
334    #[serde(default)]
335    pub value: String,
336    /// `Add`: when the key is already there.
337    #[serde(default)]
338    pub if_exists: TrailerIfExists,
339    /// `Remove`: only trailers whose value matches (all when `None`).
340    /// `Map`: what to replace.
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub find: Option<TextPattern>,
343    /// `Map`: the replacement (`$1` in regex mode).
344    #[serde(default)]
345    pub with: String,
346}
347
348impl TrailerRule {
349    pub fn add(key: &str, value: &str) -> Self {
350        Self {
351            action: TrailerAction::Add,
352            key: key.to_string(),
353            value: value.to_string(),
354            if_exists: TrailerIfExists::Add,
355            find: None,
356            with: String::new(),
357        }
358    }
359
360    pub fn remove(key: &str) -> Self {
361        Self {
362            action: TrailerAction::Remove,
363            ..Self::add(key, "")
364        }
365    }
366
367    /// Literal `old` -> `new` in the values of `key`.
368    pub fn map(key: &str, old: &str, new: &str) -> Self {
369        Self {
370            action: TrailerAction::Map,
371            find: Some(TextPattern::literal(old)),
372            with: new.to_string(),
373            ..Self::add(key, "")
374        }
375    }
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "snake_case")]
380pub enum ScriptLanguage {
381    /// The embedded, sandboxed interpreter (Lua). Always available.
382    Lua,
383    /// A shell script (bash or sh; pwsh or powershell for a PowerShell
384    /// script), run as an external process speaking JSON lines. Allowed by
385    /// default when a shell is found.
386    Shell,
387    /// A Python script, external process. Off by default in settings.
388    Python,
389    /// A Lua script run by an installed `lua` (not the embedded one), external
390    /// process. Off by default in settings.
391    LuaExternal,
392}
393
394impl ScriptLanguage {
395    /// Every language, in the order the rule form offers them.
396    pub const ALL: [ScriptLanguage; 4] = [
397        ScriptLanguage::Lua,
398        ScriptLanguage::Shell,
399        ScriptLanguage::Python,
400        ScriptLanguage::LuaExternal,
401    ];
402
403    /// Runs as a process of its own, unsandboxed, with the user's rights.
404    pub fn is_external(self) -> bool {
405        !matches!(self, ScriptLanguage::Lua)
406    }
407
408    /// The stable name used by the CLI (`--script-lang`) and in messages.
409    pub fn name(self) -> &'static str {
410        match self {
411            Self::Lua => "lua",
412            Self::Shell => "shell",
413            Self::Python => "python",
414            Self::LuaExternal => "lua-external",
415        }
416    }
417
418    /// Parses [`ScriptLanguage::name`].
419    pub fn from_name(name: &str) -> Option<Self> {
420        Self::ALL.into_iter().find(|l| l.name() == name)
421    }
422
423    /// The value of `rewrite.external_scripts` that switches this language
424    /// on (`None`: the embedded Lua, always available).
425    pub fn setting_name(self) -> Option<&'static str> {
426        match self {
427            Self::Lua => None,
428            Self::Shell => Some("shell"),
429            Self::Python => Some("python"),
430            Self::LuaExternal => Some("lua"),
431        }
432    }
433
434    /// The language a script file's extension suggests.
435    pub fn from_extension(path: &str) -> Option<Self> {
436        let ext = path.rsplit_once('.')?.1.to_ascii_lowercase();
437        match ext.as_str() {
438            "lua" => Some(Self::Lua),
439            "sh" | "bash" | "ps1" => Some(Self::Shell),
440            "py" => Some(Self::Python),
441            _ => None,
442        }
443    }
444}
445
446/// Where a script's text comes from.
447#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
448#[serde(tag = "from", rename_all = "snake_case")]
449pub enum ScriptSource {
450    Inline {
451        text: String,
452    },
453    /// A path relative to the repository.
454    File {
455        path: String,
456    },
457}
458
459#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
460pub struct ScriptRef {
461    pub language: ScriptLanguage,
462    pub source: ScriptSource,
463    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
464    pub params: BTreeMap<String, String>,
465}
466
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
468pub struct LfsImportRule {
469    /// Path globs (`.gitattributes` style) to move into LFS.
470    pub patterns: Vec<String>,
471    /// Only files of at least this many bytes move (absent: every match).
472    #[serde(default, skip_serializing_if = "Option::is_none")]
473    pub min_size: Option<u64>,
474}
475
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477pub struct LfsExportRule {
478    /// Path globs whose LFS pointers become the real files again.
479    pub patterns: Vec<String>,
480}
481
482/// S22: every text file that matches gets one line ending.
483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
484pub struct EolRule {
485    pub target: LineEnding,
486    /// Path globs; empty means every file. Binary files are always skipped.
487    #[serde(default)]
488    pub paths: Vec<String>,
489    /// Path globs the rule leaves alone.
490    #[serde(default, skip_serializing_if = "Vec::is_empty")]
491    pub exclude: Vec<String>,
492    /// Follow the root `.gitattributes` of each commit: `-text` / `binary`
493    /// files are skipped and `eol=lf|crlf` files get that ending. Off by
494    /// default: the rule's target and path filters decide alone.
495    #[serde(default, skip_serializing_if = "is_false")]
496    pub follow_attributes: bool,
497    /// Blobs larger than this are skipped.
498    #[serde(default, skip_serializing_if = "Option::is_none")]
499    pub max_blob_bytes: Option<u64>,
500}
501
502/// S22: the exec bit (mode 100755) leaves the files that match.
503#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
504pub struct StripExecRule {
505    /// Path globs (at least one: stripping every exec bit is never meant).
506    pub paths: Vec<String>,
507    #[serde(default, skip_serializing_if = "Vec::is_empty")]
508    pub exclude: Vec<String>,
509}
510
511fn is_false(b: &bool) -> bool {
512    !*b
513}
514
515fn default_fallback() -> TextEncoding {
516    TextEncoding::Windows1252
517}
518
519fn is_default_fallback(e: &TextEncoding) -> bool {
520    *e == TextEncoding::Windows1252
521}
522
523/// S24bis: the text encoding of the files that match becomes `target`.
524#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
525pub struct ReencodeRule {
526    pub target: TextEncoding,
527    /// The encoding the files are in. Absent: detected per file (byte order
528    /// mark, then valid UTF-8, then `fallback`).
529    #[serde(default, skip_serializing_if = "Option::is_none")]
530    pub from: Option<TextEncoding>,
531    /// What a file that is neither marked nor valid UTF-8 is read as.
532    #[serde(
533        default = "default_fallback",
534        skip_serializing_if = "is_default_fallback"
535    )]
536    pub fallback: TextEncoding,
537    /// Path globs; empty means every file. Binary files are always skipped.
538    #[serde(default)]
539    pub paths: Vec<String>,
540    #[serde(default, skip_serializing_if = "Vec::is_empty")]
541    pub exclude: Vec<String>,
542    /// Blobs larger than this are skipped.
543    #[serde(default, skip_serializing_if = "Option::is_none")]
544    pub max_blob_bytes: Option<u64>,
545}
546
547/// One step of a recipe.
548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
549#[serde(tag = "type", rename_all = "snake_case")]
550pub enum RuleKind {
551    Identity(IdentityRule),
552    /// Apply the repository's `.mailmap`.
553    Mailmap {
554        #[serde(default)]
555        apply_to: Who,
556        /// The `.mailmap` to apply: a path relative to the worktree, or an
557        /// absolute one. Absent: the worktree's own `.mailmap`.
558        #[serde(default, skip_serializing_if = "Option::is_none")]
559        file: Option<String>,
560    },
561    Anonymise(AnonymiseRule),
562    DateShift {
563        by_seconds: i64,
564        #[serde(default)]
565        apply_to: WhichDate,
566    },
567    DateTimezone {
568        offset_minutes: i16,
569        keep: KeepClock,
570        #[serde(default)]
571        apply_to: WhichDate,
572    },
573    DateWindow(WorkWindowRule),
574    /// Committer date (and identity) become the author's.
575    CommitterFromAuthor,
576    MessageReplace(TextReplace),
577    MessageDeleteLines {
578        pattern: TextPattern,
579    },
580    Trailer(TrailerRule),
581    ContentReplace(ContentReplace),
582    RemovePaths {
583        globs: Vec<String>,
584    },
585    RemoveBlobsOver {
586        bytes: u64,
587    },
588    MovePaths(PathMove),
589    LfsImport(LfsImportRule),
590    LfsExport(LfsExportRule),
591    /// S22: one line ending for the matching text files.
592    LineEndings(EolRule),
593    /// S22: the exec bit leaves the matching files.
594    StripExec(StripExecRule),
595    /// S24bis: one text encoding for the matching text files.
596    Reencode(ReencodeRule),
597    Script(ScriptRef),
598    /// Strip the signature of every commit in scope, even where nothing
599    /// else changes.
600    RemoveSignatures,
601    /// Re-encode commit messages to UTF-8 (S24): messages with an
602    /// `encoding` header are decoded and the header goes; UTF-8 read once
603    /// as Latin-1 / Windows-1252 is repaired when the round trip is exact.
604    /// What cannot be decided is left alone and counted.
605    MessageEncoding {
606        /// Also repair the author and committer names the same way (the
607        /// names of a commit whose header goes are always decoded: they
608        /// were in the same encoding).
609        #[serde(default)]
610        names: bool,
611    },
612}
613
614impl RuleKind {
615    /// A short stable name for labels and CLI output.
616    pub fn name(&self) -> &'static str {
617        match self {
618            Self::Identity(_) => "identity",
619            Self::Mailmap { .. } => "mailmap",
620            Self::Anonymise(_) => "anonymise",
621            Self::DateShift { .. } => "date_shift",
622            Self::DateTimezone { .. } => "date_timezone",
623            Self::DateWindow(_) => "date_window",
624            Self::CommitterFromAuthor => "committer_from_author",
625            Self::MessageReplace(_) => "message_replace",
626            Self::MessageDeleteLines { .. } => "message_delete_lines",
627            Self::Trailer(_) => "trailer",
628            Self::ContentReplace(_) => "content_replace",
629            Self::RemovePaths { .. } => "remove_paths",
630            Self::RemoveBlobsOver { .. } => "remove_blobs_over",
631            Self::MovePaths(_) => "move_paths",
632            Self::LfsImport(_) => "lfs_import",
633            Self::LfsExport(_) => "lfs_export",
634            Self::LineEndings(_) => "line_endings",
635            Self::StripExec(_) => "strip_exec",
636            Self::Reencode(_) => "reencode",
637            Self::Script(_) => "script",
638            Self::RemoveSignatures => "remove_signatures",
639            Self::MessageEncoding { .. } => "message_encoding",
640        }
641    }
642
643    /// `true` for rules that read or change file content (they need the
644    /// objects, refuse partial clones and touch the working tree).
645    pub fn changes_content(&self) -> bool {
646        matches!(
647            self,
648            Self::ContentReplace(_)
649                | Self::RemovePaths { .. }
650                | Self::RemoveBlobsOver { .. }
651                | Self::MovePaths(_)
652                | Self::LfsImport(_)
653                | Self::LfsExport(_)
654                | Self::LineEndings(_)
655                | Self::StripExec(_)
656                | Self::Reencode(_)
657                | Self::Script(_)
658        )
659    }
660}
661
662#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
663pub struct Rule {
664    #[serde(default = "yes")]
665    pub enabled: bool,
666    #[serde(default, skip_serializing_if = "Option::is_none")]
667    pub label: Option<String>,
668    pub kind: RuleKind,
669}
670
671impl Rule {
672    pub fn new(kind: RuleKind) -> Self {
673        Self {
674            enabled: true,
675            label: None,
676            kind,
677        }
678    }
679}
680
681#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
682pub struct Recipe {
683    #[serde(default = "version")]
684    pub version: u32,
685    #[serde(default)]
686    pub name: String,
687    #[serde(default)]
688    pub scope: Scope,
689    #[serde(default)]
690    pub scope_options: ScopeOptions,
691    #[serde(default)]
692    pub rules: Vec<Rule>,
693    #[serde(default)]
694    pub options: RunOptions,
695    /// What external scripts may do on this run. **Filled by the daemon from
696    /// the settings and the trust store; whatever a client sends here is
697    /// replaced.** Never saved.
698    #[serde(default, skip_serializing_if = "ScriptPolicy::is_default")]
699    pub script_policy: ScriptPolicy,
700}
701
702fn version() -> u32 {
703    RECIPE_VERSION
704}
705
706impl Recipe {
707    pub fn new(name: &str, scope: Scope, rules: Vec<Rule>) -> Self {
708        Self {
709            version: RECIPE_VERSION,
710            name: name.to_string(),
711            scope,
712            scope_options: ScopeOptions::default(),
713            rules,
714            options: RunOptions::default(),
715            script_policy: ScriptPolicy::default(),
716        }
717    }
718
719    /// The rules that run, in order, with their index in `rules`.
720    pub fn enabled_rules(&self) -> impl Iterator<Item = (usize, &Rule)> {
721        self.rules.iter().enumerate().filter(|(_, r)| r.enabled)
722    }
723
724    /// The enabled "extract a subdirectory" rule: its directory and mode.
725    pub fn extraction(&self) -> Option<(&str, Option<ExtractMode>)> {
726        self.enabled_rules().find_map(|(_, r)| match &r.kind {
727            RuleKind::MovePaths(PathMove::ExtractSubdir { dir, mode }) => {
728                Some((dir.as_str(), *mode))
729            }
730            _ => None,
731        })
732    }
733
734    /// The copy that may be written to disk: secret literals removed. A
735    /// secret rule loaded back has to be given its values again.
736    pub fn saved(&self) -> Recipe {
737        let mut copy = self.clone();
738        copy.script_policy = ScriptPolicy::default();
739        for rule in &mut copy.rules {
740            if let RuleKind::ContentReplace(c) = &mut rule.kind {
741                if let ContentFind::Secrets { literals, scan } = &mut c.find {
742                    // Finding ids name no value: they stay.
743                    literals.retain(|l| *scan && l.finding_id().is_some());
744                }
745            }
746        }
747        copy
748    }
749
750    /// `true` when a secret literal is part of the recipe.
751    pub fn holds_secrets(&self) -> bool {
752        self.rules.iter().any(|r| {
753            matches!(
754                &r.kind,
755                RuleKind::ContentReplace(ContentReplace {
756                    find: ContentFind::Secrets { literals, scan },
757                    ..
758                }) if literals.iter().any(|l| !(*scan && l.finding_id().is_some()))
759            )
760        })
761    }
762}
763
764/// What [`validate_recipe`] found.
765#[derive(Debug, Clone, PartialEq, Eq)]
766pub struct RecipeIssue {
767    /// The index in `Recipe::rules`, `None` for the recipe as a whole.
768    pub rule: Option<usize>,
769    pub refusal: RewriteRefusal,
770    pub detail: String,
771}
772
773impl fmt::Display for RecipeIssue {
774    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775        match self.rule {
776            Some(i) => write!(f, "rule {}: {}", i + 1, self.detail),
777            None => f.write_str(&self.detail),
778        }
779    }
780}
781
782fn issue(rule: Option<usize>, refusal: RewriteRefusal, detail: impl Into<String>) -> RecipeIssue {
783    RecipeIssue {
784        rule,
785        refusal,
786        detail: detail.into(),
787    }
788}
789
790/// Checks a recipe without a repository: the first problem, or `Ok`. Only
791/// enabled rules are checked, so a half-edited disabled rule does not block
792/// a run. What needs the repository (signed commits, dirty paths, protected
793/// refs, shallow clones) is the engine's to refuse.
794pub fn validate_recipe(recipe: &Recipe) -> Result<(), RecipeIssue> {
795    use RewriteRefusal as R;
796    if recipe.version != RECIPE_VERSION {
797        return Err(issue(
798            None,
799            R::InvalidRule,
800            format!("recipe version {} is not supported", recipe.version),
801        ));
802    }
803    match &recipe.scope {
804        Scope::Selection { commits } if commits.is_empty() => {
805            return Err(issue(None, R::EmptyScope, "no commit is selected"));
806        }
807        Scope::Refs { refs } if refs.iter().all(|r| r.trim().is_empty()) => {
808            return Err(issue(None, R::EmptyScope, "no branch or tag is named"));
809        }
810        Scope::Range { base, tip } if base == tip => {
811            return Err(issue(None, R::EmptyScope, "the range is empty"));
812        }
813        _ => {}
814    }
815    if recipe.enabled_rules().next().is_none() {
816        return Err(issue(None, R::NoRule, "no rule is enabled"));
817    }
818    for (i, rule) in recipe.enabled_rules() {
819        if let Some(detail) = rule_problem(&rule.kind) {
820            let refusal = match &rule.kind {
821                RuleKind::MovePaths(PathMove::ExtractSubdir { mode: None, .. }) => {
822                    R::ExtractModeNeeded
823                }
824                _ => R::InvalidRule,
825            };
826            return Err(issue(Some(i), refusal, detail));
827        }
828    }
829    // One extraction per recipe, and when it leaves this repository alone
830    // (clone, submodule) it comes before the other path rules, so the
831    // directory it names is the one in this repository's own tree.
832    let mut moves = recipe.enabled_rules().filter_map(|(i, r)| match &r.kind {
833        RuleKind::MovePaths(m) => Some((i, m)),
834        _ => None,
835    });
836    let mut seen_move = false;
837    let mut extracted = false;
838    for (i, m) in &mut moves {
839        if let PathMove::ExtractSubdir { mode, .. } = m {
840            if extracted {
841                return Err(issue(Some(i), R::InvalidRule, "only one rule can extract"));
842            }
843            extracted = true;
844            if seen_move && matches!(mode, Some(ExtractMode::Clone | ExtractMode::Submodule)) {
845                return Err(issue(
846                    Some(i),
847                    R::InvalidRule,
848                    "extracting into a clone or a submodule comes before the other path rules",
849                ));
850            }
851        }
852        seen_move = true;
853    }
854    Ok(())
855}
856
857fn globs_problem(globs: &[String]) -> Option<String> {
858    globs.iter().find_map(|g| validate_glob(g).err())
859}
860
861fn filter_problem(paths: &[String], exclude: &[String]) -> Option<String> {
862    globs_problem(paths).or_else(|| globs_problem(exclude))
863}
864
865fn pattern_problem(p: &TextPattern) -> Option<String> {
866    CompiledPattern::new(p).err()
867}
868
869fn trailer_problem(t: &TrailerRule) -> Option<String> {
870    let ok_key = !t.key.is_empty() && t.key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
871    if !ok_key {
872        return Some("a trailer key is letters, digits and `-`".to_string());
873    }
874    match t.action {
875        TrailerAction::Add => (t.value.trim().is_empty() || t.value.contains(['\n', '\r']))
876            .then(|| "a trailer to add needs a one-line value".to_string()),
877        TrailerAction::Remove => t.find.as_ref().and_then(pattern_problem),
878        TrailerAction::Map => match &t.find {
879            None => Some("a trailer to map needs the text to replace".to_string()),
880            Some(p) => pattern_problem(p).or_else(|| {
881                t.with
882                    .contains(['\n', '\r'])
883                    .then(|| "a trailer value is one line".to_string())
884            }),
885        },
886    }
887}
888
889fn rule_problem(kind: &RuleKind) -> Option<String> {
890    match kind {
891        RuleKind::Identity(r) => CompiledMatch::new(&r.when)
892            .err()
893            .or_else(|| set_problem(&r.set).map(str::to_string)),
894        RuleKind::Mailmap { .. }
895        | RuleKind::CommitterFromAuthor
896        | RuleKind::RemoveSignatures
897        | RuleKind::MessageEncoding { .. } => None,
898        RuleKind::Anonymise(r) => anonymise_problem(r),
899        RuleKind::DateShift { by_seconds, .. } => (*by_seconds == 0)
900            .then(|| "a shift of zero changes nothing".to_string())
901            .or_else(|| {
902                (by_seconds.unsigned_abs() > 200 * 365 * 86_400)
903                    .then(|| "the shift is larger than 200 years".to_string())
904            }),
905        RuleKind::DateTimezone { offset_minutes, .. } => (offset_minutes.abs()
906            > MAX_OFFSET_MINUTES)
907            .then(|| "the offset is out of range".to_string()),
908        RuleKind::DateWindow(w) => window_problem(w),
909        RuleKind::MessageReplace(r) => pattern_problem(&r.find),
910        RuleKind::MessageDeleteLines { pattern } => pattern_problem(pattern),
911        RuleKind::Trailer(t) => trailer_problem(t),
912        RuleKind::ContentReplace(c) => globs_problem(&c.paths).or_else(|| match &c.find {
913            ContentFind::Pattern { pattern } => pattern_problem(pattern),
914            ContentFind::Secrets { literals, scan } => (literals.is_empty() && !*scan)
915                .then(|| "give the secret values or turn the scanner on".to_string())
916                .or_else(|| {
917                    literals
918                        .iter()
919                        .any(|l| l.0.is_empty())
920                        .then(|| "a secret value is empty".to_string())
921                }),
922        }),
923        RuleKind::RemovePaths { globs } => (globs.is_empty())
924            .then(|| "name at least one path".to_string())
925            .or_else(|| globs_problem(globs)),
926        RuleKind::RemoveBlobsOver { bytes } => {
927            (*bytes == 0).then(|| "the size limit must be above zero".to_string())
928        }
929        RuleKind::MovePaths(m) => m.problem(),
930        RuleKind::LfsImport(l) => (l.patterns.is_empty())
931            .then(|| "name at least one pattern".to_string())
932            .or_else(|| globs_problem(&l.patterns)),
933        RuleKind::LfsExport(l) => (l.patterns.is_empty())
934            .then(|| "name at least one pattern".to_string())
935            .or_else(|| globs_problem(&l.patterns)),
936        RuleKind::LineEndings(e) => filter_problem(&e.paths, &e.exclude),
937        RuleKind::StripExec(e) => (e.paths.is_empty())
938            .then(|| "name at least one path".to_string())
939            .or_else(|| filter_problem(&e.paths, &e.exclude)),
940        RuleKind::Reencode(e) => filter_problem(&e.paths, &e.exclude).or_else(|| {
941            (e.from == Some(e.target))
942                .then(|| "the source and the target encoding are the same".to_string())
943        }),
944        RuleKind::Script(s) => match &s.source {
945            ScriptSource::Inline { text } if text.trim().is_empty() => {
946                Some("the script is empty".to_string())
947            }
948            ScriptSource::File { path } if path.trim().is_empty() => {
949                Some("the script path is empty".to_string())
950            }
951            _ => None,
952        },
953    }
954}
955
956#[cfg(test)]
957mod tests {
958    use super::*;
959    use crate::domain::rewrite::dates::{WeekWindow, Weekday};
960    use crate::domain::rewrite::identity::{IdentityMatch, IdentitySet};
961    use crate::domain::rewrite::paths::ExtractMode;
962
963    fn oid(byte: u8) -> Oid {
964        Oid([byte; 20])
965    }
966
967    fn identity_rule() -> Rule {
968        Rule::new(RuleKind::Identity(IdentityRule {
969            when: IdentityMatch::email("old@example.com"),
970            set: IdentitySet {
971                name: Some("Alice Example".into()),
972                email: Some("alice@example.com".into()),
973            },
974            apply_to: Who::Both,
975            include_taggers: true,
976            map_trailers: false,
977        }))
978    }
979
980    fn recipe(rules: Vec<Rule>) -> Recipe {
981        Recipe::new("test", Scope::default(), rules)
982    }
983
984    fn refused(r: &Recipe) -> (Option<usize>, RewriteRefusal) {
985        let e = validate_recipe(r).unwrap_err();
986        (e.rule, e.refusal)
987    }
988
989    #[test]
990    fn a_sound_recipe_validates() {
991        assert!(validate_recipe(&recipe(vec![identity_rule()])).is_ok());
992    }
993
994    #[test]
995    fn scope_refusals() {
996        let rules = vec![identity_rule()];
997        let mut r = recipe(rules.clone());
998        r.scope = Scope::Selection { commits: vec![] };
999        assert_eq!(refused(&r), (None, RewriteRefusal::EmptyScope));
1000        r.scope = Scope::Refs {
1001            refs: vec!["".into()],
1002        };
1003        assert_eq!(refused(&r), (None, RewriteRefusal::EmptyScope));
1004        r.scope = Scope::Range {
1005            base: oid(1),
1006            tip: oid(1),
1007        };
1008        assert_eq!(refused(&r), (None, RewriteRefusal::EmptyScope));
1009        r.scope = Scope::Range {
1010            base: oid(1),
1011            tip: oid(2),
1012        };
1013        assert!(validate_recipe(&r).is_ok());
1014        r.scope = Scope::AllLocal;
1015        assert!(validate_recipe(&r).is_ok());
1016    }
1017
1018    #[test]
1019    fn no_rule_and_only_disabled_rules_are_refused() {
1020        assert_eq!(refused(&recipe(vec![])), (None, RewriteRefusal::NoRule));
1021        let mut off = identity_rule();
1022        off.enabled = false;
1023        assert_eq!(refused(&recipe(vec![off])), (None, RewriteRefusal::NoRule));
1024    }
1025
1026    #[test]
1027    fn a_disabled_broken_rule_does_not_block_and_an_enabled_one_names_its_index() {
1028        let mut broken = Rule::new(RuleKind::RemovePaths { globs: vec![] });
1029        broken.enabled = false;
1030        assert!(validate_recipe(&recipe(vec![identity_rule(), broken.clone()])).is_ok());
1031        broken.enabled = true;
1032        assert_eq!(
1033            refused(&recipe(vec![identity_rule(), broken])),
1034            (Some(1), RewriteRefusal::InvalidRule)
1035        );
1036    }
1037
1038    #[test]
1039    fn a_wrong_version_is_refused() {
1040        let mut r = recipe(vec![identity_rule()]);
1041        r.version = 99;
1042        assert_eq!(refused(&r), (None, RewriteRefusal::InvalidRule));
1043    }
1044
1045    #[test]
1046    fn every_rule_kind_has_a_refusal() {
1047        let bad: Vec<RuleKind> = vec![
1048            // identity: nothing to set, a bad email, a regex that does not compile
1049            RuleKind::Identity(IdentityRule {
1050                when: IdentityMatch::everyone(),
1051                set: IdentitySet::default(),
1052                apply_to: Who::Both,
1053                include_taggers: false,
1054                map_trailers: false,
1055            }),
1056            RuleKind::Identity(IdentityRule {
1057                when: IdentityMatch::everyone(),
1058                set: IdentitySet {
1059                    name: None,
1060                    email: Some("a<b@example.com".into()),
1061                },
1062                apply_to: Who::Both,
1063                include_taggers: false,
1064                map_trailers: false,
1065            }),
1066            RuleKind::Identity(IdentityRule {
1067                when: IdentityMatch {
1068                    name: Some("(".into()),
1069                    regex: true,
1070                    ..IdentityMatch::default()
1071                },
1072                set: IdentitySet {
1073                    name: Some("X".into()),
1074                    email: None,
1075                },
1076                apply_to: Who::Both,
1077                include_taggers: false,
1078                map_trailers: false,
1079            }),
1080            RuleKind::Anonymise(AnonymiseRule {
1081                email_pattern: "fixed@anonymous.invalid".into(),
1082                ..AnonymiseRule::default()
1083            }),
1084            RuleKind::DateShift {
1085                by_seconds: 0,
1086                apply_to: WhichDate::Both,
1087            },
1088            RuleKind::DateShift {
1089                by_seconds: i64::MAX,
1090                apply_to: WhichDate::Both,
1091            },
1092            RuleKind::DateTimezone {
1093                offset_minutes: 2000,
1094                keep: KeepClock::Instant,
1095                apply_to: WhichDate::Both,
1096            },
1097            RuleKind::DateWindow(WorkWindowRule {
1098                windows: vec![WeekWindow::new(&[Weekday::Mon], 600, 600)],
1099                ..WorkWindowRule::evenings_and_weekends()
1100            }),
1101            RuleKind::MessageReplace(TextReplace {
1102                find: TextPattern::regex("("),
1103                with: String::new(),
1104            }),
1105            RuleKind::MessageReplace(TextReplace {
1106                find: TextPattern::literal(""),
1107                with: String::new(),
1108            }),
1109            RuleKind::MessageDeleteLines {
1110                pattern: TextPattern::regex("["),
1111            },
1112            RuleKind::Trailer(TrailerRule::add("Co authored", "x")),
1113            RuleKind::Trailer(TrailerRule::add("Signed-off-by", "")),
1114            RuleKind::Trailer(TrailerRule::add("Signed-off-by", "two\nlines")),
1115            // A map without the text to replace, or with a pattern that
1116            // does not compile, or a multi-line replacement.
1117            RuleKind::Trailer(TrailerRule {
1118                find: None,
1119                ..TrailerRule::map("Signed-off-by", "a", "b")
1120            }),
1121            RuleKind::Trailer(TrailerRule {
1122                find: Some(TextPattern::regex("(")),
1123                ..TrailerRule::map("Signed-off-by", "a", "b")
1124            }),
1125            RuleKind::Trailer(TrailerRule::map("Signed-off-by", "a", "b\nc")),
1126            RuleKind::Trailer(TrailerRule {
1127                find: Some(TextPattern::regex("[")),
1128                ..TrailerRule::remove("Signed-off-by")
1129            }),
1130            RuleKind::ContentReplace(ContentReplace {
1131                paths: vec!["../x".into()],
1132                find: ContentFind::Pattern {
1133                    pattern: TextPattern::literal("a"),
1134                },
1135                with: String::new(),
1136                max_blob_bytes: None,
1137            }),
1138            RuleKind::ContentReplace(ContentReplace {
1139                paths: vec![],
1140                find: ContentFind::Secrets {
1141                    literals: vec![],
1142                    scan: false,
1143                },
1144                with: String::new(),
1145                max_blob_bytes: None,
1146            }),
1147            RuleKind::RemovePaths { globs: vec![] },
1148            RuleKind::RemovePaths {
1149                globs: vec!["[".into()],
1150            },
1151            RuleKind::RemoveBlobsOver { bytes: 0 },
1152            RuleKind::MovePaths(PathMove::IntoSubdir { dir: "".into() }),
1153            RuleKind::LfsImport(LfsImportRule {
1154                patterns: vec![],
1155                min_size: None,
1156            }),
1157            RuleKind::LfsExport(LfsExportRule { patterns: vec![] }),
1158            RuleKind::Script(ScriptRef {
1159                language: ScriptLanguage::Lua,
1160                source: ScriptSource::Inline { text: " ".into() },
1161                params: BTreeMap::new(),
1162            }),
1163            RuleKind::Script(ScriptRef {
1164                language: ScriptLanguage::Shell,
1165                source: ScriptSource::File { path: "".into() },
1166                params: BTreeMap::new(),
1167            }),
1168        ];
1169        for (n, kind) in bad.into_iter().enumerate() {
1170            let name = kind.name();
1171            let r = recipe(vec![Rule::new(kind)]);
1172            assert_eq!(
1173                refused(&r),
1174                (Some(0), RewriteRefusal::InvalidRule),
1175                "case {n} ({name})"
1176            );
1177        }
1178    }
1179
1180    #[test]
1181    fn extracting_a_subdirectory_asks_for_a_mode() {
1182        let ask = |mode| {
1183            recipe(vec![Rule::new(RuleKind::MovePaths(
1184                PathMove::ExtractSubdir {
1185                    dir: "app".into(),
1186                    mode,
1187                },
1188            ))])
1189        };
1190        assert_eq!(
1191            refused(&ask(None)),
1192            (Some(0), RewriteRefusal::ExtractModeNeeded)
1193        );
1194        for mode in [
1195            ExtractMode::Clone,
1196            ExtractMode::InPlace,
1197            ExtractMode::Submodule,
1198        ] {
1199            assert!(validate_recipe(&ask(Some(mode))).is_ok());
1200        }
1201    }
1202
1203    #[test]
1204    fn defaults_keep_the_committer_and_ask_about_signatures() {
1205        let o = RunOptions::default();
1206        assert_eq!(o.committer, CommitterPolicy::Keep);
1207        assert_eq!(o.signatures, None);
1208        assert!(!o.keep_backup_refs);
1209        assert!(ScopeOptions::default().include_protected.is_empty());
1210    }
1211
1212    fn everything() -> Recipe {
1213        let mut r = Recipe::new(
1214            "everything",
1215            Scope::Range {
1216                base: oid(1),
1217                tip: oid(2),
1218            },
1219            vec![
1220                identity_rule(),
1221                Rule {
1222                    enabled: false,
1223                    label: Some("anon".into()),
1224                    kind: RuleKind::Anonymise(AnonymiseRule::default()),
1225                },
1226                Rule::new(RuleKind::DateShift {
1227                    by_seconds: -3600,
1228                    apply_to: WhichDate::AuthorDate,
1229                }),
1230                Rule::new(RuleKind::DateTimezone {
1231                    offset_minutes: -300,
1232                    keep: KeepClock::WallClock,
1233                    apply_to: WhichDate::Both,
1234                }),
1235                Rule::new(RuleKind::DateWindow(WorkWindowRule::evenings_and_weekends())),
1236                Rule::new(RuleKind::CommitterFromAuthor),
1237                Rule::new(RuleKind::Mailmap {
1238                    apply_to: Who::Author,
1239                    file: None,
1240                }),
1241                Rule::new(RuleKind::MessageReplace(TextReplace {
1242                    find: TextPattern::regex("PROJ-(\\d+)"),
1243                    with: "#$1".into(),
1244                })),
1245                Rule::new(RuleKind::MessageDeleteLines {
1246                    pattern: TextPattern::literal("WIP"),
1247                }),
1248                Rule::new(RuleKind::Trailer(TrailerRule::add(
1249                    "Signed-off-by",
1250                    "Alice Example <alice@example.com>",
1251                ))),
1252                Rule::new(RuleKind::Trailer(TrailerRule::remove("Change-Id"))),
1253                Rule::new(RuleKind::Trailer(TrailerRule::map(
1254                    "Co-authored-by",
1255                    "@old.org",
1256                    "@new.org",
1257                ))),
1258                Rule::new(RuleKind::ContentReplace(ContentReplace {
1259                    paths: vec!["*.env".into()],
1260                    find: ContentFind::Pattern {
1261                        pattern: TextPattern::literal("token"),
1262                    },
1263                    with: "x".into(),
1264                    max_blob_bytes: Some(1 << 20),
1265                })),
1266                Rule::new(RuleKind::RemovePaths {
1267                    globs: vec!["secrets/".into()],
1268                }),
1269                Rule::new(RuleKind::RemoveBlobsOver { bytes: 10_000_000 }),
1270                Rule::new(RuleKind::MovePaths(PathMove::ExtractSubdir {
1271                    dir: "app".into(),
1272                    mode: Some(ExtractMode::Submodule),
1273                })),
1274                Rule::new(RuleKind::LfsImport(LfsImportRule {
1275                    patterns: vec!["*.psd".into()],
1276                    min_size: Some(1 << 20),
1277                })),
1278                Rule::new(RuleKind::LfsExport(LfsExportRule {
1279                    patterns: vec!["*.zip".into()],
1280                })),
1281                Rule::new(RuleKind::Script(ScriptRef {
1282                    language: ScriptLanguage::Lua,
1283                    source: ScriptSource::Inline {
1284                        text: "return commit".into(),
1285                    },
1286                    params: BTreeMap::from([("who".to_string(), "Alice".to_string())]),
1287                })),
1288            ],
1289        );
1290        r.scope_options.include_protected = vec!["main".into()];
1291        r.options.committer = CommitterPolicy::MeNow;
1292        r.options.signatures = Some(SignaturePolicy::ResignSigned);
1293        r
1294    }
1295
1296    #[test]
1297    fn a_recipe_round_trips_through_toml() {
1298        let r = everything();
1299        let text = toml::to_string(&r).unwrap();
1300        let back: Recipe = toml::from_str(&text).unwrap();
1301        assert_eq!(back, r, "{text}");
1302    }
1303
1304    #[test]
1305    fn a_recipe_round_trips_through_json() {
1306        let r = everything();
1307        let text = serde_json::to_string(&r).unwrap();
1308        let back: Recipe = serde_json::from_str(&text).unwrap();
1309        assert_eq!(back, r);
1310    }
1311
1312    #[test]
1313    fn a_minimal_file_fills_in_defaults() {
1314        let r: Recipe = toml::from_str(
1315            r#"
1316name = "tidy"
1317
1318[[rules]]
1319kind = { type = "message_delete_lines", pattern = { pattern = "WIP" } }
1320"#,
1321        )
1322        .unwrap();
1323        assert_eq!(r.version, RECIPE_VERSION);
1324        assert_eq!(r.scope, Scope::default());
1325        assert!(r.rules[0].enabled);
1326        assert_eq!(r.options.signatures, None);
1327        assert!(validate_recipe(&r).is_ok());
1328    }
1329
1330    #[test]
1331    fn an_undecided_signature_choice_is_not_written() {
1332        let r = recipe(vec![identity_rule()]);
1333        let text = toml::to_string(&r).unwrap();
1334        assert!(!text.contains("signatures"), "{text}");
1335    }
1336
1337    fn secret_recipe() -> Recipe {
1338        recipe(vec![Rule::new(RuleKind::ContentReplace(ContentReplace {
1339            paths: vec![],
1340            find: ContentFind::Secrets {
1341                literals: vec![SecretText("hunter2-not-a-real-secret".into())],
1342                scan: true,
1343            },
1344            with: "***REMOVED***".into(),
1345            max_blob_bytes: None,
1346        }))])
1347    }
1348
1349    #[test]
1350    fn saved_recipes_carry_no_secret_literal() {
1351        let r = secret_recipe();
1352        assert!(r.holds_secrets());
1353        let saved = r.saved();
1354        assert!(!saved.holds_secrets());
1355        let text = toml::to_string(&saved).unwrap();
1356        assert!(!text.contains("hunter2"), "{text}");
1357        assert!(!serde_json::to_string(&saved).unwrap().contains("hunter2"));
1358        // Loaded back, the rule keeps its scanner but needs no literal to be valid.
1359        let back: Recipe = toml::from_str(&text).unwrap();
1360        assert!(validate_recipe(&back).is_ok());
1361    }
1362
1363    #[test]
1364    fn finding_ids_are_kept_when_saving_but_values_next_to_them_are_not() {
1365        let mut r = secret_recipe();
1366        if let RuleKind::ContentReplace(c) = &mut r.rules[0].kind {
1367            if let ContentFind::Secrets { literals, .. } = &mut c.find {
1368                literals.push(SecretText("f-0123456789ab".into()));
1369            }
1370        }
1371        // A value and an id: the recipe holds a secret until saved.
1372        assert!(r.holds_secrets());
1373        let saved = r.saved();
1374        assert!(!saved.holds_secrets());
1375        let text = serde_json::to_string(&saved).unwrap();
1376        assert!(
1377            text.contains("f-0123456789ab") && !text.contains("hunter2"),
1378            "{text}"
1379        );
1380        // Only ids: nothing secret to hold.
1381        assert!(!saved.holds_secrets());
1382        // Without the scanner the id-shaped text is a literal like any other.
1383        let mut plain = saved.clone();
1384        if let RuleKind::ContentReplace(c) = &mut plain.rules[0].kind {
1385            c.find = ContentFind::Secrets {
1386                literals: vec![SecretText("f-0123456789ab".into())],
1387                scan: false,
1388            };
1389        }
1390        assert!(plain.holds_secrets());
1391        assert!(!plain.saved().holds_secrets());
1392    }
1393
1394    #[test]
1395    fn a_secret_never_shows_up_in_debug_output() {
1396        let r = secret_recipe();
1397        assert!(!format!("{r:?}").contains("hunter2"));
1398    }
1399
1400    #[test]
1401    fn refusal_codes_are_stable_and_distinct() {
1402        use std::collections::HashSet;
1403        let all = [
1404            RewriteRefusal::OperationInProgress,
1405            RewriteRefusal::AutoStashPending,
1406            RewriteRefusal::Shallow,
1407            RewriteRefusal::PartialClone,
1408            RewriteRefusal::UnsupportedObjectFormat,
1409            RewriteRefusal::EmptyScope,
1410            RewriteRefusal::NoRule,
1411            RewriteRefusal::InvalidRule,
1412            RewriteRefusal::DirtyPathsTouched,
1413            RewriteRefusal::CheckedOutElsewhere,
1414            RewriteRefusal::ProtectedRef,
1415            RewriteRefusal::Stale,
1416            RewriteRefusal::ToolMissing,
1417            RewriteRefusal::ScriptFailed,
1418            RewriteRefusal::Purged,
1419            RewriteRefusal::SignatureChoiceNeeded,
1420            RewriteRefusal::ExtractModeNeeded,
1421        ];
1422        let codes: HashSet<_> = all.iter().map(|r| r.code()).collect();
1423        assert_eq!(codes.len(), all.len());
1424        for r in all {
1425            assert_eq!(
1426                serde_json::to_string(&r).unwrap(),
1427                format!("\"{}\"", r.code())
1428            );
1429        }
1430    }
1431}