Skip to main content

release_kit/
config.rs

1//! The committed target answers, parsed strictly and written from authored text.
2//! Comparisons continue to use the landing record alone.
3
4pub mod floors;
5
6use std::collections::BTreeMap;
7use std::fmt::Write as _;
8use std::path::Path;
9
10use crate::diagnostic::{Diagnostic, Reason};
11use crate::error::RkError;
12use crate::landing::{Style, Workflow};
13use serde::Deserialize;
14
15/// The committed input, relative to the target root.
16pub const CONFIG_PATH: &str = ".release-kit/config.toml";
17/// The only supported configuration schema.
18pub const SCHEMA_VERSION: i64 = 1;
19
20/// Per-target answers; an omitted table uses its compiled defaults.
21#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
22#[serde(deny_unknown_fields, default)]
23pub struct Config {
24    /// Version of the authored configuration shape.
25    pub schema_version: i64,
26    /// Landing identity and trunk name.
27    pub project: Project,
28    /// Values resolved into the landing record.
29    pub landing: Landing,
30    /// Report-routing facts, currently not rendered into any payload.
31    pub security: Security,
32    /// Forge setup inputs.
33    pub setup: Setup,
34    /// Names and floored policy.
35    pub protection: Protection,
36}
37
38impl Default for Config {
39    fn default() -> Self {
40        Self {
41            schema_version: SCHEMA_VERSION,
42            project: Project::default(),
43            landing: Landing::default(),
44            security: Security::default(),
45            setup: Setup::default(),
46            protection: Protection::default(),
47        }
48    }
49}
50
51/// The `project` table.
52#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
53#[serde(deny_unknown_fields, default)]
54pub struct Project {
55    /// P: project path on the forge, nested groups included.
56    pub repo: String,
57    /// P: github or gitlab; empty means detect.
58    pub forge: String,
59    /// P: payload binding; empty means detect.
60    pub tech: String,
61    /// P: the one permanent branch, rendered into every landed artifact
62    /// that names it. Absent means the landing has not answered it, so a
63    /// record's own answer survives an upgrade that predates the key.
64    pub trunk: Option<String>,
65}
66
67/// The compiled trunk, used where neither a configuration nor a record answers.
68pub const TRUNK_DEFAULT: &str = "master";
69
70/// The compiled release-line prefix, used where nothing else answers.
71pub const LINE_PREFIX_DEFAULT: &str = "release/";
72
73/// The `landing` table.
74#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
75#[serde(deny_unknown_fields, default)]
76pub struct Landing {
77    /// P: worktree or branches.
78    pub workflow: Option<Workflow>,
79    /// P: trunk or lines.
80    pub style: Option<Style>,
81    /// P: opt-in Nix capability.
82    pub nix: Option<bool>,
83}
84
85/// The `security` table.
86#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
87#[serde(deny_unknown_fields, default)]
88pub struct Security {
89    /// N: project receiving vulnerability reports.
90    pub advisories: String,
91    /// P: contact when the forge channel is unavailable, rendered into the
92    /// landed policy. Absent means the landing has not answered it, so a
93    /// record's own answer survives an upgrade that predates the key; an
94    /// explicit empty string resets the policy to the forge's own prose.
95    pub contact: Option<String>,
96    /// P: the acknowledgment window the landed policy promises. Absent
97    /// means unanswered, exactly as `contact` does.
98    pub response: Option<String>,
99}
100
101/// The compiled response stance, used where nothing else answers: the
102/// policy promises no window at all.
103pub const RESPONSE_DEFAULT: &str = "best-effort";
104
105/// The canonical form of a security contact, or why it is refused.
106///
107/// One trimmed line. The value is rendered into `SECURITY.md` verbatim, so
108/// a line feed, a carriage return, or any other ASCII control character
109/// would break the sentence it lands in and is refused before any write.
110/// Emptiness is not a refusal: it selects the forge's own authored prose.
111///
112/// # Errors
113/// The refusal text, naming the key and what it accepts.
114pub fn canonical_contact(raw: &str) -> Result<String, String> {
115    let trimmed = raw.trim();
116    if trimmed.chars().any(char::is_control) {
117        return Err(format!(
118            "security.contact carries a control character; it is one line naming an address, a URL, a person, or a team, and empty selects the forge's own wording, found {trimmed:?}"
119        ));
120    }
121    Ok(trimmed.to_owned())
122}
123
124/// The canonical form of a response stance, or why it is refused.
125///
126/// Either `best-effort` or a plural-correct day count: `1 day`, `<n> days`,
127/// `1 business day`, or `<n> business days`, with `n` a `u32` above one
128/// written without a sign or a leading zero. The grammar is narrow because
129/// the rendered sentence is a public promise, and only a value this
130/// renderer can state exactly may reach it. An empty value reads as the
131/// compiled default.
132///
133/// # Errors
134/// The refusal text, naming the key and every accepted form.
135pub fn canonical_response(raw: &str) -> Result<String, String> {
136    let trimmed = raw.trim();
137    if trimmed.is_empty() || trimmed == RESPONSE_DEFAULT {
138        return Ok(RESPONSE_DEFAULT.to_owned());
139    }
140    let refusal = || {
141        format!(
142            "security.response must be one of: best-effort, 1 day, <n> days, 1 business day, <n> business days, where n is a whole number above one; found {trimmed:?}"
143        )
144    };
145    let (count, unit) = trimmed.split_once(' ').ok_or_else(refusal)?;
146    let plural = match unit {
147        "day" | "business day" => false,
148        "days" | "business days" => true,
149        _ => return Err(refusal()),
150    };
151    let number: u32 = count.parse().map_err(|_| refusal())?;
152    // A canonical count round-trips, which refuses a sign and a leading
153    // zero without a second pass over the text.
154    if count != number.to_string() || (number > 1) != plural {
155        return Err(refusal());
156    }
157    Ok(trimmed.to_owned())
158}
159
160/// The `setup` table.
161#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
162#[serde(deny_unknown_fields, default)]
163pub struct Setup {
164    /// N: the check the merge must pass.
165    pub required_check: String,
166    /// N: long-lived branches retired by the trunk.
167    pub retired_branches: Vec<String>,
168    /// P: release-line branch prefix, rendered into the release triggers
169    /// and branch guards a landing writes. Absent means unanswered, so a
170    /// record's own answer survives an upgrade that predates the key.
171    pub line_prefix: Option<String>,
172    /// N: run release-line protection in a full apply.
173    pub release_lines: bool,
174    /// N: the steps this target does not run, each against the reason a
175    /// report prints. An exclusion narrows what the setup judges and
176    /// weakens no floor: every value a step the target still runs reads is
177    /// floored exactly as before.
178    pub excluded_steps: BTreeMap<String, String>,
179    /// Public bot identity.
180    pub bot: Bot,
181}
182
183impl Default for Setup {
184    fn default() -> Self {
185        Self {
186            required_check: String::new(),
187            retired_branches: vec!["main".into(), "develop".into()],
188            line_prefix: None,
189            release_lines: false,
190            excluded_steps: BTreeMap::new(),
191            bot: Bot::default(),
192        }
193    }
194}
195
196/// The `setup.bot` table.
197///
198/// The App's public identifier and nothing else. The installation id is
199/// not here: it is the forge's own state, one cheap call answers it, and a
200/// cached copy that goes stale buys a refusal the operator must resolve by
201/// hand. The private key and the token are never here at all.
202#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
203#[serde(deny_unknown_fields, default)]
204pub struct Bot {
205    /// N: public App identifier; private credentials stay outside this file.
206    pub app_id: String,
207    /// Accepted and ignored. Version 0.3.13 wrote this key, so a target
208    /// landed by it must still parse; nothing reads the value and no new
209    /// configuration carries it. Removing it outright would refuse every
210    /// such target, because this reader denies an unknown key by design.
211    #[serde(default, skip_serializing)]
212    pub installation_id: Option<i64>,
213}
214
215/// The `protection` table.
216#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
217#[serde(deny_unknown_fields, default)]
218#[allow(
219    clippy::struct_excessive_bools,
220    reason = "these are independent policy switches in the committed TOML schema, not a state machine a smaller type could carry"
221)]
222pub struct Protection {
223    /// N: trunk ruleset name. Absent derives `<trunk>-protection`, which
224    /// is the name the setup script built before the key existed, so a
225    /// target that states none keeps the ruleset it already has.
226    pub trunk_ruleset: Option<String>,
227    /// N: tag ruleset name.
228    pub tag_ruleset: String,
229    /// N: release-line ruleset name.
230    pub lines_ruleset: String,
231    /// N: title job context.
232    pub title_check: String,
233    /// F: invariant, covers every published version.
234    pub tag_pattern: String,
235    /// F: invariant, empty.
236    pub bypass_actors: Vec<String>,
237    /// F: invariant, exactly squash.
238    pub allowed_merge_methods: Vec<String>,
239    /// F: invariant, true.
240    pub strict_required_status_checks: bool,
241    /// F: invariant, contains all four rules.
242    pub owned_trunk_rules: Vec<String>,
243    /// F: floor zero; higher is stricter.
244    pub required_approving_review_count: i64,
245    /// F: floor false; true is stricter.
246    pub dismiss_stale_reviews_on_push: bool,
247    /// F: floor false; true is stricter.
248    pub require_code_owner_review: bool,
249    /// F: floor false; true is stricter.
250    pub require_last_push_approval: bool,
251    /// GitHub policy.
252    pub github: Github,
253    /// GitLab policy.
254    pub gitlab: Gitlab,
255}
256
257impl Default for Protection {
258    fn default() -> Self {
259        Self {
260            trunk_ruleset: None,
261            tag_ruleset: "release-tags".into(),
262            lines_ruleset: "release-lines".into(),
263            title_check: "pr-title".into(),
264            tag_pattern: "refs/tags/v*".into(),
265            bypass_actors: Vec::new(),
266            allowed_merge_methods: vec!["squash".into()],
267            strict_required_status_checks: true,
268            owned_trunk_rules: vec![
269                "deletion".into(),
270                "non_fast_forward".into(),
271                "pull_request".into(),
272                "required_status_checks".into(),
273            ],
274            required_approving_review_count: 0,
275            dismiss_stale_reviews_on_push: false,
276            require_code_owner_review: false,
277            require_last_push_approval: false,
278            github: Github::default(),
279            gitlab: Gitlab::default(),
280        }
281    }
282}
283
284impl Protection {
285    /// The trunk ruleset's name: the target's own answer, or the name the
286    /// setup script derived before the key existed.
287    #[must_use]
288    pub fn trunk_ruleset(&self, trunk: &str) -> String {
289        self.trunk_ruleset
290            .clone()
291            .unwrap_or_else(|| format!("{trunk}-protection"))
292    }
293}
294
295/// The `protection.github` table.
296#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
297#[serde(deny_unknown_fields, default)]
298pub struct Github {
299    /// F: invariant, `PR_TITLE`.
300    pub squash_title_source: String,
301    /// F: invariant, `PR_BODY`.
302    pub squash_body_source: String,
303}
304
305impl Default for Github {
306    fn default() -> Self {
307        Self {
308            squash_title_source: "PR_TITLE".into(),
309            squash_body_source: "PR_BODY".into(),
310        }
311    }
312}
313
314/// The `protection.gitlab` table.
315#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
316#[serde(deny_unknown_fields, default)]
317pub struct Gitlab {
318    /// F: invariant, linear history.
319    pub merge_method: String,
320    /// F: invariant, always squash.
321    pub squash_option: String,
322    /// F: invariant, references title and description.
323    pub squash_commit_template: String,
324    /// F: invariant, zero.
325    pub push_access_level: i64,
326    /// F: floor thirty.
327    pub merge_access_level: i64,
328}
329
330impl Default for Gitlab {
331    fn default() -> Self {
332        Self {
333            merge_method: "ff".into(),
334            squash_option: "always".into(),
335            squash_commit_template: include_str!("../blocks/gitlab-squash-commit-template.in")
336                .trim_end_matches('\n')
337                .to_owned(),
338            push_access_level: 0,
339            merge_access_level: 40,
340        }
341    }
342}
343
344/// Read the optional file; content errors refuse instead of falling back.
345///
346/// # Errors
347/// Returns a config-invalid refusal for invalid content, and preserves I/O errors.
348pub fn load(target: &Path) -> Result<Option<Config>, RkError> {
349    let text = match std::fs::read_to_string(target.join(CONFIG_PATH)) {
350        Ok(text) => text,
351        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
352        Err(error) => return Err(error.into()),
353    };
354    parse(&text).map(Some)
355}
356
357fn parse(text: &str) -> Result<Config, RkError> {
358    let raw: toml::Value =
359        toml::from_str(text).map_err(|error: toml::de::Error| invalid(error.to_string()))?;
360    if raw.get("schema_version").and_then(toml::Value::as_integer) != Some(SCHEMA_VERSION) {
361        return Err(invalid(format!("schema_version must be {SCHEMA_VERSION}")));
362    }
363    let config: Config = toml::from_str(text).map_err(|error: toml::de::Error| {
364        let mut message = error.to_string();
365        if let Some(rest) = error.message().strip_prefix("unknown field `") {
366            let names: Vec<_> = rest.split('`').collect();
367            if let Some(unknown) = names.first()
368                && let Some(nearest) = names
369                    .iter()
370                    .skip(2)
371                    .step_by(2)
372                    .min_by_key(|name| distance(unknown, name))
373            {
374                let _ = write!(message, "; nearest known key: {nearest}");
375            }
376        }
377        invalid(message)
378    })?;
379    if !config.project.forge.is_empty()
380        && crate::detect::Forge::parse(&config.project.forge).is_none()
381    {
382        return Err(invalid("project.forge must be github or gitlab"));
383    }
384    if !config.project.tech.is_empty()
385        && (config.project.tech.starts_with('_')
386            || crate::embedded::SNIPPETS
387                .get_dir(&config.project.tech)
388                .is_none())
389    {
390        return Err(invalid(
391            "project.tech must name a supported payload binding",
392        ));
393    }
394    if let Some(contact) = &config.security.contact {
395        canonical_contact(contact).map_err(invalid)?;
396    }
397    if let Some(response) = &config.security.response {
398        canonical_response(response).map_err(invalid)?;
399    }
400    exclusions(&config.setup.excluded_steps)?;
401    floors::check(&config)?;
402    Ok(config)
403}
404
405/// Judge the declared exclusions: every id names a step this binary runs,
406/// and every exclusion states why.
407///
408/// A reason is required because the exclusions are the audit trail. A
409/// reader must be able to tell a chosen subset from an incomplete setup,
410/// and a line that names a step and says nothing tells them neither.
411fn exclusions(excluded: &BTreeMap<String, String>) -> Result<(), RkError> {
412    for (name, reason) in excluded {
413        if crate::setup::steps::spec(name).is_none() {
414            let nearest = crate::setup::steps::STEPS
415                .iter()
416                .min_by_key(|step| distance(name, step.name))
417                .map_or("", |step| step.name);
418            return Err(invalid(format!(
419                "setup.excluded_steps names {name}, which is no setup step; nearest known step: {nearest}"
420            )));
421        }
422        if reason.trim().is_empty() {
423            return Err(invalid(format!(
424                "setup.excluded_steps names {name} with no reason; an excluded step is reported with why it is out of scope"
425            )));
426        }
427    }
428    Ok(())
429}
430
431pub(super) fn invalid(message: impl std::fmt::Display) -> RkError {
432    RkError::refusal(
433        Diagnostic::new(Reason::ConfigInvalid, format!("{CONFIG_PATH}: {message}"))
434            .action(format!("edit {CONFIG_PATH} and retry"))
435            .target_state("nothing was written"),
436    )
437}
438
439fn distance(left: &str, right: &str) -> usize {
440    let mut row: Vec<_> = (0..=right.chars().count()).collect();
441    for (i, a) in left.chars().enumerate() {
442        let mut previous = row[0];
443        row[0] = i + 1;
444        for (j, b) in right.chars().enumerate() {
445            let old = row[j + 1];
446            row[j + 1] = (previous + usize::from(a != b))
447                .min(row[j] + 1)
448                .min(old + 1);
449            previous = old;
450        }
451    }
452    row.last().copied().unwrap_or(0)
453}
454
455/// Write the authored template with TOML-escaped scalar substitutions.
456///
457/// # Errors
458/// Returns invalid configuration or I/O failures before or during the atomic write.
459pub fn write(target: &Path, config: &Config) -> Result<(), RkError> {
460    let bytes = render(config)?;
461    parse(&String::from_utf8_lossy(&bytes))?;
462    crate::atomic::write(&target.join(CONFIG_PATH), &bytes)?;
463    Ok(())
464}
465
466fn array(values: &[String]) -> toml_edit::Value {
467    toml_edit::Value::Array(values.iter().collect())
468}
469
470/// The exclusions as the one-line inline table the template carries. A
471/// landing writes an empty one; an operator who wants several may turn it
472/// into a `[setup.excluded_steps]` table, which this reader parses the
473/// same way.
474fn inline(values: &BTreeMap<String, String>) -> toml_edit::Value {
475    let mut table = toml_edit::InlineTable::new();
476    for (key, value) in values {
477        table.insert(key, value.clone().into());
478    }
479    toml_edit::Value::InlineTable(table)
480}
481
482#[allow(
483    clippy::too_many_lines,
484    reason = "the render list is one token per authored line of the config template, and splitting it would hide that correspondence"
485)]
486fn render(config: &Config) -> Result<Vec<u8>, RkError> {
487    // The trunk names the ruleset the setup installs, so the written
488    // configuration states the name a target actually gets rather than a
489    // literal that would be wrong for any trunk but the default.
490    let trunk = config
491        .project
492        .trunk
493        .clone()
494        .ok_or_else(|| invalid("project.trunk is unresolved"))?;
495    let mut fields: Vec<(&str, toml_edit::Value)> = vec![
496        ("RK_CONFIG_SCHEMA_VERSION", config.schema_version.into()),
497        ("RK_CONFIG_PROJECT_REPO", config.project.repo.clone().into()),
498        (
499            "RK_CONFIG_PROJECT_FORGE",
500            config.project.forge.clone().into(),
501        ),
502        ("RK_CONFIG_PROJECT_TECH", config.project.tech.clone().into()),
503        ("RK_CONFIG_PROJECT_TRUNK", trunk.clone().into()),
504        (
505            "RK_CONFIG_LANDING_WORKFLOW",
506            config
507                .landing
508                .workflow
509                .ok_or_else(|| invalid("landing.workflow is unresolved"))?
510                .as_str()
511                .into(),
512        ),
513        (
514            "RK_CONFIG_LANDING_STYLE",
515            config
516                .landing
517                .style
518                .ok_or_else(|| invalid("landing.style is unresolved"))?
519                .as_str()
520                .into(),
521        ),
522        (
523            "RK_CONFIG_LANDING_NIX",
524            config
525                .landing
526                .nix
527                .ok_or_else(|| invalid("landing.nix is unresolved"))?
528                .into(),
529        ),
530        (
531            "RK_CONFIG_SECURITY_ADVISORIES",
532            config.security.advisories.clone().into(),
533        ),
534        (
535            "RK_CONFIG_SECURITY_CONTACT",
536            config.security.contact.clone().unwrap_or_default().into(),
537        ),
538        (
539            "RK_CONFIG_SECURITY_RESPONSE",
540            config
541                .security
542                .response
543                .clone()
544                .unwrap_or_else(|| RESPONSE_DEFAULT.to_owned())
545                .into(),
546        ),
547        (
548            "RK_CONFIG_SETUP_REQUIRED_CHECK",
549            config.setup.required_check.clone().into(),
550        ),
551        (
552            "RK_CONFIG_SETUP_RETIRED_BRANCHES",
553            array(&config.setup.retired_branches),
554        ),
555        (
556            "RK_CONFIG_SETUP_LINE_PREFIX",
557            config
558                .setup
559                .line_prefix
560                .clone()
561                .ok_or_else(|| invalid("setup.line_prefix is unresolved"))?
562                .into(),
563        ),
564        (
565            "RK_CONFIG_SETUP_RELEASE_LINES",
566            config.setup.release_lines.into(),
567        ),
568        (
569            "RK_CONFIG_SETUP_EXCLUDED_STEPS",
570            inline(&config.setup.excluded_steps),
571        ),
572        (
573            "RK_CONFIG_SETUP_BOT_APP_ID",
574            config.setup.bot.app_id.clone().into(),
575        ),
576    ];
577    fields.extend(protection_fields(&config.protection, trunk.as_str()));
578    let template = crate::embedded::BLOCKS
579        .get_file("target-config.toml.in")
580        .and_then(include_dir::File::contents_utf8)
581        .ok_or_else(|| invalid("the binary lacks its configuration template"))?;
582    // Each authored line has one token. Substitute in the source line once,
583    // so a user's string containing another token stays literal.
584    let mut bytes = Vec::new();
585    for line in template.split_inclusive('\n') {
586        if let Some((token, value)) = fields.iter().find(|(token, _)| line.contains(token)) {
587            bytes.extend(crate::landing::substitute(
588                line.as_bytes(),
589                token.as_bytes(),
590                value.to_string().as_bytes(),
591            ));
592        } else {
593            bytes.extend_from_slice(line.as_bytes());
594        }
595    }
596    Ok(bytes)
597}
598
599fn protection_fields(
600    protection: &Protection,
601    trunk: &str,
602) -> Vec<(&'static str, toml_edit::Value)> {
603    vec![
604        (
605            "RK_CONFIG_PROTECTION_TRUNK_RULESET",
606            protection.trunk_ruleset(trunk).into(),
607        ),
608        (
609            "RK_CONFIG_PROTECTION_TAG_RULESET",
610            protection.tag_ruleset.clone().into(),
611        ),
612        (
613            "RK_CONFIG_PROTECTION_LINES_RULESET",
614            protection.lines_ruleset.clone().into(),
615        ),
616        (
617            "RK_CONFIG_PROTECTION_TITLE_CHECK",
618            protection.title_check.clone().into(),
619        ),
620        (
621            "RK_CONFIG_PROTECTION_TAG_PATTERN",
622            protection.tag_pattern.clone().into(),
623        ),
624        (
625            "RK_CONFIG_PROTECTION_BYPASS_ACTORS",
626            array(&protection.bypass_actors),
627        ),
628        (
629            "RK_CONFIG_PROTECTION_ALLOWED_MERGE_METHODS",
630            array(&protection.allowed_merge_methods),
631        ),
632        (
633            "RK_CONFIG_PROTECTION_STRICT_REQUIRED_STATUS_CHECKS",
634            protection.strict_required_status_checks.into(),
635        ),
636        (
637            "RK_CONFIG_PROTECTION_OWNED_TRUNK_RULES",
638            array(&protection.owned_trunk_rules),
639        ),
640        (
641            "RK_CONFIG_PROTECTION_REQUIRED_APPROVING_REVIEW_COUNT",
642            protection.required_approving_review_count.into(),
643        ),
644        (
645            "RK_CONFIG_PROTECTION_DISMISS_STALE_REVIEWS_ON_PUSH",
646            protection.dismiss_stale_reviews_on_push.into(),
647        ),
648        (
649            "RK_CONFIG_PROTECTION_REQUIRE_CODE_OWNER_REVIEW",
650            protection.require_code_owner_review.into(),
651        ),
652        (
653            "RK_CONFIG_PROTECTION_REQUIRE_LAST_PUSH_APPROVAL",
654            protection.require_last_push_approval.into(),
655        ),
656        (
657            "RK_CONFIG_PROTECTION_GITHUB_SQUASH_TITLE_SOURCE",
658            protection.github.squash_title_source.clone().into(),
659        ),
660        (
661            "RK_CONFIG_PROTECTION_GITHUB_SQUASH_BODY_SOURCE",
662            protection.github.squash_body_source.clone().into(),
663        ),
664        (
665            "RK_CONFIG_PROTECTION_GITLAB_MERGE_METHOD",
666            protection.gitlab.merge_method.clone().into(),
667        ),
668        (
669            "RK_CONFIG_PROTECTION_GITLAB_SQUASH_OPTION",
670            protection.gitlab.squash_option.clone().into(),
671        ),
672        (
673            "RK_CONFIG_PROTECTION_GITLAB_SQUASH_COMMIT_TEMPLATE",
674            protection.gitlab.squash_commit_template.clone().into(),
675        ),
676        (
677            "RK_CONFIG_PROTECTION_GITLAB_PUSH_ACCESS_LEVEL",
678            protection.gitlab.push_access_level.into(),
679        ),
680        (
681            "RK_CONFIG_PROTECTION_GITLAB_MERGE_ACCESS_LEVEL",
682            protection.gitlab.merge_access_level.into(),
683        ),
684    ]
685}
686
687/// Change one landing parameter while preserving comments and table ordering.
688///
689/// # Errors
690/// Refuses an invalid key, invalid resulting content, or unreadable file; writes atomically.
691pub fn rewrite_key(target: &Path, key: &str, value: toml_edit::Value) -> Result<(), RkError> {
692    let path = target.join(CONFIG_PATH);
693    let text = std::fs::read_to_string(&path)?;
694    let next = rewrite_text(&text, key, value)?;
695    crate::atomic::write(&path, next.as_bytes())?;
696    Ok(())
697}
698
699fn rewrite_text(text: &str, key: &str, mut value: toml_edit::Value) -> Result<String, RkError> {
700    if ![
701        "project.repo",
702        "project.forge",
703        "project.tech",
704        "project.trunk",
705        "landing.workflow",
706        "landing.style",
707        "landing.nix",
708        "security.contact",
709        "security.response",
710        "setup.line_prefix",
711    ]
712    .contains(&key)
713    {
714        return Err(invalid(format!("{key} is not a landing parameter")));
715    }
716    parse(text)?;
717    let mut document = text
718        .parse::<toml_edit::DocumentMut>()
719        .map_err(|error| invalid(error.to_string()))?;
720    let mut item = document.as_item_mut();
721    for segment in key.split('.') {
722        item = &mut item[segment];
723    }
724    if let Some(old) = item.as_value() {
725        if old
726            .as_str()
727            .zip(value.as_str())
728            .is_some_and(|(old, new)| old == new)
729            || old
730                .as_bool()
731                .zip(value.as_bool())
732                .is_some_and(|(old, new)| old == new)
733        {
734            return Ok(text.to_owned());
735        }
736        *value.decor_mut() = old.decor().clone();
737    }
738    *item = toml_edit::Item::Value(value);
739    let next = document.to_string();
740    parse(&next)?;
741    Ok(next)
742}
743
744/// Resolved landing input, including every key a preview would write.
745#[derive(Debug, Clone, serde::Serialize)]
746pub struct Plan {
747    /// Added or updated configuration.
748    pub action: &'static str,
749    /// Keys whose configured answers differ from the record.
750    pub changes: Vec<String>,
751    /// The exact authored TOML the apply writes.
752    pub content: String,
753}
754
755impl Plan {
756    /// Resolve the output without writing it; existing comments survive.
757    ///
758    /// # Errors
759    /// Propagates unreadable or invalid configuration.
760    pub fn new(
761        target: &Path,
762        params: &crate::landing::Params,
763        existing: Option<&Config>,
764        record: Option<&crate::landing::manifest::Manifest>,
765    ) -> Result<Self, RkError> {
766        let text = existing
767            .map(|_| std::fs::read_to_string(target.join(CONFIG_PATH)))
768            .transpose()?;
769        Self::compose(text.as_deref(), params, existing, record)
770    }
771
772    /// Resolve the output from the existing text already read, so a
773    /// planner that owns no filesystem can compose it from its
774    /// observation; existing comments survive.
775    ///
776    /// # Errors
777    /// Propagates invalid configuration.
778    pub fn compose(
779        text: Option<&str>,
780        params: &crate::landing::Params,
781        existing: Option<&Config>,
782        record: Option<&crate::landing::manifest::Manifest>,
783    ) -> Result<Self, RkError> {
784        let mut resolved = existing.cloned().unwrap_or_default();
785        resolved.project.tech = params.tech().into();
786        resolved.project.forge = params.forge().into();
787        resolved.project.repo = params.repo().into();
788        resolved.landing = Landing {
789            workflow: Some(params.workflow()),
790            style: params.style(),
791            nix: Some(params.nix()),
792        };
793        resolved.project.trunk = Some(params.trunk().to_owned());
794        resolved.setup.line_prefix = Some(params.line_prefix().to_owned());
795        resolved.security.contact = Some(params.security_contact().to_owned());
796        resolved.security.response = Some(params.security_response().to_owned());
797        let content = if let Some(text) = text.filter(|_| existing.is_some()) {
798            let mut text = text.to_owned();
799            for (key, value) in parameter_values(&resolved) {
800                text = rewrite_text(&text, key, value)?;
801            }
802            text
803        } else {
804            String::from_utf8(render(&resolved)?).map_err(|e| invalid(e.to_string()))?
805        };
806        parse(&content)?;
807        Ok(Self {
808            action: if existing.is_some() {
809                "updated"
810            } else {
811                "added"
812            },
813            changes: record.map_or_else(Vec::new, |record| pending(&resolved, record)),
814            content,
815        })
816    }
817
818    /// Write the prepared configuration before the landing record.
819    ///
820    /// # Errors
821    /// Propagates an atomic write failure.
822    pub fn apply(&self, target: &Path) -> Result<(), RkError> {
823        crate::atomic::write(&target.join(CONFIG_PATH), self.content.as_bytes())?;
824        Ok(())
825    }
826}
827
828fn parameter_values(config: &Config) -> Vec<(&'static str, toml_edit::Value)> {
829    let mut values = Vec::new();
830    for (key, value) in [
831        ("project.repo", &config.project.repo),
832        ("project.forge", &config.project.forge),
833        ("project.tech", &config.project.tech),
834    ] {
835        if !value.is_empty() {
836            values.push((key, value.clone().into()));
837        }
838    }
839    if let Some(value) = config.landing.workflow {
840        values.push(("landing.workflow", value.as_str().into()));
841    }
842    if let Some(value) = config.landing.style {
843        values.push(("landing.style", value.as_str().into()));
844    }
845    if let Some(value) = config.landing.nix {
846        values.push(("landing.nix", value.into()));
847    }
848    if let Some(value) = config.project.trunk.clone() {
849        values.push(("project.trunk", value.into()));
850    }
851    if let Some(value) = config.setup.line_prefix.clone() {
852        values.push(("setup.line_prefix", value.into()));
853    }
854    // An empty contact is an answer, not an absence: it resets the landed
855    // policy to the forge's own prose, so it projects like any other value.
856    if let Some(value) = config.security.contact.clone() {
857        values.push(("security.contact", value.into()));
858    }
859    if let Some(value) = config.security.response.clone() {
860        values.push(("security.response", value.into()));
861    }
862    values
863}
864
865/// Only explicit class P answers can be pending; comparisons still use the record.
866#[must_use]
867pub fn pending(config: &Config, record: &crate::landing::manifest::Manifest) -> Vec<String> {
868    let mut recorded = Config::default();
869    recorded.project.repo.clone_from(&record.parameters.repo);
870    recorded.project.forge.clone_from(&record.forge);
871    recorded.project.tech.clone_from(&record.tech);
872    recorded.landing = Landing {
873        workflow: Some(record.parameters.workflow),
874        style: record.parameters.style,
875        nix: Some(record.parameters.nix),
876    };
877    recorded.project.trunk = Some(record.parameters.trunk.clone());
878    recorded.setup.line_prefix = Some(record.parameters.line_prefix.clone());
879    recorded.security.contact = Some(record.parameters.security_contact.clone());
880    recorded.security.response = Some(record.parameters.security_response.clone());
881    let baseline = parameter_values(&recorded);
882    parameter_values(config)
883        .into_iter()
884        .filter(|(key, value)| {
885            !baseline
886                .iter()
887                .any(|(other, old)| key == other && value.to_string() == old.to_string())
888        })
889        .map(|(key, _)| key.to_owned())
890        .collect()
891}
892
893/// The trunk accessor for callers without a setup context.
894///
895/// # Errors
896/// Propagates invalid configuration and I/O failures.
897pub fn trunk_of(target: &Path) -> Result<String, RkError> {
898    Ok(load(target)?
899        .and_then(|config| config.project.trunk)
900        .unwrap_or_else(|| TRUNK_DEFAULT.to_owned()))
901}
902
903/// The release-line prefix for callers without a setup context.
904///
905/// # Errors
906/// Propagates invalid configuration and I/O failures.
907pub fn line_prefix_of(target: &Path) -> Result<String, RkError> {
908    Ok(load(target)?
909        .and_then(|config| config.setup.line_prefix)
910        .unwrap_or_else(|| LINE_PREFIX_DEFAULT.to_owned()))
911}
912
913#[cfg(test)]
914mod tests {
915    use super::{CONFIG_PATH, Config, load, parse, rewrite_key, trunk_of, write};
916    use crate::landing::{Style, Workflow};
917
918    #[test]
919    fn an_omitted_landing_key_is_distinguishable_from_an_explicit_default() {
920        let omitted = parse("schema_version = 1\n").expect("omitted answers parse");
921        let explicit = parse(
922            "schema_version = 1\n[landing]\nworkflow = 'worktree'\nstyle = 'trunk'\nnix = false\n",
923        )
924        .expect("explicit defaults parse");
925        assert_eq!(omitted.landing, super::Landing::default());
926        assert_eq!(explicit.landing.workflow, Some(Workflow::Worktree));
927        assert_eq!(explicit.landing.style, Some(Style::Trunk));
928        assert_eq!(explicit.landing.nix, Some(false));
929        assert_ne!(omitted, explicit);
930    }
931
932    /// A configuration written by 0.3.13 carries `installation_id`, which
933    /// this version reads and ignores. Refusing it would strand every
934    /// target that release landed.
935    #[test]
936    fn a_config_from_the_release_that_wrote_installation_id_still_reads() {
937        let dir = tempfile::tempdir().expect("a tempdir");
938        std::fs::create_dir_all(dir.path().join(".release-kit")).expect("the directory exists");
939        std::fs::write(
940            dir.path().join(CONFIG_PATH),
941            "schema_version = 1\n\n[setup.bot]\napp_id = \"123\"\ninstallation_id = 0\n",
942        )
943        .expect("the config writes");
944        let held = load(dir.path())
945            .expect("the config reads")
946            .expect("it is present");
947        assert_eq!(held.setup.bot.app_id, "123");
948        assert_eq!(
949            held.setup.bot.installation_id,
950            Some(0),
951            "the key parses; nothing reads it"
952        );
953    }
954
955    #[test]
956    fn the_landed_config_template_round_trips() {
957        let dir = tempfile::tempdir().expect("a target exists");
958        let mut config = Config::default();
959        config.project.repo = "acme/nested/widget".into();
960        config.project.forge = "gitlab".into();
961        config.project.tech = "bash".into();
962        config.project.trunk = Some("main".into());
963        config.landing.workflow = Some(Workflow::Branches);
964        config.landing.style = Some(Style::Lines);
965        config.landing.nix = Some(true);
966        // The escaping subject moved to the one unrestricted string in this
967        // table: `contact` is now a class P value the reader holds to a
968        // single control-free line, so it can carry neither.
969        config.security.advisories =
970            "A \"quoted\" project\nRK_CONFIG_SECURITY_RESPONSE\\end".into();
971        config.security.contact = Some("security team, room 3 \"the vault\"".into());
972        config.security.response = Some("14 business days".into());
973        config.setup.required_check = "build / test".into();
974        config.setup.retired_branches = vec!["develop".into(), "old\"branch".into()];
975        config.setup.line_prefix = Some("stable/".into());
976        config.setup.release_lines = true;
977        config.setup.excluded_steps = [
978            (
979                "package-check".to_owned(),
980                "nothing is published".to_owned(),
981            ),
982            (
983                "protect-trunk".to_owned(),
984                "this project merges \"locally\"".to_owned(),
985            ),
986        ]
987        .into_iter()
988        .collect();
989        config.setup.bot.app_id = "123".into();
990        config.protection.trunk_ruleset = Some("primary".into());
991        config.protection.tag_ruleset = "versions".into();
992        config.protection.lines_ruleset = "maintenance".into();
993        config.protection.title_check = "intent".into();
994        config.protection.tag_pattern = "refs/tags/*".into();
995        config
996            .protection
997            .owned_trunk_rules
998            .push("required_signatures".into());
999        config.protection.required_approving_review_count = 2;
1000        config.protection.dismiss_stale_reviews_on_push = true;
1001        config.protection.require_code_owner_review = true;
1002        config.protection.require_last_push_approval = true;
1003        config.protection.gitlab.squash_commit_template =
1004            "%{title}\n\nContext: %{description}".into();
1005        config.protection.gitlab.merge_access_level = 40;
1006        let defaults = Config {
1007            landing: super::Landing {
1008                workflow: Some(Workflow::Worktree),
1009                style: Some(Style::Trunk),
1010                nix: Some(false),
1011            },
1012            project: super::Project {
1013                trunk: Some(super::TRUNK_DEFAULT.into()),
1014                ..super::Project::default()
1015            },
1016            setup: super::Setup {
1017                line_prefix: Some(super::LINE_PREFIX_DEFAULT.into()),
1018                ..super::Setup::default()
1019            },
1020            // Writing states both security answers, so a reader sees the
1021            // policy the target landed rather than an implied one.
1022            security: super::Security {
1023                contact: Some(String::new()),
1024                response: Some(super::RESPONSE_DEFAULT.into()),
1025                ..super::Security::default()
1026            },
1027            // Writing resolves the derived ruleset name, so the file states
1028            // the name the setup installs rather than leaving it implied.
1029            protection: super::Protection {
1030                trunk_ruleset: Some(format!("{}-protection", super::TRUNK_DEFAULT)),
1031                ..super::Protection::default()
1032            },
1033            ..Config::default()
1034        };
1035        for expected in [defaults, config] {
1036            write(dir.path(), &expected).expect("the template renders");
1037            assert_eq!(load(dir.path()).expect("the config reads"), Some(expected));
1038            let text =
1039                std::fs::read_to_string(dir.path().join(CONFIG_PATH)).expect("the text reads");
1040            assert!(text.contains("# P: project path"));
1041            assert!(text.contains("# F: invariant"));
1042        }
1043    }
1044
1045    #[test]
1046    fn a_config_with_an_unknown_key_refuses_by_name() {
1047        for (table, typo, nearest) in [
1048            ("", "schemax_version", "schema_version"),
1049            ("project", "trunkx", "trunk"),
1050            ("landing", "stile", "style"),
1051            ("security", "contactx", "contact"),
1052            ("setup", "required_checkx", "required_check"),
1053            ("setup.bot", "app_i", "app_id"),
1054            ("protection", "trunk_rulesett", "trunk_ruleset"),
1055            (
1056                "protection.github",
1057                "squash_body_sourcex",
1058                "squash_body_source",
1059            ),
1060            ("protection.gitlab", "squash_optionx", "squash_option"),
1061        ] {
1062            let header = if table.is_empty() {
1063                String::new()
1064            } else {
1065                format!("[{table}]\n")
1066            };
1067            let text = format!("schema_version = 1\n{header}{typo} = 'value'\n");
1068            let error = parse(&text).expect_err("unknown keys refuse").to_string();
1069            for expected in [CONFIG_PATH, typo, &format!("nearest known key: {nearest}")] {
1070                assert!(error.contains(expected), "{error}");
1071            }
1072        }
1073    }
1074
1075    /// An exclusion removes a step from scope, so a typo in one would
1076    /// silently keep judging a step the target does not run, and a
1077    /// reasonless one would leave a report nobody can audit.
1078    #[test]
1079    fn an_exclusion_names_a_real_step_and_states_why() {
1080        for (text, expected) in [
1081            (
1082                "[setup.excluded_steps]\nprotect-trunkk = 'we merge locally'\n",
1083                vec!["protect-trunkk", "nearest known step: protect-trunk"],
1084            ),
1085            (
1086                "[setup.excluded_steps]\nprotect-trunk = '  '\n",
1087                vec!["protect-trunk", "no reason"],
1088            ),
1089        ] {
1090            let error = parse(&format!("schema_version = 1\n{text}"))
1091                .expect_err("the exclusion refuses")
1092                .to_string();
1093            for want in expected {
1094                assert!(error.contains(want), "{error}");
1095            }
1096        }
1097        let held = parse(
1098            "schema_version = 1\n[setup.excluded_steps]\nprotect-trunk = 'we merge locally'\n",
1099        )
1100        .expect("a named step with a reason parses");
1101        assert_eq!(
1102            held.setup
1103                .excluded_steps
1104                .get("protect-trunk")
1105                .map(String::as_str),
1106            Some("we merge locally")
1107        );
1108    }
1109
1110    /// An exclusion narrows what the setup judges. It never weakens the
1111    /// method's policy, so the floors bind a target that runs a subset
1112    /// exactly as they bind one that runs every step.
1113    #[test]
1114    fn an_exclusion_does_not_lift_a_floor() {
1115        let error = parse(
1116            "schema_version = 1\n[setup.excluded_steps]\nprotect-trunk = 'we merge locally'\n\n[protection]\nallowed_merge_methods = ['squash', 'merge']\n",
1117        )
1118        .expect_err("the floor binds an excluded step's keys too")
1119        .to_string();
1120        assert!(
1121            error.contains("protection.allowed_merge_methods"),
1122            "{error}"
1123        );
1124    }
1125
1126    #[test]
1127    fn a_config_at_an_unknown_schema_refuses() {
1128        for text in ["schema_version = 999", "schema_version = '1'", ""] {
1129            let error = parse(text)
1130                .expect_err("a schema must be declared and known")
1131                .to_string();
1132            assert!(
1133                error.contains(CONFIG_PATH) && error.contains("schema_version"),
1134                "{error}"
1135            );
1136        }
1137    }
1138
1139    #[test]
1140    fn an_unparsable_config_refuses_naming_the_position() {
1141        let error = parse("schema_version = 1\n[project\n")
1142            .expect_err("bad TOML refuses")
1143            .to_string();
1144        for expected in [CONFIG_PATH, "line 2", "column"] {
1145            assert!(error.contains(expected), "{error}");
1146        }
1147    }
1148
1149    #[test]
1150    fn an_absent_config_reads_as_none() {
1151        let dir = tempfile::tempdir().expect("a target exists");
1152        assert_eq!(load(dir.path()).expect("absence is compatible"), None);
1153        assert_eq!(trunk_of(dir.path()).expect("the default reads"), "master");
1154    }
1155
1156    #[test]
1157    fn loading_checks_floors_and_trunk_of_propagates_invalid_content() {
1158        let dir = tempfile::tempdir().expect("a target exists");
1159        std::fs::create_dir(dir.path().join(".release-kit")).expect("the directory exists");
1160        std::fs::write(
1161            dir.path().join(CONFIG_PATH),
1162            "schema_version = 1\n[protection]\nstrict_required_status_checks = false\n",
1163        )
1164        .expect("a config exists");
1165        let error =
1166            trunk_of(dir.path()).expect_err("invalid policy refuses even through the accessor");
1167        assert_eq!(error.exit_code(), 73);
1168        assert!(
1169            error
1170                .to_string()
1171                .contains("protection.strict_required_status_checks")
1172        );
1173    }
1174
1175    #[test]
1176    fn rewrite_key_preserves_comments() {
1177        let dir = tempfile::tempdir().expect("a target exists");
1178        std::fs::create_dir(dir.path().join(".release-kit")).expect("the directory exists");
1179        let original = "# Project answers\nschema_version = 1\n\n[security] # first table stays first\ncontact = 'team' # keep me\n\n[landing]\n# Our release choice\nstyle  = 'trunk'  # keep this reason\nworkflow = 'branches'\n";
1180        let path = dir.path().join(CONFIG_PATH);
1181        std::fs::write(&path, original).expect("a config exists");
1182        rewrite_key(dir.path(), "landing.style", "lines".into()).expect("the style writes back");
1183        let text = std::fs::read_to_string(&path).expect("the text reads");
1184        assert_eq!(text, original.replace("'trunk'", "\"lines\""));
1185        assert_eq!(
1186            load(dir.path())
1187                .expect("the config reads")
1188                .expect("present")
1189                .landing
1190                .style,
1191            Some(Style::Lines)
1192        );
1193        rewrite_key(dir.path(), "project.repo", "acme/widget".into())
1194            .expect("an omitted table can be added");
1195        assert_eq!(
1196            load(dir.path())
1197                .expect("reads")
1198                .expect("present")
1199                .project
1200                .repo,
1201            "acme/widget"
1202        );
1203        rewrite_key(
1204            dir.path(),
1205            "security.contact",
1206            "security@acme.example".into(),
1207        )
1208        .expect("the contact is a landing parameter now");
1209        rewrite_key(dir.path(), "security.response", "14 days".into())
1210            .expect("the response is a landing parameter now");
1211        let held = load(dir.path()).expect("reads").expect("present");
1212        assert_eq!(
1213            held.security.contact.as_deref(),
1214            Some("security@acme.example")
1215        );
1216        assert_eq!(held.security.response.as_deref(), Some("14 days"));
1217        let text = std::fs::read_to_string(&path).expect("the text reads");
1218        assert!(text.contains("# keep me"), "the comment survives: {text}");
1219        let before = std::fs::read(&path).expect("the bytes read");
1220        for (key, value) in [
1221            ("security.advisories", "acme/private"),
1222            ("security.response", "90d"),
1223            ("landing.style", "unknown"),
1224        ] {
1225            assert!(rewrite_key(dir.path(), key, value.into()).is_err());
1226            assert_eq!(std::fs::read(&path).expect("the bytes read"), before);
1227        }
1228    }
1229
1230    /// The two security answers are one line and one narrow grammar,
1231    /// because both land verbatim in a public policy.
1232    #[test]
1233    fn the_security_answers_are_held_to_their_grammar() {
1234        for value in ["team@acme.example", "  https://acme.example/report  ", ""] {
1235            super::canonical_contact(value).expect("a control-free line is a contact");
1236        }
1237        for value in ["one\ntwo", "one\rtwo", "one\u{7}two"] {
1238            let refusal = super::canonical_contact(value).expect_err("a control character refuses");
1239            assert!(refusal.contains("security.contact"), "{refusal}");
1240        }
1241        assert_eq!(
1242            super::canonical_contact("  team@acme.example  "),
1243            Ok("team@acme.example".to_owned()),
1244            "surrounding whitespace is trimmed"
1245        );
1246        for value in [
1247            "best-effort",
1248            "1 day",
1249            "2 days",
1250            "14 days",
1251            "1 business day",
1252            "14 business days",
1253        ] {
1254            assert_eq!(super::canonical_response(value), Ok(value.to_owned()));
1255        }
1256        assert_eq!(
1257            super::canonical_response(""),
1258            Ok(super::RESPONSE_DEFAULT.to_owned()),
1259            "an empty answer reads as the compiled default"
1260        );
1261        for value in [
1262            "0 days",
1263            "1 days",
1264            "2 day",
1265            "+2 days",
1266            "02 days",
1267            "4294967296 days",
1268            "90d",
1269            "two days",
1270            "we answer quickly",
1271            "2 weeks",
1272        ] {
1273            let refusal =
1274                super::canonical_response(value).expect_err("an unstateable window refuses");
1275            assert!(refusal.contains("security.response"), "{value}: {refusal}");
1276            assert!(refusal.contains("business days"), "{value}: {refusal}");
1277        }
1278        let refusal = parse("schema_version = 1\n[security]\nresponse = '90d'\n")
1279            .expect_err("the reader refuses it too")
1280            .to_string();
1281        assert!(refusal.contains("security.response"), "{refusal}");
1282    }
1283}