release_kit/setup/context.rs
1//! The resolved context one setup run works in: target, repository, forge,
2//! the forge CLI binary, and the environment a step receives.
3//!
4//! The environment is constructed, not inherited: `env_clear` plus exactly
5//! the declared variables, the forge CLI's own configuration and
6//! authentication variables, and — only for the steps that need them — the
7//! bot credentials. The parent's environment does not leak into a
8//! privileged child, no secret is ever an argv value, and key material
9//! reaches no environment at all: `rk` reads the key the operator named and
10//! writes it to the step's standard input. [`super::secrets`] owns that
11//! boundary.
12
13use std::ffi::OsString;
14use std::path::{Path, PathBuf};
15
16use camino::Utf8PathBuf;
17use zeroize::Zeroizing;
18
19use super::secrets;
20use crate::detect::{self, Forge};
21use crate::diagnostic::{Diagnostic, Reason};
22use crate::error::RkError;
23use crate::profile::{CapabilityRequests, ProfileSnapshot, ReleaseMode};
24
25// The trunk every setup asserts is the one permanent branch the target
26// states in its own committed configuration, read through `Ctx::trunk`.
27// A target that names none keeps the compiled default, so a landing
28// predating the key behaves exactly as it did.
29
30/// A policy boolean as the JSON word a forge body carries.
31/// The compact JSON text of one answer, so the proof fields read alike
32/// whatever type holds them. A value that cannot serialize reads as
33/// empty, which no real answer is.
34fn canonical<T: serde::Serialize>(value: &T) -> String {
35 serde_json::to_string(value).unwrap_or_default()
36}
37
38const fn bool_word(value: bool) -> &'static str {
39 if value { "true" } else { "false" }
40}
41
42/// A policy list as the JSON array a forge body carries. Every element
43/// passed the floor table, so this quotes rather than escapes.
44fn json_list(values: &[String]) -> String {
45 let inner: Vec<String> = values.iter().map(|value| format!("\"{value}\"")).collect();
46 format!("[{}]", inner.join(", "))
47}
48
49/// The GitHub API objects named by the policy's stable bypass vocabulary.
50///
51/// GitHub's built-in repository-administrator role is actor 5. Keeping that
52/// API encoding here lets configuration, diagnostics, and prose name intent
53/// while the setup owns the forge representation in one place.
54pub(super) fn github_bypass_actors(values: &[String]) -> serde_json::Value {
55 serde_json::Value::Array(
56 values
57 .iter()
58 .filter_map(|value| match value.as_str() {
59 crate::config::LOCAL_GITHUB_BYPASS => Some(serde_json::json!({
60 "actor_id": 5,
61 "actor_type": "RepositoryRole",
62 "bypass_mode": "always",
63 })),
64 _ => None,
65 })
66 .collect(),
67 )
68}
69
70/// One GitHub ruleset's `rules` array, as JSON.
71///
72/// Every rule comes from `protection.owned_trunk_rules`, which the floor
73/// table judges per integration mode and the observer checks against, so
74/// one key decides what a run installs and what the check expects. A rule
75/// this convention parameterizes carries its parameters; the rest are
76/// bare type entries.
77///
78/// `wanted` selects which of the owned rules this ruleset carries. The
79/// trunk's rules live in two rulesets because a bypass actor is recorded
80/// on a ruleset: the rules a bypass may excuse are kept apart from the
81/// rules that must hold against everyone.
82fn compose_rules(
83 protection: &crate::config::Protection,
84 wanted: &[&str],
85 required_check: &str,
86 title_check: &str,
87) -> String {
88 let rules: Vec<serde_json::Value> = protection
89 .owned_trunk_rules
90 .iter()
91 .filter(|rule| wanted.iter().any(|kind| kind == &rule.as_str()))
92 .map(|rule| match rule.as_str() {
93 "pull_request" => serde_json::json!({
94 "type": "pull_request",
95 "parameters": {
96 "required_approving_review_count": protection.required_approving_review_count,
97 "dismiss_stale_reviews_on_push": protection.dismiss_stale_reviews_on_push,
98 "require_code_owner_review": protection.require_code_owner_review,
99 "require_last_push_approval": protection.require_last_push_approval,
100 "required_review_thread_resolution": false,
101 "require_extra_approval_for_unattributed_changes": false,
102 "allowed_merge_methods": protection.allowed_merge_methods,
103 }
104 }),
105 "required_status_checks" => serde_json::json!({
106 "type": "required_status_checks",
107 "parameters": {
108 "do_not_enforce_on_create": true,
109 "strict_required_status_checks_policy":
110 protection.strict_required_status_checks,
111 "required_status_checks": [
112 { "context": required_check },
113 { "context": title_check },
114 ],
115 }
116 }),
117 other => serde_json::json!({ "type": other }),
118 })
119 .collect();
120 // Pretty rather than compact: the body a run sends is what an
121 // operator reads back off the forge when a protection is in doubt.
122 serde_json::to_string_pretty(&rules).unwrap_or_else(|_| "[]".to_owned())
123}
124
125/// One target's effective protection policy: what it stated, resolved
126/// against the authority that carries an implementation onto its trunk.
127///
128/// A target that stated a policy gets its own values: the floor table
129/// already judged them under the same mode, and an operator who narrowed
130/// or widened something meant it. The one exception is the former compiled
131/// local tuple: it remains readable so an upgrade can migrate it, but setup
132/// must never reinstall its missing freshness rules. A target that stated nothing gets the
133/// compiled defaults, which describe forge integration because that is
134/// the shape this convention had before the axis existed — so under
135/// local integration they are adjusted rather than installed.
136///
137/// Two adjustments, and both only where the target stated nothing. GitHub
138/// names the repository-administrator role as the bypass authority while
139/// retaining every rule, so a local integrator may push but the release App
140/// may merge only the tested request. The GitLab push level moves off zero
141/// to the narrowest level that still admits a push.
142///
143/// The merge values follow the recorded merge form whatever the target
144/// stated, because the floors hold them to exactly that form's values:
145/// GitHub allows the one method the form names, and GitLab squashes every
146/// merge request under `squash` and none under `rebase`. Under `rebase`
147/// the safety ruleset also carries the linear-history rule, so a merge
148/// commit reaches the trunk from no actor.
149///
150/// The profile decides two requirements beside the policy. The tag
151/// protection follows the release mode alone: a target that releases
152/// nothing mints no tag to protect. The required status check and the
153/// GitLab pipeline requirement follow the forge gate alone, as
154/// [`crate::profile::catalog::forge_gate_lands`] answers it: where no gate
155/// lands, no workflow reports a check and no pipeline runs, so the trunk
156/// ruleset drops its required-check rule and the GitLab trunk drops the
157/// pipeline requirement, while deletion and force-push hold in every case.
158/// The floors still require the check rule in the stated key; the
159/// relaxation lives here, in the one result every reader takes.
160///
161/// One resolution serves the body a step sends, the observer that reads
162/// the answer back, and the prerequisites, so a canonical apply cannot
163/// install one shape and then fault its own result for not being another.
164///
165/// SATISFIES target-config:the-effective-protection-follows-the-profile
166fn effective_protection(
167 stated: Option<&crate::config::Protection>,
168 integration: crate::landing::Integration,
169 form: crate::landing::MergeForm,
170 mode: ReleaseMode,
171) -> Effective {
172 let authority = stated.map_or_else(
173 || {
174 if integration == crate::landing::Integration::Local {
175 crate::config::local_protection()
176 } else {
177 crate::config::Protection::default()
178 }
179 },
180 |stated| {
181 if integration == crate::landing::Integration::Local
182 && crate::config::legacy_local_protection(stated)
183 {
184 let mut migrated = stated.clone();
185 let current = crate::config::local_protection();
186 migrated.bypass_actors = current.bypass_actors;
187 migrated.owned_trunk_rules = current.owned_trunk_rules;
188 migrated.gitlab.push_access_level = current.gitlab.push_access_level;
189 migrated
190 } else {
191 stated.clone()
192 }
193 },
194 );
195 let mut policy = crate::config::with_merge_form(&authority, form);
196 if form == crate::landing::MergeForm::Rebase
197 && !policy
198 .owned_trunk_rules
199 .iter()
200 .any(|rule| rule == crate::config::LINEAR_HISTORY_RULE)
201 {
202 policy
203 .owned_trunk_rules
204 .push(crate::config::LINEAR_HISTORY_RULE.to_owned());
205 }
206 let forge_gate = crate::profile::catalog::forge_gate_lands(integration, mode);
207 if !forge_gate {
208 policy
209 .owned_trunk_rules
210 .retain(|rule| rule != REQUIRED_CHECK_RULE);
211 }
212 Effective {
213 policy,
214 tag_protection: mode != ReleaseMode::None,
215 forge_gate,
216 }
217}
218
219/// The ruleset rule that requires a status check, which the trunk carries
220/// only where a forge gate reports one.
221const REQUIRED_CHECK_RULE: &str = "required_status_checks";
222
223/// The effective protection: the policy, and the two requirements the
224/// profile decides beside it.
225struct Effective {
226 /// The policy every setter, observer, and check reads.
227 policy: crate::config::Protection,
228 /// Whether the release tags are protected: wherever the release mode
229 /// is not `none`.
230 tag_protection: bool,
231 /// Whether a forge gate lands, so the trunk requires its check on
232 /// GitHub and the whole pipeline on GitLab.
233 forge_gate: bool,
234}
235
236/// The authority and the merge form a setup configures the forge for.
237///
238/// The record, not the resolution's compiled default: a setup configures a
239/// forge to match what landed, and a target with no record has landed
240/// nothing here. Forge integration and `squash` are what such a target
241/// carries, the same compatibility answers `rk integrate` reads, and a
242/// record predating the merge form reads as `squash` too.
243fn recorded_workflow(
244 record: Option<&crate::landing::manifest::Manifest>,
245) -> (crate::landing::Integration, crate::landing::MergeForm) {
246 record.map_or_else(
247 || {
248 (
249 crate::landing::manifest::integration_forge(),
250 crate::landing::manifest::merge_form_squash(),
251 )
252 },
253 |held| (held.git.integration, held.git.merge_form),
254 )
255}
256
257/// The context the landed forge gate reports under: the title check the
258/// target names under `squash`, and the commit gate's job under `rebase`.
259///
260/// The commit gate's job name is a constant of its rendered file, as the
261/// title job's is, and no key renames it: a renamed context would require
262/// a check nothing reports.
263fn gate_check(protection: &crate::config::Protection, form: crate::landing::MergeForm) -> String {
264 match form {
265 crate::landing::MergeForm::Squash => protection.title_check.clone(),
266 crate::landing::MergeForm::Rebase => crate::config::COMMIT_GATE_CHECK.to_owned(),
267 }
268}
269
270/// The variables that pass through from the operator's environment to a
271/// step: the interpreter's search path, the forge CLI's configuration and
272/// authentication, and nothing else.
273const PASSTHROUGH: [&str; 11] = [
274 "PATH",
275 "HOME",
276 "XDG_CONFIG_HOME",
277 "GH_TOKEN",
278 "GITHUB_TOKEN",
279 "GH_HOST",
280 "GH_CONFIG_DIR",
281 "GLAB_TOKEN",
282 "GITLAB_TOKEN",
283 "GITLAB_HOST",
284 "GLAB_CONFIG_DIR",
285];
286
287/// The value-bearing bot variables, forwarded only to the steps that
288/// consume them and recorded in the journal as handling, never as value.
289/// The key is in no list here: it reaches its step as bytes on standard
290/// input, and neither it nor its path is ever put in an environment.
291/// [`secrets`] owns that.
292pub use super::secrets::VALUE_VARS as SECRET_VARS;
293
294/// One resolved run context.
295#[derive(Debug, Clone)]
296pub struct Ctx {
297 /// The repository being set up.
298 pub target: Utf8PathBuf,
299 /// The project path on the forge, empty where the profile names none.
300 pub repo: String,
301 /// The forge adapter the run acts through, where the profile names a
302 /// forge this release drives. A target with no forge, or one this
303 /// release has no adapter for, carries none: its local steps still
304 /// run and its forge steps report as not applicable.
305 pub forge: Option<Forge>,
306 /// The forge the profile declares, preserved whatever the adapter
307 /// says, so an unknown name stays readable.
308 pub declared_forge: Option<String>,
309 /// What the project is, as the target configuration resolves it.
310 pub profile: ProfileSnapshot,
311 /// Which optional products the target requests.
312 pub capabilities: CapabilityRequests,
313 /// The remote host, where one was detected.
314 pub host: Option<String>,
315 /// The value of `--required-check`, where given.
316 pub required_check: Option<String>,
317 /// The committed `setup.required_workflow`, on GitHub alone. No flag
318 /// answers it: the setup never writes it, it reads it to prove that
319 /// the workflow the release gate waits on is the workflow that carries
320 /// the check the gate judges.
321 pub required_workflow: Option<String>,
322 /// The resolved forge CLI binary.
323 pub cli: PathBuf,
324 /// The detected technology, where the version file names one.
325 pub tech: Option<&'static str>,
326 /// The one permanent branch this target states, or the compiled
327 /// default where it states none.
328 trunk: String,
329 /// The release-line prefix this target states, or the compiled
330 /// default where it states none.
331 line_prefix: String,
332 /// The long-lived branches a single trunk retires, as this target
333 /// names them.
334 retired_branches: Vec<String>,
335 /// Whether a full apply runs the release-line protection, which a
336 /// project that keeps no line does not want run at all.
337 release_lines: bool,
338 /// The steps this target declared it does not run, each against its
339 /// stated reason. A run reports them and judges none of them.
340 excluded_steps: std::collections::BTreeMap<String, String>,
341 /// The bot App's public identifier where this target states one; the
342 /// environment still wins over it, and no private credential is here.
343 bot_app_id: Option<String>,
344 /// The bot identity's name where this target states one. Unset takes
345 /// the forge's default, which on a GitLab service account carries the
346 /// project id only the forge answers.
347 bot_name: Option<String>,
348 /// The ruleset that protects the trunk, as this target names it.
349 trunk_ruleset: String,
350 /// The ruleset that keeps the trunk undeletable and unrewritable, as
351 /// this target names it. It names no bypass actor.
352 safety_ruleset: String,
353 /// The ruleset that makes published tags immutable.
354 tag_ruleset: String,
355 /// The ruleset that protects the release lines.
356 lines_ruleset: String,
357 /// The context the landed forge gate reports under: the title job under
358 /// `squash`, the commit gate's job under `rebase`.
359 title_check: String,
360 /// The effective policy this target runs under: what the target
361 /// stated, resolved against the recorded integration mode. Every
362 /// stated value passed the floor table at load, so a run passes this
363 /// to a step without judging it again, and one resolution serves the
364 /// body a step sends, the observer that reads the answer back, and
365 /// every prerequisite — so a run cannot install one shape and then
366 /// fault its own result for not being another.
367 protection: crate::config::Protection,
368 /// The destinations the landing record names, or `None` where nothing
369 /// landed here. The package check claims them as release-kit's own.
370 landed: Option<Vec<String>>,
371 /// Which authority carries an implementation onto this target's trunk.
372 /// A local-integration trunk takes the direct push that mode's
373 /// integrations end in, so the protection a run installs is not the
374 /// forge-integration one.
375 integration: crate::landing::Integration,
376 /// How the commits of a branch reach this target's trunk, as the record
377 /// says: it decides the merge settings and the forge gate a run
378 /// installs and expects.
379 merge_form: crate::landing::MergeForm,
380 /// Whether the release tags are protected, as the effective protection
381 /// decides it from the release mode.
382 pub(super) tag_protection: bool,
383 /// Whether a forge gate lands, as the effective protection decides it:
384 /// the trunk then requires the gate's check, and GitLab the pipeline.
385 pub(super) forge_gate: bool,
386}
387
388impl Ctx {
389 /// Resolve detection, overrides, and the forge CLI in one pass, before
390 /// any step runs.
391 ///
392 /// # Errors
393 ///
394 /// Refuses when the target is missing, when no remote resolves and no
395 /// override covers the gap, when the host is unrecognized, and when the
396 /// forge CLI is not on `PATH`.
397 pub fn resolve(
398 target: &Utf8PathBuf,
399 repo_flag: Option<&str>,
400 forge_flag: Option<&str>,
401 required_check: Option<&str>,
402 ) -> Result<Self, RkError> {
403 if !target.is_dir() {
404 return Err(RkError::missing(
405 Diagnostic::new(
406 Reason::TargetNotFound,
407 format!("target {target} is not a directory; nothing was run"),
408 )
409 .expected("an existing repository to set up"),
410 ));
411 }
412 let forge_flag = forge_flag
413 .map(|name| {
414 detect::Forge::parse(name).ok_or_else(|| {
415 RkError::Usage(format!(
416 "unknown forge '{name}'; the forges are: github, gitlab"
417 ))
418 })
419 })
420 .transpose()?;
421 let detected = detect::detect(target.as_std_path());
422 let config = crate::config::load(target.as_std_path())?;
423 let record = crate::landing::manifest::load(target)?;
424 // The setup reads the same target configuration a landing records,
425 // so which steps apply follows the profile rather than a second
426 // detection of its own.
427 let resolved = crate::profile::Params::resolve(
428 target,
429 &crate::profile::Inputs {
430 forge: forge_flag.map(Forge::as_str),
431 repo: repo_flag,
432 ..crate::profile::Inputs::default()
433 },
434 config.as_ref(),
435 record.as_ref(),
436 crate::profile::Purpose::Preview,
437 )?;
438 let declared_forge = resolved.forge().map(str::to_owned);
439 let forge = declared_forge.as_deref().and_then(Forge::parse);
440 let repo = resolved.repo().to_owned();
441 let repo = if repo == crate::projection::REPO_PLACEHOLDER {
442 String::new()
443 } else {
444 repo
445 };
446 // The forge CLI is not a prerequisite of building a context: it is
447 // a prerequisite of the steps a run actually calls the forge for,
448 // which `require_cli` resolves at that point.
449 let cli = PathBuf::new();
450 let answers = config
451 .as_ref()
452 .map_or_else(crate::config::Setup::default, |held| held.setup.clone());
453 // The flag wins, and the committed answer fills the gap on GitHub
454 // alone: GitLab names no individual check and refuses a supplied
455 // one, so a shared configuration must not make that refusal fire.
456 let required_check = required_check.map(str::to_owned).or_else(|| {
457 Some(answers.required_check.clone())
458 .filter(|name| !name.is_empty() && forge == Some(Forge::Github))
459 });
460 let required_workflow = Some(answers.required_workflow.clone())
461 .filter(|name| !name.is_empty() && forge == Some(Forge::Github));
462 let bot_app_id = Some(answers.bot.app_id.clone()).filter(|id| !id.is_empty());
463 let bot_name = Some(answers.bot.name.trim().to_owned()).filter(|name| !name.is_empty());
464 let trunk = resolved.trunk().to_owned();
465 let (integration, merge_form) = recorded_workflow(record.as_ref());
466 let landed = record.as_ref().map(|held| {
467 held.files
468 .iter()
469 .map(|file| file.destination.clone())
470 .collect()
471 });
472 let stated = config.as_ref().map(|held| &held.protection);
473 let effective =
474 effective_protection(stated, integration, merge_form, resolved.release_mode());
475 let protection = effective.policy;
476 Ok(Self {
477 target: target.clone(),
478 repo,
479 forge,
480 host: detected.host,
481 required_check,
482 required_workflow,
483 cli,
484 tech: resolved.driver().and_then(|driver| {
485 ["rust", "python", "bash"]
486 .into_iter()
487 .find(|known| *known == driver)
488 }),
489 trunk_ruleset: protection.trunk_ruleset(&trunk),
490 safety_ruleset: protection.safety_ruleset(&trunk),
491 tag_ruleset: protection.tag_ruleset.clone(),
492 lines_ruleset: protection.lines_ruleset.clone(),
493 title_check: gate_check(&protection, merge_form),
494 protection,
495 tag_protection: effective.tag_protection,
496 forge_gate: effective.forge_gate,
497 integration,
498 merge_form,
499 landed,
500 trunk,
501 line_prefix: resolved.line_prefix().to_owned(),
502 profile: resolved.profile().clone(),
503 capabilities: resolved.capabilities().clone(),
504 declared_forge,
505 retired_branches: answers.retired_branches,
506 release_lines: answers.release_lines,
507 excluded_steps: answers.excluded_steps,
508 bot_app_id,
509 bot_name,
510 })
511 }
512
513 /// The context of a target as its configuration and its record state
514 /// it, with no setup flag and no forge call, for a reader that judges
515 /// offline.
516 ///
517 /// # Errors
518 ///
519 /// The resolution's refusals, as [`Self::resolve`] raises them.
520 pub fn offline(target: &Utf8PathBuf) -> Result<Self, RkError> {
521 Self::resolve(target, None, None, None)
522 }
523
524 /// Resolve the forge CLI where this run will call the forge for one of
525 /// `steps`, and refuse where it cannot be found.
526 ///
527 /// The prerequisite belongs to the call, not to the command. A step is
528 /// only a caller when the target's configuration selects it, the
529 /// target has not excluded it, and the step reaches the forge at this
530 /// particular forge. A preview writes nothing, and asks anyway for the
531 /// steps it would act on, because it names the command it would run
532 /// and a CLI nothing could find is worth saying then.
533 ///
534 /// # Errors
535 /// Propagates the refusal when the forge CLI cannot be resolved.
536 ///
537 /// SATISFIES forge-setup:applicability-follows-the-target-configuration
538 pub fn require_cli(&mut self, steps: &[&crate::setup::steps::StepSpec]) -> Result<(), RkError> {
539 let Some(forge) = self.forge else {
540 return Ok(());
541 };
542 let calls = steps.iter().any(|step| {
543 step.forge_cli.contains(&forge) && crate::setup::report::stance(self, step).acts()
544 });
545 if calls && self.cli.as_os_str().is_empty() {
546 self.cli = resolve_cli(forge)?;
547 }
548 Ok(())
549 }
550
551 /// A context the integration tests build directly, for an observer
552 /// exercised against recorded forge answers rather than a repository.
553 /// The trunk and the prefix take their compiled defaults, because such
554 /// a test reads no target configuration.
555 #[doc(hidden)]
556 #[must_use]
557 pub fn for_tests(
558 target: Utf8PathBuf,
559 repo: String,
560 forge: Forge,
561 cli: PathBuf,
562 tech: Option<&'static str>,
563 ) -> Self {
564 let defaults = crate::config::Protection::default();
565 Self {
566 // The forge-integration shape, which is what every observer
567 // and request-body test here asserts; a local-mode case states it.
568 integration: crate::landing::Integration::Forge,
569 merge_form: crate::landing::MergeForm::Squash,
570 tag_protection: true,
571 forge_gate: true,
572 landed: None,
573 target,
574 repo,
575 forge: Some(forge),
576 declared_forge: Some(forge.as_str().to_owned()),
577 profile: ProfileSnapshot {
578 technologies: tech.into_iter().map(str::to_owned).collect(),
579 forge: Some(forge.as_str().to_owned()),
580 release: crate::profile::ReleaseIntent {
581 mode: ReleaseMode::Automatic,
582 driver: tech.map(str::to_owned),
583 style: Some(crate::landing::Style::Trunk),
584 line_prefix: Some(crate::config::LINE_PREFIX_DEFAULT.to_owned()),
585 registry: None,
586 build: None,
587 },
588 },
589 capabilities: CapabilityRequests {
590 nix_packaging: false,
591 reporting_policy: true,
592 scorecard: false,
593 code_scanning: None,
594 workflow_guards: Some(true),
595 },
596 host: None,
597 required_check: None,
598 required_workflow: None,
599 cli,
600 tech,
601 trunk: crate::config::TRUNK_DEFAULT.to_owned(),
602 line_prefix: crate::config::LINE_PREFIX_DEFAULT.to_owned(),
603 retired_branches: crate::config::Setup::default().retired_branches,
604 release_lines: false,
605 excluded_steps: std::collections::BTreeMap::new(),
606 bot_app_id: None,
607 bot_name: None,
608 trunk_ruleset: format!("{}-protection", crate::config::TRUNK_DEFAULT),
609 safety_ruleset: format!("{}-safety", crate::config::TRUNK_DEFAULT),
610 tag_ruleset: defaults.tag_ruleset.clone(),
611 lines_ruleset: defaults.lines_ruleset.clone(),
612 title_check: defaults.title_check.clone(),
613 protection: defaults,
614 }
615 }
616
617 /// The destinations the landing record names, or `None` where nothing
618 /// landed here.
619 #[must_use]
620 pub fn landed_destinations(&self) -> Option<&[String]> {
621 self.landed.as_deref()
622 }
623
624 /// Whether the run has a forge adapter to act through.
625 #[must_use]
626 pub const fn has_adapter(&self) -> bool {
627 self.forge.is_some()
628 }
629
630 /// The forge adapter, or the refusal a forge operation answers where
631 /// the profile names no forge this release drives.
632 ///
633 /// # Errors
634 ///
635 /// A `prerequisite-unmet` refusal naming the declared forge and the
636 /// ones this release drives.
637 pub fn adapter(&self) -> Result<Forge, RkError> {
638 self.forge.ok_or_else(|| {
639 let named = self.declared_forge.as_deref();
640 let message = named.map_or_else(
641 || "the profile names no forge, and this operation acts on one".to_owned(),
642 |name| {
643 format!(
644 "the profile names the forge {name}, which this release has no adapter for"
645 )
646 },
647 );
648 RkError::refusal(
649 Diagnostic::new(Reason::PrerequisiteUnmet, message)
650 .expected("a profile naming github or gitlab")
651 .action("set profile.forge in .release-kit/config.toml, or pass --forge <github|gitlab>")
652 .target_state("unchanged"),
653 )
654 })
655 }
656
657 /// Whether this target's release is one release-kit drives.
658 #[must_use]
659 pub const fn automatic_release(&self) -> bool {
660 matches!(self.profile.release.mode, ReleaseMode::Automatic)
661 }
662
663 /// The release driver, where the profile names one.
664 #[must_use]
665 pub fn driver(&self) -> Option<&str> {
666 self.profile.release.driver.as_deref()
667 }
668
669 /// The forge the profile declares, whatever the adapter says.
670 #[must_use]
671 pub fn declared_forge(&self) -> Option<&str> {
672 self.declared_forge.as_deref()
673 }
674
675 /// Whether the target requested the landed reporting policy.
676 #[must_use]
677 pub const fn reporting_policy(&self) -> bool {
678 self.capabilities.reporting_policy
679 }
680
681 /// The one permanent branch this run asserts.
682 #[must_use]
683 pub fn trunk(&self) -> &str {
684 &self.trunk
685 }
686
687 /// The release-line prefix this run asserts.
688 #[must_use]
689 pub fn line_prefix(&self) -> &str {
690 &self.line_prefix
691 }
692
693 /// The long-lived branches this run's single-trunk step retires.
694 #[must_use]
695 pub fn retired_branches(&self) -> &[String] {
696 &self.retired_branches
697 }
698
699 /// Whether a full apply runs the release-line protection.
700 #[must_use]
701 pub const fn release_lines(&self) -> bool {
702 self.release_lines
703 }
704
705 /// Why this target does not run the named step, where it declared an
706 /// exclusion for it. The reason is what the report prints, so an
707 /// excluded step is always visible with the answer behind it.
708 #[must_use]
709 pub fn excluded(&self, step: &str) -> Option<&str> {
710 self.excluded_steps.get(step).map(String::as_str)
711 }
712
713 /// How many steps this target declared it does not run.
714 #[must_use]
715 pub fn excluded_count(&self) -> usize {
716 self.excluded_steps.len()
717 }
718
719 /// The bot App's public identifier this target states, where it does.
720 #[must_use]
721 pub fn bot_app_id(&self) -> Option<&str> {
722 self.bot_app_id.as_deref()
723 }
724
725 /// The bot identity's name this target states, where it does.
726 #[must_use]
727 pub fn bot_name(&self) -> Option<&str> {
728 self.bot_name.as_deref()
729 }
730
731 /// The ruleset that protects the trunk.
732 #[must_use]
733 pub fn trunk_ruleset(&self) -> &str {
734 &self.trunk_ruleset
735 }
736
737 /// The ruleset that keeps the trunk undeletable and unrewritable.
738 #[must_use]
739 pub fn safety_ruleset(&self) -> &str {
740 &self.safety_ruleset
741 }
742
743 /// The ruleset that makes published tags immutable.
744 #[must_use]
745 pub fn tag_ruleset(&self) -> &str {
746 &self.tag_ruleset
747 }
748
749 /// The ruleset that protects the release lines.
750 #[must_use]
751 pub fn lines_ruleset(&self) -> &str {
752 &self.lines_ruleset
753 }
754
755 /// The context the landed forge gate reports under: the title job under
756 /// `squash`, the commit gate's job under `rebase`.
757 #[must_use]
758 pub fn title_check(&self) -> &str {
759 &self.title_check
760 }
761
762 /// Which authority carries an implementation onto this trunk.
763 #[must_use]
764 pub const fn integration(&self) -> crate::landing::Integration {
765 self.integration
766 }
767
768 /// How the commits of a branch reach this trunk, as the record says.
769 #[must_use]
770 pub const fn merge_form(&self) -> crate::landing::MergeForm {
771 self.merge_form
772 }
773
774 /// Whether the release tags are protected: wherever the release mode
775 /// is not `none`.
776 #[must_use]
777 pub const fn tag_protection(&self) -> bool {
778 self.tag_protection
779 }
780
781 /// Whether a forge gate lands, so the trunk requires its check and
782 /// GitLab requires the pipeline.
783 #[must_use]
784 pub const fn forge_gate(&self) -> bool {
785 self.forge_gate
786 }
787
788 /// The safety ruleset's rule types, sorted, as the compact JSON array
789 /// the protection check compares against the forge's answer.
790 fn safety_rule_types(&self) -> String {
791 let mut types: Vec<&str> = self
792 .protection
793 .owned_trunk_rules
794 .iter()
795 .map(String::as_str)
796 .filter(|rule| crate::config::SAFETY_RULES.contains(rule))
797 .collect();
798 types.sort_unstable();
799 types.dedup();
800 serde_json::to_string(&types).unwrap_or_else(|_| "[]".to_owned())
801 }
802
803 /// The trunk ruleset's rules: the request and the check it carries,
804 /// which the recorded bypass actors may be excused from.
805 fn trunk_rules(&self) -> String {
806 compose_rules(
807 &self.protection,
808 &crate::config::REQUEST_RULES,
809 self.required_check.as_deref().unwrap_or_default(),
810 &self.title_check,
811 )
812 }
813
814 /// The safety ruleset's rules: what holds against every actor.
815 fn safety_rules(&self) -> String {
816 compose_rules(
817 &self.protection,
818 &crate::config::SAFETY_RULES,
819 self.required_check.as_deref().unwrap_or_default(),
820 &self.title_check,
821 )
822 }
823
824 /// The setup answers a proof is judged against, by name: everything
825 /// that decides which steps run and what each one asserts, and
826 /// nothing about the host the run happened on. Each value is its
827 /// canonical text, so two runs that resolve the same target produce
828 /// the same map.
829 ///
830 /// SATISFIES setup-proof:the-proof-carries-no-secret-or-machine-coordinate
831 #[must_use]
832 pub fn proof_fields(&self) -> std::collections::BTreeMap<String, String> {
833 let mut fields = std::collections::BTreeMap::new();
834 let mut put = |key: &str, value: String| {
835 fields.insert(key.to_owned(), value);
836 };
837 put("forge", self.declared_forge.clone().unwrap_or_default());
838 put("host", self.host.clone().unwrap_or_default());
839 put("repo", self.repo.clone());
840 put("profile", canonical(&self.profile));
841 put("capabilities", canonical(&self.capabilities));
842 put("trunk", self.trunk.clone());
843 put("line_prefix", self.line_prefix.clone());
844 put("retired_branches", canonical(&self.retired_branches));
845 put("release_lines", bool_word(self.release_lines).to_owned());
846 put("integration", canonical(&self.integration));
847 put(
848 "required_check",
849 self.required_check.clone().unwrap_or_default(),
850 );
851 put(
852 "required_workflow",
853 self.required_workflow.clone().unwrap_or_default(),
854 );
855 put("bot_app_id", self.bot_app_id.clone().unwrap_or_default());
856 // Only where it is set: a proof counts a key one side lacks as a
857 // change, so an always-present key would turn every proof committed
858 // before the name existed stale.
859 if let Some(name) = &self.bot_name {
860 put("bot_name", name.clone());
861 }
862 put("trunk_ruleset", self.trunk_ruleset.clone());
863 put("safety_ruleset", self.safety_ruleset.clone());
864 put("tag_ruleset", self.tag_ruleset.clone());
865 put("lines_ruleset", self.lines_ruleset.clone());
866 put("title_check", self.title_check.clone());
867 put("protection", canonical(&self.protection));
868 fields
869 }
870
871 /// The floored policy this target states, already judged at load.
872 #[must_use]
873 pub const fn protection(&self) -> &crate::config::Protection {
874 &self.protection
875 }
876
877 /// Whether this run targets a GitLab instance that is not gitlab.com,
878 /// where registry trusted publishing cannot reach.
879 #[must_use]
880 pub fn self_hosted_gitlab(&self) -> bool {
881 self.forge == Some(Forge::Gitlab)
882 && self
883 .host
884 .as_deref()
885 .is_some_and(|host| host != "gitlab.com")
886 }
887
888 /// Whether this run targets gitlab.com itself, as a detected host.
889 ///
890 /// Positive on purpose: a run with no detected host answers false, so
891 /// a rule that loosens only for gitlab.com stays closed where the host
892 /// is unknown.
893 #[must_use]
894 pub fn on_gitlab_com(&self) -> bool {
895 self.forge == Some(Forge::Gitlab) && self.host.as_deref() == Some("gitlab.com")
896 }
897
898 /// The constructed environment a step receives. Secrets enter only for
899 /// the step that consumes them; the caller records their handling.
900 #[must_use]
901 #[allow(
902 clippy::too_many_lines,
903 reason = "one pass builds the whole environment a step receives, and splitting it would separate a variable from the value it carries"
904 )]
905 pub fn child_env(&self, step: &str) -> Vec<(OsString, OsString)> {
906 let mut env: Vec<(OsString, OsString)> = vec![
907 (
908 "RK_FORGE".into(),
909 self.forge.map_or("", Forge::as_str).into(),
910 ),
911 ("RK_REPO".into(), self.repo.clone().into()),
912 // The bot identity's configured name, empty where the forge's
913 // default applies, and whether the host is gitlab.com, where
914 // the identity form follows the namespace's tier.
915 (
916 "RK_BOT_NAME".into(),
917 self.bot_name.clone().unwrap_or_default().into(),
918 ),
919 (
920 "RK_GITLAB_COM".into(),
921 bool_word(self.on_gitlab_com()).into(),
922 ),
923 ("RK_TRUNK_BRANCH".into(), self.trunk.clone().into()),
924 ("RK_LINE_PREFIX".into(), self.line_prefix.clone().into()),
925 ("RK_TRUNK_RULESET".into(), self.trunk_ruleset.clone().into()),
926 (
927 "RK_SAFETY_RULESET".into(),
928 self.safety_ruleset.clone().into(),
929 ),
930 ("RK_TAG_RULESET".into(), self.tag_ruleset.clone().into()),
931 ("RK_LINES_RULESET".into(), self.lines_ruleset.clone().into()),
932 // The context the landed forge gate reports under, which the
933 // trunk ruleset requires: the title job under `squash` and the
934 // commit gate's job under `rebase`.
935 ("RK_TITLE_CHECK".into(), self.title_check.clone().into()),
936 // The recorded merge form, so a step asserts the squash
937 // settings only where a squash merge reads them.
938 ("RK_MERGE_FORM".into(), self.merge_form.as_str().into()),
939 // The two requirements the profile decides: the release tags
940 // are protected wherever a release mints them, and the trunk
941 // requires the gate's check, or GitLab's pipeline, wherever a
942 // forge gate lands to report it.
943 (
944 "RK_TAG_PROTECTION".into(),
945 bool_word(self.tag_protection).into(),
946 ),
947 ("RK_FORGE_GATE".into(), bool_word(self.forge_gate).into()),
948 // The floored policy, already judged against the floor table
949 // at load. A step receives values, never a judgment: one
950 // owner decides what passes, and it is not a shell script.
951 (
952 "RK_TAG_PATTERN".into(),
953 self.protection.tag_pattern.clone().into(),
954 ),
955 (
956 "RK_REVIEW_COUNT".into(),
957 self.protection
958 .required_approving_review_count
959 .to_string()
960 .into(),
961 ),
962 (
963 "RK_DISMISS_STALE_REVIEWS".into(),
964 bool_word(self.protection.dismiss_stale_reviews_on_push).into(),
965 ),
966 (
967 "RK_CODE_OWNER_REVIEW".into(),
968 bool_word(self.protection.require_code_owner_review).into(),
969 ),
970 (
971 "RK_LAST_PUSH_APPROVAL".into(),
972 bool_word(self.protection.require_last_push_approval).into(),
973 ),
974 (
975 "RK_MERGE_METHODS".into(),
976 json_list(&self.protection.allowed_merge_methods).into(),
977 ),
978 (
979 "RK_STRICT_CHECKS".into(),
980 bool_word(self.protection.strict_required_status_checks).into(),
981 ),
982 (
983 "RK_BYPASS_ACTORS".into(),
984 github_bypass_actors(&self.protection.bypass_actors)
985 .to_string()
986 .into(),
987 ),
988 (
989 "RK_SQUASH_TITLE_SOURCE".into(),
990 self.protection.github.squash_title_source.clone().into(),
991 ),
992 (
993 "RK_SQUASH_BODY_SOURCE".into(),
994 self.protection.github.squash_body_source.clone().into(),
995 ),
996 (
997 "RK_GITLAB_MERGE_METHOD".into(),
998 self.protection.gitlab.merge_method.clone().into(),
999 ),
1000 (
1001 "RK_GITLAB_SQUASH_OPTION".into(),
1002 self.protection.gitlab.squash_option.clone().into(),
1003 ),
1004 (
1005 "RK_GITLAB_SQUASH_TEMPLATE".into(),
1006 self.protection.gitlab.squash_commit_template.clone().into(),
1007 ),
1008 (
1009 "RK_GITLAB_PUSH_LEVEL".into(),
1010 self.protection.gitlab.push_access_level.to_string().into(),
1011 ),
1012 // The two rulesets' rules, built from the one key the floor
1013 // table judges and the observer reads, so the body a run
1014 // sends cannot install a rule the check does not expect, or
1015 // omit one it does. The split is what a bypass costs: an
1016 // actor excused from the trunk ruleset is excused from every
1017 // rule in it, so the rules that must hold against everyone
1018 // live in the safety ruleset, which names nobody.
1019 ("RK_TRUNK_RULES".into(), self.trunk_rules().into()),
1020 ("RK_SAFETY_RULES".into(), self.safety_rules().into()),
1021 (
1022 "RK_SAFETY_RULE_TYPES".into(),
1023 self.safety_rule_types().into(),
1024 ),
1025 (
1026 "RK_GITLAB_MERGE_LEVEL".into(),
1027 self.protection.gitlab.merge_access_level.to_string().into(),
1028 ),
1029 ("GH_PAGER".into(), "".into()),
1030 ("GLAB_PAGER".into(), "".into()),
1031 ];
1032 if let Some(check) = &self.required_check
1033 && self.forge == Some(Forge::Github)
1034 && self.forge_gate
1035 && matches!(step, "protect-trunk" | "protections-check")
1036 {
1037 env.push(("RK_REQUIRED_CHECK".into(), check.clone().into()));
1038 }
1039 for name in PASSTHROUGH {
1040 if let Some(value) = std::env::var_os(name) {
1041 env.push((name.into(), value));
1042 }
1043 }
1044 // The forge CLI override substitutes the binary for the run's own
1045 // calls; a step resolves the CLI by name, so the override's
1046 // directory leads the child's search path.
1047 if let Some(dir) = self.cli_override_dir() {
1048 let mut paths: Vec<PathBuf> = vec![dir];
1049 if let Some(existing) = std::env::var_os("PATH") {
1050 paths.extend(std::env::split_paths(&existing));
1051 }
1052 if let Ok(joined) = std::env::join_paths(paths) {
1053 env.retain(|(name, _)| name != "PATH");
1054 env.push(("PATH".into(), joined));
1055 }
1056 }
1057 if step == "bot-secrets" {
1058 for name in SECRET_VARS {
1059 if let Some(value) = secrets::value_of(name) {
1060 env.push((name.into(), value));
1061 }
1062 }
1063 }
1064 env
1065 }
1066
1067 /// The directory of an explicitly overridden forge CLI, where one is set.
1068 fn cli_override_dir(&self) -> Option<PathBuf> {
1069 let overridden = std::env::var_os(match self.forge? {
1070 Forge::Github => "RK_GH_BIN",
1071 Forge::Gitlab => "RK_GLAB_BIN",
1072 })?;
1073 Path::new(&overridden).parent().map(Path::to_path_buf)
1074 }
1075
1076 /// The secret bytes a run must keep out of its own output: the values
1077 /// the environment carries. Every buffer is scrubbed on drop; none is
1078 /// ever logged or echoed.
1079 ///
1080 /// Key material is not read here. The step that transmits a key adds
1081 /// the very bytes it sends, so the needle cannot describe one file
1082 /// while the child receives another.
1083 #[must_use]
1084 pub fn secret_values() -> Vec<Zeroizing<Vec<u8>>> {
1085 SECRET_VARS
1086 .iter()
1087 .filter_map(|name| secrets::value_of(name))
1088 .map(|value| Zeroizing::new(value.into_encoded_bytes()))
1089 .collect()
1090 }
1091}
1092
1093/// Resolve the forge CLI once, at context time: the `RK_GH_BIN` and
1094/// `RK_GLAB_BIN` overrides first, then a `PATH` search.
1095///
1096/// Not found and not executable are distinct failures, in the shell
1097/// convention. `rk branches prune` shares it for the verify path.
1098///
1099/// # Errors
1100///
1101/// Refuses when the override or the search resolves no usable binary.
1102pub fn resolve_cli(forge: Forge) -> Result<PathBuf, RkError> {
1103 let override_var = match forge {
1104 Forge::Github => "RK_GH_BIN",
1105 Forge::Gitlab => "RK_GLAB_BIN",
1106 };
1107 if let Some(overridden) = std::env::var_os(override_var).filter(|v| !v.is_empty()) {
1108 let path = PathBuf::from(&overridden);
1109 if !path.is_file() {
1110 return Err(RkError::refusal(
1111 Diagnostic::new(
1112 Reason::PrerequisiteUnmet,
1113 format!(
1114 "{override_var} names {}, which does not exist",
1115 path.display()
1116 ),
1117 )
1118 .expected("the override to name the forge CLI binary"),
1119 ));
1120 }
1121 // The scripts invoke the CLI by its canonical name through the
1122 // child's search path, so an override under any other name would
1123 // split one lifecycle across two binaries: observed through the
1124 // override, applied through whatever the name resolves to.
1125 if path.file_name().is_none_or(|name| name != forge.cli()) {
1126 return Err(RkError::refusal(
1127 Diagnostic::new(
1128 Reason::PrerequisiteUnmet,
1129 format!(
1130 "{override_var} must name a binary called {}, and {} is not one",
1131 forge.cli(),
1132 path.display()
1133 ),
1134 )
1135 .expected(format!(
1136 "an override whose file name is {}, so scripts and observations run one binary",
1137 forge.cli()
1138 )),
1139 ));
1140 }
1141 return Ok(path);
1142 }
1143 let name = forge.cli();
1144 let found = std::env::var_os("PATH").and_then(|path| {
1145 std::env::split_paths(&path)
1146 .map(|dir| dir.join(name))
1147 .find(|candidate| candidate.is_file())
1148 });
1149 found.ok_or_else(|| {
1150 RkError::refusal(
1151 Diagnostic::new(
1152 Reason::PrerequisiteUnmet,
1153 format!(
1154 "{name} is not on PATH, and a step this run acts on calls it on {}",
1155 forge.as_str()
1156 ),
1157 )
1158 .expected(format!("the {name} CLI installed and authenticated"))
1159 .action(format!("install {name}, then run {name} auth login")),
1160 )
1161 })
1162}
1163
1164#[cfg(test)]
1165mod tests {
1166 /// Both rulesets' rules come from the one owned-rules key, so what a
1167 /// run installs, what the floor table judges, and what the check
1168 /// expects cannot disagree. The split is what a bypass costs: a
1169 /// recorded actor is excused from every rule in the ruleset it names,
1170 /// so the rules that hold against everyone are composed apart, and a
1171 /// target under either authority composes the same two halves.
1172 #[test]
1173 fn each_ruleset_composes_its_half_of_the_owned_rule_key() {
1174 let kinds = |text: &str| -> Vec<String> {
1175 let parsed: Vec<serde_json::Value> =
1176 serde_json::from_str(text).expect("the rules parse");
1177 parsed
1178 .iter()
1179 .filter_map(|rule| rule["type"].as_str())
1180 .map(str::to_owned)
1181 .collect()
1182 };
1183 let mut policy = crate::config::Protection::default();
1184 let request =
1185 super::compose_rules(&policy, &crate::config::REQUEST_RULES, "gate", "pr-title");
1186 assert_eq!(kinds(&request), ["pull_request", "required_status_checks"]);
1187 let safety =
1188 super::compose_rules(&policy, &crate::config::SAFETY_RULES, "gate", "pr-title");
1189 assert_eq!(kinds(&safety), ["deletion", "non_fast_forward"]);
1190
1191 let parsed: Vec<serde_json::Value> =
1192 serde_json::from_str(&request).expect("the rules parse");
1193 let checks = parsed
1194 .iter()
1195 .find(|rule| rule["type"] == "required_status_checks")
1196 .expect("the check rule");
1197 assert_eq!(
1198 checks["parameters"]["required_status_checks"],
1199 serde_json::json!([{ "context": "gate" }, { "context": "pr-title" }])
1200 );
1201
1202 // The recorded bypass changes who is excused, never which rules
1203 // each ruleset carries.
1204 policy.bypass_actors = vec![crate::config::LOCAL_GITHUB_BYPASS.into()];
1205 assert_eq!(
1206 kinds(&super::compose_rules(
1207 &policy,
1208 &crate::config::REQUEST_RULES,
1209 "gate",
1210 "pr-title"
1211 )),
1212 ["pull_request", "required_status_checks"]
1213 );
1214 assert_eq!(
1215 kinds(&super::compose_rules(
1216 &policy,
1217 &crate::config::SAFETY_RULES,
1218 "gate",
1219 "pr-title"
1220 )),
1221 ["deletion", "non_fast_forward"]
1222 );
1223 }
1224
1225 /// One effective policy serves the body a step sends, the observer
1226 /// that reads the answer back, and every prerequisite.
1227 ///
1228 /// A target that stated nothing gets the compiled defaults, which
1229 /// describe forge integration because that is the shape this
1230 /// convention had before the axis existed — so under local
1231 /// integration they are adjusted: the GitHub administrator role gains
1232 /// the bypass that admits the direct push, and the GitLab level moves
1233 /// off the zero that would close the trunk to that push. A
1234 /// target that stated a policy keeps every value it stated, because
1235 /// the floor table already judged it under the same mode. The former
1236 /// compiled local tuple is migrated before setup can reinstall it.
1237 #[test]
1238 fn the_effective_policy_follows_the_recorded_authority() {
1239 use crate::landing::{Integration, MergeForm};
1240 let silent = super::effective_protection(
1241 None,
1242 Integration::Forge,
1243 MergeForm::Squash,
1244 crate::profile::ReleaseMode::Automatic,
1245 )
1246 .policy;
1247 assert!(
1248 silent
1249 .owned_trunk_rules
1250 .contains(&"pull_request".to_owned())
1251 );
1252 assert_eq!(silent.gitlab.push_access_level, 0);
1253
1254 let silent = super::effective_protection(
1255 None,
1256 Integration::Local,
1257 MergeForm::Squash,
1258 crate::profile::ReleaseMode::Automatic,
1259 )
1260 .policy;
1261 assert_eq!(
1262 silent.owned_trunk_rules,
1263 crate::config::Protection::default().owned_trunk_rules,
1264 "local integration retains the release request's atomic check"
1265 );
1266 assert_eq!(
1267 silent.bypass_actors,
1268 [crate::config::LOCAL_GITHUB_BYPASS.to_owned()]
1269 );
1270 assert_eq!(
1271 silent.gitlab.push_access_level, 40,
1272 "zero would close the trunk to the push this mode ends in"
1273 );
1274
1275 let mut stated = crate::config::Protection::default();
1276 stated.gitlab.push_access_level = 0;
1277 stated.owned_trunk_rules = vec!["deletion".into()];
1278 let held = super::effective_protection(
1279 Some(&stated),
1280 Integration::Local,
1281 MergeForm::Squash,
1282 crate::profile::ReleaseMode::Automatic,
1283 )
1284 .policy;
1285 assert_eq!(held.gitlab.push_access_level, 0, "a stated value wins");
1286 assert_eq!(held.owned_trunk_rules, ["deletion".to_owned()]);
1287
1288 let legacy = crate::config::Protection {
1289 owned_trunk_rules: vec!["deletion".into(), "non_fast_forward".into()],
1290 gitlab: crate::config::Gitlab {
1291 push_access_level: 40,
1292 ..crate::config::Gitlab::default()
1293 },
1294 ..crate::config::Protection::default()
1295 };
1296 let migrated = super::effective_protection(
1297 Some(&legacy),
1298 Integration::Local,
1299 MergeForm::Squash,
1300 crate::profile::ReleaseMode::Automatic,
1301 )
1302 .policy;
1303 assert_eq!(
1304 migrated,
1305 crate::config::local_protection(),
1306 "setup cannot reinstall the legacy policy while upgrade remains able to read it"
1307 );
1308 }
1309
1310 /// The merge values follow the recorded form under both authorities,
1311 /// whether the target stated a policy or not, and only the rebase form
1312 /// adds the linear-history rule, to the safety half.
1313 ///
1314 /// SATISFIES target-config:the-effective-protection-follows-the-profile
1315 #[test]
1316 fn merge_form_decides_the_effective_merge_values() {
1317 use crate::landing::{Integration, MergeForm};
1318 let kinds = |text: &str| -> Vec<String> {
1319 let parsed: Vec<serde_json::Value> =
1320 serde_json::from_str(text).expect("the rules parse");
1321 parsed
1322 .iter()
1323 .filter_map(|rule| rule["type"].as_str())
1324 .map(str::to_owned)
1325 .collect()
1326 };
1327 let stated = crate::config::Protection::default();
1328 for integration in [Integration::Forge, Integration::Local] {
1329 for held in [None, Some(&stated)] {
1330 let squash = super::effective_protection(
1331 held,
1332 integration,
1333 MergeForm::Squash,
1334 crate::profile::ReleaseMode::Automatic,
1335 )
1336 .policy;
1337 assert_eq!(squash.allowed_merge_methods, ["squash".to_owned()]);
1338 assert_eq!(squash.gitlab.squash_option, "always");
1339 assert!(
1340 !squash
1341 .owned_trunk_rules
1342 .contains(&crate::config::LINEAR_HISTORY_RULE.to_owned())
1343 );
1344 assert_eq!(
1345 kinds(&super::compose_rules(
1346 &squash,
1347 &crate::config::SAFETY_RULES,
1348 "gate",
1349 "pr-title"
1350 )),
1351 ["deletion", "non_fast_forward"]
1352 );
1353
1354 let rebase = super::effective_protection(
1355 held,
1356 integration,
1357 MergeForm::Rebase,
1358 crate::profile::ReleaseMode::Automatic,
1359 )
1360 .policy;
1361 assert_eq!(rebase.allowed_merge_methods, ["rebase".to_owned()]);
1362 assert_eq!(rebase.gitlab.squash_option, "never");
1363 assert_eq!(rebase.gitlab.merge_method, "ff");
1364 assert_eq!(
1365 kinds(&super::compose_rules(
1366 &rebase,
1367 &crate::config::SAFETY_RULES,
1368 "gate",
1369 "pr-commits"
1370 )),
1371 ["deletion", "non_fast_forward", "required_linear_history"]
1372 );
1373 assert_eq!(
1374 kinds(&super::compose_rules(
1375 &rebase,
1376 &crate::config::REQUEST_RULES,
1377 "gate",
1378 "pr-commits"
1379 )),
1380 ["pull_request", "required_status_checks"],
1381 "the linear-history rule never sits where a bypass excuses it"
1382 );
1383 }
1384 }
1385 }
1386
1387 /// The required context is the gate the form lands.
1388 #[test]
1389 fn merge_form_names_the_required_gate() {
1390 use crate::landing::MergeForm;
1391 let policy = crate::config::Protection::default();
1392 assert_eq!(super::gate_check(&policy, MergeForm::Squash), "pr-title");
1393 assert_eq!(super::gate_check(&policy, MergeForm::Rebase), "pr-commits");
1394 }
1395 /// The effective protection decides the two requirements from the
1396 /// profile: the tag protection follows the release mode alone, and the
1397 /// required check, carried by the trunk ruleset's check rule, follows
1398 /// the forge gate alone. Deletion and force-push hold in every cell.
1399 ///
1400 /// SATISFIES target-config:the-effective-protection-follows-the-profile
1401 #[test]
1402 fn release_less_effective_protection_follows_the_profile() {
1403 use crate::landing::{Integration, MergeForm};
1404 use crate::profile::ReleaseMode;
1405 for integration in [Integration::Forge, Integration::Local] {
1406 for form in [MergeForm::Squash, MergeForm::Rebase] {
1407 for mode in [
1408 ReleaseMode::Automatic,
1409 ReleaseMode::External,
1410 ReleaseMode::None,
1411 ] {
1412 let effective = super::effective_protection(None, integration, form, mode);
1413 let at = format!("{integration:?} {form:?} {mode:?}");
1414 let gate = integration == Integration::Forge || mode == ReleaseMode::Automatic;
1415 assert_eq!(effective.tag_protection, mode != ReleaseMode::None, "{at}");
1416 assert_eq!(effective.forge_gate, gate, "{at}");
1417 let rules = &effective.policy.owned_trunk_rules;
1418 assert_eq!(
1419 rules.iter().any(|rule| rule == "required_status_checks"),
1420 gate,
1421 "{at}: {rules:?}"
1422 );
1423 for kept in ["deletion", "non_fast_forward", "pull_request"] {
1424 assert!(rules.iter().any(|rule| rule == kept), "{at}: {kept}");
1425 }
1426 assert_eq!(
1427 effective.policy.allowed_merge_methods,
1428 [form.as_str().to_owned()],
1429 "{at}"
1430 );
1431 }
1432 }
1433 }
1434 }
1435}