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 landed file.
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: the 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("project.tech must name a supported binding"));
391    }
392    if let Some(contact) = &config.security.contact {
393        canonical_contact(contact).map_err(invalid)?;
394    }
395    if let Some(response) = &config.security.response {
396        canonical_response(response).map_err(invalid)?;
397    }
398    exclusions(&config.setup.excluded_steps)?;
399    floors::check(&config)?;
400    Ok(config)
401}
402
403/// Judge the declared exclusions: every id names a step this binary runs,
404/// and every exclusion states why.
405///
406/// A reason is required because the exclusions are the audit trail. A
407/// reader must be able to tell a chosen subset from an incomplete setup,
408/// and a line that names a step and says nothing tells them neither.
409fn exclusions(excluded: &BTreeMap<String, String>) -> Result<(), RkError> {
410    for (name, reason) in excluded {
411        if crate::setup::steps::spec(name).is_none() {
412            let nearest = crate::setup::steps::STEPS
413                .iter()
414                .min_by_key(|step| distance(name, step.name))
415                .map_or("", |step| step.name);
416            return Err(invalid(format!(
417                "setup.excluded_steps names {name}, which is no setup step; nearest known step: {nearest}"
418            )));
419        }
420        if reason.trim().is_empty() {
421            return Err(invalid(format!(
422                "setup.excluded_steps names {name} with no reason; an excluded step is reported with why it is out of scope"
423            )));
424        }
425    }
426    Ok(())
427}
428
429pub(super) fn invalid(message: impl std::fmt::Display) -> RkError {
430    RkError::refusal(
431        Diagnostic::new(Reason::ConfigInvalid, format!("{CONFIG_PATH}: {message}"))
432            .action(format!("edit {CONFIG_PATH} and retry"))
433            .target_state("nothing was written"),
434    )
435}
436
437fn distance(left: &str, right: &str) -> usize {
438    let mut row: Vec<_> = (0..=right.chars().count()).collect();
439    for (i, a) in left.chars().enumerate() {
440        let mut previous = row[0];
441        row[0] = i + 1;
442        for (j, b) in right.chars().enumerate() {
443            let old = row[j + 1];
444            row[j + 1] = (previous + usize::from(a != b))
445                .min(row[j] + 1)
446                .min(old + 1);
447            previous = old;
448        }
449    }
450    row.last().copied().unwrap_or(0)
451}
452
453/// Write the authored template with TOML-escaped scalar substitutions.
454///
455/// # Errors
456/// Returns invalid configuration or I/O failures before or during the atomic write.
457pub fn write(target: &Path, config: &Config) -> Result<(), RkError> {
458    let bytes = render(config)?;
459    parse(&String::from_utf8_lossy(&bytes))?;
460    crate::atomic::write(&target.join(CONFIG_PATH), &bytes)?;
461    Ok(())
462}
463
464fn array(values: &[String]) -> toml_edit::Value {
465    toml_edit::Value::Array(values.iter().collect())
466}
467
468/// The exclusions as the one-line inline table the template carries. A
469/// landing writes an empty one; an operator who wants several may turn it
470/// into a `[setup.excluded_steps]` table, which this reader parses the
471/// same way.
472fn inline(values: &BTreeMap<String, String>) -> toml_edit::Value {
473    let mut table = toml_edit::InlineTable::new();
474    for (key, value) in values {
475        table.insert(key, value.clone().into());
476    }
477    toml_edit::Value::InlineTable(table)
478}
479
480#[allow(
481    clippy::too_many_lines,
482    reason = "the render list is one token per authored line of the config template, and splitting it would hide that correspondence"
483)]
484fn render(config: &Config) -> Result<Vec<u8>, RkError> {
485    // The trunk names the ruleset the setup installs, so the written
486    // configuration states the name a target actually gets rather than a
487    // literal that would be wrong for any trunk but the default.
488    let trunk = config
489        .project
490        .trunk
491        .clone()
492        .ok_or_else(|| invalid("project.trunk is unresolved"))?;
493    let mut fields: Vec<(&str, toml_edit::Value)> = vec![
494        ("RK_CONFIG_SCHEMA_VERSION", config.schema_version.into()),
495        ("RK_CONFIG_PROJECT_REPO", config.project.repo.clone().into()),
496        (
497            "RK_CONFIG_PROJECT_FORGE",
498            config.project.forge.clone().into(),
499        ),
500        ("RK_CONFIG_PROJECT_TECH", config.project.tech.clone().into()),
501        ("RK_CONFIG_PROJECT_TRUNK", trunk.clone().into()),
502        (
503            "RK_CONFIG_LANDING_WORKFLOW",
504            config
505                .landing
506                .workflow
507                .ok_or_else(|| invalid("landing.workflow is unresolved"))?
508                .as_str()
509                .into(),
510        ),
511        (
512            "RK_CONFIG_LANDING_STYLE",
513            config
514                .landing
515                .style
516                .ok_or_else(|| invalid("landing.style is unresolved"))?
517                .as_str()
518                .into(),
519        ),
520        (
521            "RK_CONFIG_LANDING_NIX",
522            config
523                .landing
524                .nix
525                .ok_or_else(|| invalid("landing.nix is unresolved"))?
526                .into(),
527        ),
528        (
529            "RK_CONFIG_SECURITY_ADVISORIES",
530            config.security.advisories.clone().into(),
531        ),
532        (
533            "RK_CONFIG_SECURITY_CONTACT",
534            config.security.contact.clone().unwrap_or_default().into(),
535        ),
536        (
537            "RK_CONFIG_SECURITY_RESPONSE",
538            config
539                .security
540                .response
541                .clone()
542                .unwrap_or_else(|| RESPONSE_DEFAULT.to_owned())
543                .into(),
544        ),
545        (
546            "RK_CONFIG_SETUP_REQUIRED_CHECK",
547            config.setup.required_check.clone().into(),
548        ),
549        (
550            "RK_CONFIG_SETUP_RETIRED_BRANCHES",
551            array(&config.setup.retired_branches),
552        ),
553        (
554            "RK_CONFIG_SETUP_LINE_PREFIX",
555            config
556                .setup
557                .line_prefix
558                .clone()
559                .ok_or_else(|| invalid("setup.line_prefix is unresolved"))?
560                .into(),
561        ),
562        (
563            "RK_CONFIG_SETUP_RELEASE_LINES",
564            config.setup.release_lines.into(),
565        ),
566        (
567            "RK_CONFIG_SETUP_EXCLUDED_STEPS",
568            inline(&config.setup.excluded_steps),
569        ),
570        (
571            "RK_CONFIG_SETUP_BOT_APP_ID",
572            config.setup.bot.app_id.clone().into(),
573        ),
574    ];
575    fields.extend(protection_fields(&config.protection, trunk.as_str()));
576    let template = crate::embedded::BLOCKS
577        .get_file("target-config.toml.in")
578        .and_then(include_dir::File::contents_utf8)
579        .ok_or_else(|| invalid("the binary lacks its configuration template"))?;
580    // Each authored line has one token. Substitute in the source line once,
581    // so a user's string containing another token stays literal.
582    let mut bytes = Vec::new();
583    for line in template.split_inclusive('\n') {
584        if let Some((token, value)) = fields.iter().find(|(token, _)| line.contains(token)) {
585            bytes.extend(crate::landing::substitute(
586                line.as_bytes(),
587                token.as_bytes(),
588                value.to_string().as_bytes(),
589            ));
590        } else {
591            bytes.extend_from_slice(line.as_bytes());
592        }
593    }
594    Ok(bytes)
595}
596
597fn protection_fields(
598    protection: &Protection,
599    trunk: &str,
600) -> Vec<(&'static str, toml_edit::Value)> {
601    vec![
602        (
603            "RK_CONFIG_PROTECTION_TRUNK_RULESET",
604            protection.trunk_ruleset(trunk).into(),
605        ),
606        (
607            "RK_CONFIG_PROTECTION_TAG_RULESET",
608            protection.tag_ruleset.clone().into(),
609        ),
610        (
611            "RK_CONFIG_PROTECTION_LINES_RULESET",
612            protection.lines_ruleset.clone().into(),
613        ),
614        (
615            "RK_CONFIG_PROTECTION_TITLE_CHECK",
616            protection.title_check.clone().into(),
617        ),
618        (
619            "RK_CONFIG_PROTECTION_TAG_PATTERN",
620            protection.tag_pattern.clone().into(),
621        ),
622        (
623            "RK_CONFIG_PROTECTION_BYPASS_ACTORS",
624            array(&protection.bypass_actors),
625        ),
626        (
627            "RK_CONFIG_PROTECTION_ALLOWED_MERGE_METHODS",
628            array(&protection.allowed_merge_methods),
629        ),
630        (
631            "RK_CONFIG_PROTECTION_STRICT_REQUIRED_STATUS_CHECKS",
632            protection.strict_required_status_checks.into(),
633        ),
634        (
635            "RK_CONFIG_PROTECTION_OWNED_TRUNK_RULES",
636            array(&protection.owned_trunk_rules),
637        ),
638        (
639            "RK_CONFIG_PROTECTION_REQUIRED_APPROVING_REVIEW_COUNT",
640            protection.required_approving_review_count.into(),
641        ),
642        (
643            "RK_CONFIG_PROTECTION_DISMISS_STALE_REVIEWS_ON_PUSH",
644            protection.dismiss_stale_reviews_on_push.into(),
645        ),
646        (
647            "RK_CONFIG_PROTECTION_REQUIRE_CODE_OWNER_REVIEW",
648            protection.require_code_owner_review.into(),
649        ),
650        (
651            "RK_CONFIG_PROTECTION_REQUIRE_LAST_PUSH_APPROVAL",
652            protection.require_last_push_approval.into(),
653        ),
654        (
655            "RK_CONFIG_PROTECTION_GITHUB_SQUASH_TITLE_SOURCE",
656            protection.github.squash_title_source.clone().into(),
657        ),
658        (
659            "RK_CONFIG_PROTECTION_GITHUB_SQUASH_BODY_SOURCE",
660            protection.github.squash_body_source.clone().into(),
661        ),
662        (
663            "RK_CONFIG_PROTECTION_GITLAB_MERGE_METHOD",
664            protection.gitlab.merge_method.clone().into(),
665        ),
666        (
667            "RK_CONFIG_PROTECTION_GITLAB_SQUASH_OPTION",
668            protection.gitlab.squash_option.clone().into(),
669        ),
670        (
671            "RK_CONFIG_PROTECTION_GITLAB_SQUASH_COMMIT_TEMPLATE",
672            protection.gitlab.squash_commit_template.clone().into(),
673        ),
674        (
675            "RK_CONFIG_PROTECTION_GITLAB_PUSH_ACCESS_LEVEL",
676            protection.gitlab.push_access_level.into(),
677        ),
678        (
679            "RK_CONFIG_PROTECTION_GITLAB_MERGE_ACCESS_LEVEL",
680            protection.gitlab.merge_access_level.into(),
681        ),
682    ]
683}
684
685/// Change one landing parameter while preserving comments and table ordering.
686///
687/// # Errors
688/// Refuses an invalid key, invalid resulting content, or unreadable file; writes atomically.
689pub fn rewrite_key(target: &Path, key: &str, value: toml_edit::Value) -> Result<(), RkError> {
690    let path = target.join(CONFIG_PATH);
691    let text = std::fs::read_to_string(&path)?;
692    let next = rewrite_text(&text, key, value)?;
693    crate::atomic::write(&path, next.as_bytes())?;
694    Ok(())
695}
696
697fn rewrite_text(text: &str, key: &str, mut value: toml_edit::Value) -> Result<String, RkError> {
698    if ![
699        "project.repo",
700        "project.forge",
701        "project.tech",
702        "project.trunk",
703        "landing.workflow",
704        "landing.style",
705        "landing.nix",
706        "security.contact",
707        "security.response",
708        "setup.line_prefix",
709    ]
710    .contains(&key)
711    {
712        return Err(invalid(format!("{key} is not a landing parameter")));
713    }
714    parse(text)?;
715    let mut document = text
716        .parse::<toml_edit::DocumentMut>()
717        .map_err(|error| invalid(error.to_string()))?;
718    let mut item = document.as_item_mut();
719    for segment in key.split('.') {
720        item = &mut item[segment];
721    }
722    if let Some(old) = item.as_value() {
723        if old
724            .as_str()
725            .zip(value.as_str())
726            .is_some_and(|(old, new)| old == new)
727            || old
728                .as_bool()
729                .zip(value.as_bool())
730                .is_some_and(|(old, new)| old == new)
731        {
732            return Ok(text.to_owned());
733        }
734        *value.decor_mut() = old.decor().clone();
735    }
736    *item = toml_edit::Item::Value(value);
737    let next = document.to_string();
738    parse(&next)?;
739    Ok(next)
740}
741
742/// Resolved landing input, including every key a preview would write.
743#[derive(Debug, Clone, serde::Serialize)]
744pub struct Plan {
745    /// Added or updated configuration.
746    pub action: &'static str,
747    /// Keys whose configured answers differ from the record.
748    pub changes: Vec<String>,
749    /// The exact authored TOML the apply writes.
750    pub content: String,
751}
752
753impl Plan {
754    /// Resolve the output without writing it; existing comments survive.
755    ///
756    /// # Errors
757    /// Propagates unreadable or invalid configuration.
758    pub fn new(
759        target: &Path,
760        params: &crate::landing::Params,
761        existing: Option<&Config>,
762        record: Option<&crate::landing::manifest::Manifest>,
763    ) -> Result<Self, RkError> {
764        let text = existing
765            .map(|_| std::fs::read_to_string(target.join(CONFIG_PATH)))
766            .transpose()?;
767        Self::compose(text.as_deref(), params, existing, record)
768    }
769
770    /// Resolve the output from the existing text already read, so a
771    /// planner that owns no filesystem can compose it from its
772    /// observation; existing comments survive.
773    ///
774    /// # Errors
775    /// Propagates invalid configuration.
776    pub fn compose(
777        text: Option<&str>,
778        params: &crate::landing::Params,
779        existing: Option<&Config>,
780        record: Option<&crate::landing::manifest::Manifest>,
781    ) -> Result<Self, RkError> {
782        let mut resolved = existing.cloned().unwrap_or_default();
783        resolved.project.tech = params.tech().into();
784        resolved.project.forge = params.forge().into();
785        resolved.project.repo = params.repo().into();
786        resolved.landing = Landing {
787            workflow: Some(params.workflow()),
788            style: params.style(),
789            nix: Some(params.nix()),
790        };
791        resolved.project.trunk = Some(params.trunk().to_owned());
792        resolved.setup.line_prefix = Some(params.line_prefix().to_owned());
793        resolved.security.contact = Some(params.security_contact().to_owned());
794        resolved.security.response = Some(params.security_response().to_owned());
795        let content = if let Some(text) = text.filter(|_| existing.is_some()) {
796            let mut text = text.to_owned();
797            for (key, value) in parameter_values(&resolved) {
798                text = rewrite_text(&text, key, value)?;
799            }
800            text
801        } else {
802            String::from_utf8(render(&resolved)?).map_err(|e| invalid(e.to_string()))?
803        };
804        parse(&content)?;
805        Ok(Self {
806            action: if existing.is_some() {
807                "updated"
808            } else {
809                "added"
810            },
811            changes: record.map_or_else(Vec::new, |record| pending(&resolved, record)),
812            content,
813        })
814    }
815
816    /// Write the prepared configuration before the landing record.
817    ///
818    /// # Errors
819    /// Propagates an atomic write failure.
820    pub fn apply(&self, target: &Path) -> Result<(), RkError> {
821        crate::atomic::write(&target.join(CONFIG_PATH), self.content.as_bytes())?;
822        Ok(())
823    }
824}
825
826fn parameter_values(config: &Config) -> Vec<(&'static str, toml_edit::Value)> {
827    let mut values = Vec::new();
828    for (key, value) in [
829        ("project.repo", &config.project.repo),
830        ("project.forge", &config.project.forge),
831        ("project.tech", &config.project.tech),
832    ] {
833        if !value.is_empty() {
834            values.push((key, value.clone().into()));
835        }
836    }
837    if let Some(value) = config.landing.workflow {
838        values.push(("landing.workflow", value.as_str().into()));
839    }
840    if let Some(value) = config.landing.style {
841        values.push(("landing.style", value.as_str().into()));
842    }
843    if let Some(value) = config.landing.nix {
844        values.push(("landing.nix", value.into()));
845    }
846    if let Some(value) = config.project.trunk.clone() {
847        values.push(("project.trunk", value.into()));
848    }
849    if let Some(value) = config.setup.line_prefix.clone() {
850        values.push(("setup.line_prefix", value.into()));
851    }
852    // An empty contact is an answer, not an absence: it resets the landed
853    // policy to the forge's own prose, so it projects like any other value.
854    if let Some(value) = config.security.contact.clone() {
855        values.push(("security.contact", value.into()));
856    }
857    if let Some(value) = config.security.response.clone() {
858        values.push(("security.response", value.into()));
859    }
860    values
861}
862
863/// Only explicit class P answers can be pending; comparisons still use the record.
864#[must_use]
865pub fn pending(config: &Config, record: &crate::landing::manifest::Manifest) -> Vec<String> {
866    let mut recorded = Config::default();
867    recorded.project.repo.clone_from(&record.parameters.repo);
868    recorded.project.forge.clone_from(&record.forge);
869    recorded.project.tech.clone_from(&record.tech);
870    recorded.landing = Landing {
871        workflow: Some(record.parameters.workflow),
872        style: record.parameters.style,
873        nix: Some(record.parameters.nix),
874    };
875    recorded.project.trunk = Some(record.parameters.trunk.clone());
876    recorded.setup.line_prefix = Some(record.parameters.line_prefix.clone());
877    recorded.security.contact = Some(record.parameters.security_contact.clone());
878    recorded.security.response = Some(record.parameters.security_response.clone());
879    let baseline = parameter_values(&recorded);
880    parameter_values(config)
881        .into_iter()
882        .filter(|(key, value)| {
883            !baseline
884                .iter()
885                .any(|(other, old)| key == other && value.to_string() == old.to_string())
886        })
887        .map(|(key, _)| key.to_owned())
888        .collect()
889}
890
891/// The trunk accessor for callers without a setup context.
892///
893/// # Errors
894/// Propagates invalid configuration and I/O failures.
895pub fn trunk_of(target: &Path) -> Result<String, RkError> {
896    Ok(load(target)?
897        .and_then(|config| config.project.trunk)
898        .unwrap_or_else(|| TRUNK_DEFAULT.to_owned()))
899}
900
901/// The release-line prefix for callers without a setup context.
902///
903/// # Errors
904/// Propagates invalid configuration and I/O failures.
905pub fn line_prefix_of(target: &Path) -> Result<String, RkError> {
906    Ok(load(target)?
907        .and_then(|config| config.setup.line_prefix)
908        .unwrap_or_else(|| LINE_PREFIX_DEFAULT.to_owned()))
909}
910
911#[cfg(test)]
912mod tests {
913    use super::{CONFIG_PATH, Config, load, parse, rewrite_key, trunk_of, write};
914    use crate::landing::{Style, Workflow};
915
916    #[test]
917    fn an_omitted_landing_key_is_distinguishable_from_an_explicit_default() {
918        let omitted = parse("schema_version = 1\n").expect("omitted answers parse");
919        let explicit = parse(
920            "schema_version = 1\n[landing]\nworkflow = 'worktree'\nstyle = 'trunk'\nnix = false\n",
921        )
922        .expect("explicit defaults parse");
923        assert_eq!(omitted.landing, super::Landing::default());
924        assert_eq!(explicit.landing.workflow, Some(Workflow::Worktree));
925        assert_eq!(explicit.landing.style, Some(Style::Trunk));
926        assert_eq!(explicit.landing.nix, Some(false));
927        assert_ne!(omitted, explicit);
928    }
929
930    /// A configuration written by 0.3.13 carries `installation_id`, which
931    /// this version reads and ignores. Refusing it would strand every
932    /// target that release landed.
933    #[test]
934    fn a_config_from_the_release_that_wrote_installation_id_still_reads() {
935        let dir = tempfile::tempdir().expect("a tempdir");
936        std::fs::create_dir_all(dir.path().join(".release-kit")).expect("the directory exists");
937        std::fs::write(
938            dir.path().join(CONFIG_PATH),
939            "schema_version = 1\n\n[setup.bot]\napp_id = \"123\"\ninstallation_id = 0\n",
940        )
941        .expect("the config writes");
942        let held = load(dir.path())
943            .expect("the config reads")
944            .expect("it is present");
945        assert_eq!(held.setup.bot.app_id, "123");
946        assert_eq!(
947            held.setup.bot.installation_id,
948            Some(0),
949            "the key parses; nothing reads it"
950        );
951    }
952
953    #[test]
954    fn the_landed_config_template_round_trips() {
955        let dir = tempfile::tempdir().expect("a target exists");
956        let mut config = Config::default();
957        config.project.repo = "acme/nested/widget".into();
958        config.project.forge = "gitlab".into();
959        config.project.tech = "bash".into();
960        config.project.trunk = Some("main".into());
961        config.landing.workflow = Some(Workflow::Branches);
962        config.landing.style = Some(Style::Lines);
963        config.landing.nix = Some(true);
964        // The escaping subject moved to the one unrestricted string in this
965        // table: `contact` is now a class P value the reader holds to a
966        // single control-free line, so it can carry neither.
967        config.security.advisories =
968            "A \"quoted\" project\nRK_CONFIG_SECURITY_RESPONSE\\end".into();
969        config.security.contact = Some("security team, room 3 \"the vault\"".into());
970        config.security.response = Some("14 business days".into());
971        config.setup.required_check = "build / test".into();
972        config.setup.retired_branches = vec!["develop".into(), "old\"branch".into()];
973        config.setup.line_prefix = Some("stable/".into());
974        config.setup.release_lines = true;
975        config.setup.excluded_steps = [
976            (
977                "package-check".to_owned(),
978                "nothing is published".to_owned(),
979            ),
980            (
981                "protect-trunk".to_owned(),
982                "this project merges \"locally\"".to_owned(),
983            ),
984        ]
985        .into_iter()
986        .collect();
987        config.setup.bot.app_id = "123".into();
988        config.protection.trunk_ruleset = Some("primary".into());
989        config.protection.tag_ruleset = "versions".into();
990        config.protection.lines_ruleset = "maintenance".into();
991        config.protection.title_check = "intent".into();
992        config.protection.tag_pattern = "refs/tags/*".into();
993        config
994            .protection
995            .owned_trunk_rules
996            .push("required_signatures".into());
997        config.protection.required_approving_review_count = 2;
998        config.protection.dismiss_stale_reviews_on_push = true;
999        config.protection.require_code_owner_review = true;
1000        config.protection.require_last_push_approval = true;
1001        config.protection.gitlab.squash_commit_template =
1002            "%{title}\n\nContext: %{description}".into();
1003        config.protection.gitlab.merge_access_level = 40;
1004        let defaults = Config {
1005            landing: super::Landing {
1006                workflow: Some(Workflow::Worktree),
1007                style: Some(Style::Trunk),
1008                nix: Some(false),
1009            },
1010            project: super::Project {
1011                trunk: Some(super::TRUNK_DEFAULT.into()),
1012                ..super::Project::default()
1013            },
1014            setup: super::Setup {
1015                line_prefix: Some(super::LINE_PREFIX_DEFAULT.into()),
1016                ..super::Setup::default()
1017            },
1018            // Writing states both security answers, so a reader sees the
1019            // policy the target landed rather than an implied one.
1020            security: super::Security {
1021                contact: Some(String::new()),
1022                response: Some(super::RESPONSE_DEFAULT.into()),
1023                ..super::Security::default()
1024            },
1025            // Writing resolves the derived ruleset name, so the file states
1026            // the name the setup installs rather than leaving it implied.
1027            protection: super::Protection {
1028                trunk_ruleset: Some(format!("{}-protection", super::TRUNK_DEFAULT)),
1029                ..super::Protection::default()
1030            },
1031            ..Config::default()
1032        };
1033        for expected in [defaults, config] {
1034            write(dir.path(), &expected).expect("the template renders");
1035            assert_eq!(load(dir.path()).expect("the config reads"), Some(expected));
1036            let text =
1037                std::fs::read_to_string(dir.path().join(CONFIG_PATH)).expect("the text reads");
1038            assert!(text.contains("# P: project path"));
1039            assert!(text.contains("# F: invariant"));
1040        }
1041    }
1042
1043    #[test]
1044    fn a_config_with_an_unknown_key_refuses_by_name() {
1045        for (table, typo, nearest) in [
1046            ("", "schemax_version", "schema_version"),
1047            ("project", "trunkx", "trunk"),
1048            ("landing", "stile", "style"),
1049            ("security", "contactx", "contact"),
1050            ("setup", "required_checkx", "required_check"),
1051            ("setup.bot", "app_i", "app_id"),
1052            ("protection", "trunk_rulesett", "trunk_ruleset"),
1053            (
1054                "protection.github",
1055                "squash_body_sourcex",
1056                "squash_body_source",
1057            ),
1058            ("protection.gitlab", "squash_optionx", "squash_option"),
1059        ] {
1060            let header = if table.is_empty() {
1061                String::new()
1062            } else {
1063                format!("[{table}]\n")
1064            };
1065            let text = format!("schema_version = 1\n{header}{typo} = 'value'\n");
1066            let error = parse(&text).expect_err("unknown keys refuse").to_string();
1067            for expected in [CONFIG_PATH, typo, &format!("nearest known key: {nearest}")] {
1068                assert!(error.contains(expected), "{error}");
1069            }
1070        }
1071    }
1072
1073    /// An exclusion removes a step from scope, so a typo in one would
1074    /// silently keep judging a step the target does not run, and a
1075    /// reasonless one would leave a report nobody can audit.
1076    #[test]
1077    fn an_exclusion_names_a_real_step_and_states_why() {
1078        for (text, expected) in [
1079            (
1080                "[setup.excluded_steps]\nprotect-trunkk = 'we merge locally'\n",
1081                vec!["protect-trunkk", "nearest known step: protect-trunk"],
1082            ),
1083            (
1084                "[setup.excluded_steps]\nprotect-trunk = '  '\n",
1085                vec!["protect-trunk", "no reason"],
1086            ),
1087        ] {
1088            let error = parse(&format!("schema_version = 1\n{text}"))
1089                .expect_err("the exclusion refuses")
1090                .to_string();
1091            for want in expected {
1092                assert!(error.contains(want), "{error}");
1093            }
1094        }
1095        let held = parse(
1096            "schema_version = 1\n[setup.excluded_steps]\nprotect-trunk = 'we merge locally'\n",
1097        )
1098        .expect("a named step with a reason parses");
1099        assert_eq!(
1100            held.setup
1101                .excluded_steps
1102                .get("protect-trunk")
1103                .map(String::as_str),
1104            Some("we merge locally")
1105        );
1106    }
1107
1108    /// An exclusion narrows what the setup judges. It never weakens the
1109    /// method's policy, so the floors bind a target that runs a subset
1110    /// exactly as they bind one that runs every step.
1111    #[test]
1112    fn an_exclusion_does_not_lift_a_floor() {
1113        let error = parse(
1114            "schema_version = 1\n[setup.excluded_steps]\nprotect-trunk = 'we merge locally'\n\n[protection]\nallowed_merge_methods = ['squash', 'merge']\n",
1115        )
1116        .expect_err("the floor binds an excluded step's keys too")
1117        .to_string();
1118        assert!(
1119            error.contains("protection.allowed_merge_methods"),
1120            "{error}"
1121        );
1122    }
1123
1124    #[test]
1125    fn a_config_at_an_unknown_schema_refuses() {
1126        for text in ["schema_version = 999", "schema_version = '1'", ""] {
1127            let error = parse(text)
1128                .expect_err("a schema must be declared and known")
1129                .to_string();
1130            assert!(
1131                error.contains(CONFIG_PATH) && error.contains("schema_version"),
1132                "{error}"
1133            );
1134        }
1135    }
1136
1137    #[test]
1138    fn an_unparsable_config_refuses_naming_the_position() {
1139        let error = parse("schema_version = 1\n[project\n")
1140            .expect_err("bad TOML refuses")
1141            .to_string();
1142        for expected in [CONFIG_PATH, "line 2", "column"] {
1143            assert!(error.contains(expected), "{error}");
1144        }
1145    }
1146
1147    #[test]
1148    fn an_absent_config_reads_as_none() {
1149        let dir = tempfile::tempdir().expect("a target exists");
1150        assert_eq!(load(dir.path()).expect("absence is compatible"), None);
1151        assert_eq!(trunk_of(dir.path()).expect("the default reads"), "master");
1152    }
1153
1154    #[test]
1155    fn loading_checks_floors_and_trunk_of_propagates_invalid_content() {
1156        let dir = tempfile::tempdir().expect("a target exists");
1157        std::fs::create_dir(dir.path().join(".release-kit")).expect("the directory exists");
1158        std::fs::write(
1159            dir.path().join(CONFIG_PATH),
1160            "schema_version = 1\n[protection]\nstrict_required_status_checks = false\n",
1161        )
1162        .expect("a config exists");
1163        let error =
1164            trunk_of(dir.path()).expect_err("invalid policy refuses even through the accessor");
1165        assert_eq!(error.exit_code(), 73);
1166        assert!(
1167            error
1168                .to_string()
1169                .contains("protection.strict_required_status_checks")
1170        );
1171    }
1172
1173    #[test]
1174    fn rewrite_key_preserves_comments() {
1175        let dir = tempfile::tempdir().expect("a target exists");
1176        std::fs::create_dir(dir.path().join(".release-kit")).expect("the directory exists");
1177        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";
1178        let path = dir.path().join(CONFIG_PATH);
1179        std::fs::write(&path, original).expect("a config exists");
1180        rewrite_key(dir.path(), "landing.style", "lines".into()).expect("the style writes back");
1181        let text = std::fs::read_to_string(&path).expect("the text reads");
1182        assert_eq!(text, original.replace("'trunk'", "\"lines\""));
1183        assert_eq!(
1184            load(dir.path())
1185                .expect("the config reads")
1186                .expect("present")
1187                .landing
1188                .style,
1189            Some(Style::Lines)
1190        );
1191        rewrite_key(dir.path(), "project.repo", "acme/widget".into())
1192            .expect("an omitted table can be added");
1193        assert_eq!(
1194            load(dir.path())
1195                .expect("reads")
1196                .expect("present")
1197                .project
1198                .repo,
1199            "acme/widget"
1200        );
1201        rewrite_key(
1202            dir.path(),
1203            "security.contact",
1204            "security@acme.example".into(),
1205        )
1206        .expect("the contact is a landing parameter now");
1207        rewrite_key(dir.path(), "security.response", "14 days".into())
1208            .expect("the response is a landing parameter now");
1209        let held = load(dir.path()).expect("reads").expect("present");
1210        assert_eq!(
1211            held.security.contact.as_deref(),
1212            Some("security@acme.example")
1213        );
1214        assert_eq!(held.security.response.as_deref(), Some("14 days"));
1215        let text = std::fs::read_to_string(&path).expect("the text reads");
1216        assert!(text.contains("# keep me"), "the comment survives: {text}");
1217        let before = std::fs::read(&path).expect("the bytes read");
1218        for (key, value) in [
1219            ("security.advisories", "acme/private"),
1220            ("security.response", "90d"),
1221            ("landing.style", "unknown"),
1222        ] {
1223            assert!(rewrite_key(dir.path(), key, value.into()).is_err());
1224            assert_eq!(std::fs::read(&path).expect("the bytes read"), before);
1225        }
1226    }
1227
1228    /// The two security answers are one line and one narrow grammar,
1229    /// because both land verbatim in a public policy.
1230    #[test]
1231    fn the_security_answers_are_held_to_their_grammar() {
1232        for value in ["team@acme.example", "  https://acme.example/report  ", ""] {
1233            super::canonical_contact(value).expect("a control-free line is a contact");
1234        }
1235        for value in ["one\ntwo", "one\rtwo", "one\u{7}two"] {
1236            let refusal = super::canonical_contact(value).expect_err("a control character refuses");
1237            assert!(refusal.contains("security.contact"), "{refusal}");
1238        }
1239        assert_eq!(
1240            super::canonical_contact("  team@acme.example  "),
1241            Ok("team@acme.example".to_owned()),
1242            "surrounding whitespace is trimmed"
1243        );
1244        for value in [
1245            "best-effort",
1246            "1 day",
1247            "2 days",
1248            "14 days",
1249            "1 business day",
1250            "14 business days",
1251        ] {
1252            assert_eq!(super::canonical_response(value), Ok(value.to_owned()));
1253        }
1254        assert_eq!(
1255            super::canonical_response(""),
1256            Ok(super::RESPONSE_DEFAULT.to_owned()),
1257            "an empty answer reads as the compiled default"
1258        );
1259        for value in [
1260            "0 days",
1261            "1 days",
1262            "2 day",
1263            "+2 days",
1264            "02 days",
1265            "4294967296 days",
1266            "90d",
1267            "two days",
1268            "we answer quickly",
1269            "2 weeks",
1270        ] {
1271            let refusal =
1272                super::canonical_response(value).expect_err("an unstateable window refuses");
1273            assert!(refusal.contains("security.response"), "{value}: {refusal}");
1274            assert!(refusal.contains("business days"), "{value}: {refusal}");
1275        }
1276        let refusal = parse("schema_version = 1\n[security]\nresponse = '90d'\n")
1277            .expect_err("the reader refuses it too")
1278            .to_string();
1279        assert!(refusal.contains("security.response"), "{refusal}");
1280    }
1281}