1pub mod apply;
20pub mod invariants;
21pub mod lock;
22pub mod manifest;
23
24use camino::Utf8Path;
25
26pub use crate::projection::{
27 AGENTS_DESTINATION, BLOCK_BEGIN, BLOCK_DESTINATIONS, BLOCK_END, BRANCH_GRAMMAR,
28 CODE_SCANNING_DESTINATIONS, CODE_SCANNING_TECHS, GLOSSARY_DESTINATION, HOOK_TYPES_LINE,
29 HOOKS_BEGIN, HOOKS_DESTINATION, HOOKS_END, Kind, LINE_PREFIX_RE_TOKEN, LINE_PREFIX_TOKEN,
30 NIX_DESTINATIONS, NIX_WITHHOLDABLE, OWNER_TOKEN, REPO_PLACEHOLDER, REPO_TOKEN, SCOPE_SHAPE,
31 SCOPE_SHAPE_TOKEN, SCORECARD_DESTINATIONS, SECURITY_SPANS, STYLE_TOKEN, TRUNK_BRANCH_TOKEN,
32 authored, block_markers, destinations, extract_block, hooks_marker_defect, kind_of,
33 marker_defect, render, scope_is_shaped, splice_hooks_block, splice_marked_block, substitute,
34};
35pub use manifest::{CheckoutMode, Integration, MergeForm, Provider, Style};
36use serde::Serialize;
37
38use crate::diagnostic::{Diagnostic, Reason};
39use crate::error::RkError;
40
41pub use crate::profile::{Inputs, Params, Purpose};
42
43#[derive(Debug, Clone, Serialize)]
45pub struct Withheld {
46 pub path: String,
48 pub reason: String,
51}
52
53pub fn read_recorded(target: &Utf8Path, destination: &str) -> std::io::Result<Option<Vec<u8>>> {
64 let path = target.join(destination);
65 let bytes = match std::fs::read(&path) {
66 Ok(bytes) => bytes,
67 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
68 Err(e) => return Err(e),
69 };
70 if let Some((begin, end)) = block_markers(destination) {
71 let text = String::from_utf8_lossy(&bytes);
72 Ok(extract_block(&text, begin, end).map(|block| block.as_bytes().to_vec()))
73 } else {
74 Ok(Some(bytes))
75 }
76}
77
78#[derive(Debug)]
81pub struct Resolved {
82 pub forge: String,
84 pub repo: Option<String>,
86}
87
88pub fn resolve(
99 target: &Utf8Path,
100 forge_flag: Option<&str>,
101 repo_flag: Option<&str>,
102) -> Result<Resolved, RkError> {
103 let forge_flag = forge_flag
104 .map(|name| {
105 crate::detect::Forge::parse(name).ok_or_else(|| {
106 RkError::Usage(format!(
107 "unknown forge '{name}'; the forges are: github, gitlab"
108 ))
109 })
110 })
111 .transpose()?;
112 let detected = crate::detect::detect(target.as_std_path());
113 let forge = forge_flag
114 .or(detected.forge)
115 .map(|forge| forge.as_str().to_owned())
116 .ok_or_else(|| {
117 let message = detected.host.map_or_else(
118 || "no forge detected: the target has no origin remote".to_owned(),
119 |host| format!("no forge detected: the host {host} is not recognized"),
120 );
121 RkError::refusal(
122 Diagnostic::new(Reason::ForgeUndetected, message)
123 .expected("a github.com or gitlab remote, or --forge")
124 .action("pass --forge <github|gitlab>"),
125 )
126 })?;
127 Ok(Resolved {
128 forge,
129 repo: repo_flag.map(str::to_owned).or(detected.repo),
130 })
131}
132
133#[must_use]
136pub fn repo_unresolved() -> RkError {
137 RkError::missing(
138 Diagnostic::new(
139 Reason::ForgeUndetected,
140 "no repository detected: the target has no origin remote",
141 )
142 .expected("an origin remote naming the project")
143 .action("pass --repo <path>"),
144 )
145}
146
147#[cfg(test)]
148mod tests {
149 use super::{
150 AGENTS_DESTINATION, BLOCK_BEGIN, BLOCK_DESTINATIONS, BLOCK_END, BRANCH_GRAMMAR,
151 CheckoutMode, GLOSSARY_DESTINATION, HOOK_TYPES_LINE, HOOKS_BEGIN, HOOKS_DESTINATION,
152 HOOKS_END, Integration, Kind, Provider, SCOPE_SHAPE, Style, extract_block, kind_of, render,
153 splice_hooks_block, splice_marked_block,
154 };
155 use crate::embedded;
156 use crate::profile::{
157 CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
158 };
159 use crate::projection::{self, Projection, ProjectionInput, TargetEvidence};
160
161 const MODE_PAIRS: [(CheckoutMode, Integration); 4] = [
163 (CheckoutMode::MainWorktree, Integration::Forge),
164 (CheckoutMode::LinkedWorktree, Integration::Forge),
165 (CheckoutMode::MainWorktree, Integration::Local),
166 (CheckoutMode::LinkedWorktree, Integration::Local),
167 ];
168
169 fn destinations(params: &super::Params) -> Vec<String> {
172 Projection::compute(&ProjectionInput {
173 params: params.clone(),
174 evidence: TargetEvidence {
175 crate_shape: projection::CrateShape {
176 cargo_toml: Some(
177 "[package]\nname = \"widget\"\nversion = \"0.1.0\"\n".to_owned(),
178 ),
179 cargo_lock: true,
180 main_rs: true,
181 },
182 ..TargetEvidence::default()
183 },
184 })
185 .expect("the pair projects")
186 .candidates
187 .into_iter()
188 .map(|candidate| candidate.destination)
189 .collect()
190 }
191
192 fn routing_block(workflow_guards: bool) -> String {
193 projection::routing_block(workflow_guards).expect("the binary embeds the block")
194 }
195
196 fn hooks_block(mode: CheckoutMode) -> String {
197 projection::hooks_block(mode, Integration::Forge, true)
198 .expect("the binary embeds the block")
199 }
200
201 fn hooks_block_for(mode: CheckoutMode, integration: Integration) -> String {
202 projection::hooks_block(mode, integration, true).expect("the binary embeds the block")
203 }
204
205 fn unguarded_hooks_block(mode: CheckoutMode, integration: Integration) -> String {
206 projection::hooks_block(mode, integration, false).expect("the binary embeds the block")
207 }
208
209 fn glossary_block() -> String {
210 projection::glossary_block().expect("the binary embeds the block")
211 }
212
213 fn spliced(existing: Option<&str>, block: &str) -> String {
216 String::from_utf8(splice_marked_block(existing.map(str::as_bytes), block))
217 .expect("the fixtures are text")
218 }
219
220 #[test]
221 fn private_reporting_path_tokens_are_reproducible() {
222 for repo in [
223 "acme/widget",
224 "acme/group/widget",
225 "acme/OWNER-RK_STYLE-RK_SCOPE_SHAPE",
226 ] {
227 assert_eq!(
228 super::render(
229 b"RK_REPO RK_REPO OWNER RK_STYLE RK_SCOPE_SHAPE",
230 &super::Params::for_test(repo, Some(super::Style::Trunk))
231 ),
232 format!("{repo} {repo} acme trunk {}", super::SCOPE_SHAPE).as_bytes()
233 );
234 }
235 assert_eq!(super::kind_of("SECURITY.md"), Some(super::Kind::Rendered));
236 }
237
238 #[test]
243 fn each_forge_policy_carries_one_ordered_pair_of_every_span() {
244 for forge in ["github", "gitlab"] {
245 let bytes = embedded::SNIPPETS
246 .get_file(format!("_shared/{forge}/SECURITY.md"))
247 .expect("the policy ships")
248 .contents();
249 let text = String::from_utf8_lossy(bytes);
250 for (begin, end) in super::SECURITY_SPANS {
251 let begin = String::from_utf8_lossy(begin);
252 let end = String::from_utf8_lossy(end);
253 assert_eq!(text.matches(begin.as_ref()).count(), 1, "{forge} {begin}");
254 assert_eq!(text.matches(end.as_ref()).count(), 1, "{forge} {end}");
255 assert!(
256 text.find(begin.as_ref()) < text.find(end.as_ref()),
257 "{forge}: {begin} must precede {end}"
258 );
259 }
260 }
261 }
262
263 #[test]
268 fn the_security_spans_render_per_answer() {
269 for forge in ["github", "gitlab"] {
270 let bytes = embedded::SNIPPETS
271 .get_file(format!("_shared/{forge}/SECURITY.md"))
272 .expect("the policy ships")
273 .contents();
274 let authored = String::from_utf8_lossy(bytes);
275 let stripped = {
276 let mut text = authored.clone().into_owned();
277 for (begin, end) in super::SECURITY_SPANS {
278 text = text.replace(&String::from_utf8_lossy(begin).into_owned(), "");
279 text = text.replace(&String::from_utf8_lossy(end).into_owned(), "");
280 }
281 text
282 };
283 let mut default = super::Params::for_test_security("", crate::config::RESPONSE_DEFAULT);
284 default.set_pair_for_test("rust", forge);
285 let rendered = String::from_utf8(render(bytes, &default)).expect("text");
286 assert_eq!(
287 rendered,
288 stripped.replace("RK_REPO", "acme/widget"),
289 "{forge}: the default answers must reproduce the authored policy"
290 );
291 assert!(!rendered.contains("RK_SECURITY"), "{forge}: {rendered}");
292
293 let mut answered =
294 super::Params::for_test_security("OWNER RK_REPO <team@acme.example>", "14 days");
295 answered.set_pair_for_test("rust", forge);
296 let rendered = String::from_utf8(render(bytes, &answered)).expect("text");
297 assert!(
298 rendered.contains("OWNER RK_REPO <team@acme.example>"),
299 "{forge}: a contact spelling a token name lands literally: {rendered}"
300 );
301 assert!(
302 rendered.contains("Maintainers acknowledge a report within 14 days."),
303 "{forge}: {rendered}"
304 );
305 assert!(
306 rendered.contains("This policy commits to no disclosure deadline."),
307 "{forge}: {rendered}"
308 );
309 assert!(
310 !rendered.contains("best-effort basis"),
311 "{forge}: a stated window replaces the best-effort sentence: {rendered}"
312 );
313 assert!(
314 !rendered.contains("no response or disclosure deadline"),
315 "{forge}: a stated window contradicts the response disclaimer: {rendered}"
316 );
317 }
318 }
319
320 #[test]
323 fn a_defective_span_renders_unchanged() {
324 let (begin, end) = super::SECURITY_SPANS[0];
325 let begin = String::from_utf8_lossy(begin).into_owned();
326 let end = String::from_utf8_lossy(end).into_owned();
327 let params = super::Params::for_test_security("team@acme.example", "1 day");
328 for baseline in [
329 format!("contact {begin}a maintainer\n"),
330 format!("contact a maintainer{end}\n"),
331 format!("contact {end}a maintainer{begin}\n"),
332 "contact a maintainer\n".to_owned(),
333 ] {
334 assert_eq!(
335 render(baseline.as_bytes(), ¶ms),
336 baseline.as_bytes(),
337 "{baseline}"
338 );
339 }
340 }
341
342 #[test]
346 fn the_kind_table_closes_over_every_snippet() {
347 for tech_dir in embedded::SNIPPETS.dirs() {
348 for pair_dir in tech_dir.dirs() {
349 let prefix = format!("{}/", pair_dir.path().to_string_lossy());
350 for (path, _) in embedded::walk(pair_dir) {
351 let destination = path.strip_prefix(&prefix).unwrap_or(&path);
352 assert!(
353 kind_of(destination).is_some(),
354 "{destination}: no declared kind"
355 );
356 }
357 }
358 }
359 for block in BLOCK_DESTINATIONS {
360 assert_eq!(kind_of(block), Some(Kind::Rendered), "{block}");
361 }
362 assert_eq!(kind_of("something-else.txt"), None);
363 }
364
365 #[test]
370 fn rendering_substitutes_every_owner_occurrence() {
371 let baseline = b"if: repository_owner == 'OWNER'\n# OWNER again: OWNER\n";
372 let rendered = render(baseline, &super::Params::for_test("acme/sub/widget", None));
373 let text = String::from_utf8(rendered).expect("rendered bytes stay text");
374 assert_eq!(text, "if: repository_owner == 'acme'\n# acme again: acme\n");
375
376 let baseline = b"match (RK_SCOPE_SHAPE)\n";
377 let rendered = render(baseline, &super::Params::for_test("acme/widget", None));
378 let text = String::from_utf8(rendered).expect("rendered bytes stay text");
379 assert_eq!(text, format!("match ({SCOPE_SHAPE})\n"));
380 }
381
382 #[test]
386 fn the_scope_shape_drops_into_the_title_check() {
387 assert_eq!(SCOPE_SHAPE, "[a-z0-9._/-]+");
388 assert!(
389 !SCOPE_SHAPE.contains('\''),
390 "the title checks single-quote it"
391 );
392 }
393
394 #[test]
399 fn the_scope_predicate_and_the_rendered_pattern_agree() {
400 let body = SCOPE_SHAPE
401 .strip_prefix('[')
402 .and_then(|rest| rest.strip_suffix("]+"))
403 .expect("the shape is one bracket expression, repeated");
404 let chars: Vec<char> = body.chars().collect();
405 let mut admitted = std::collections::BTreeSet::new();
406 let mut at = 0;
407 while at < chars.len() {
408 if at + 2 < chars.len() && chars[at + 1] == '-' {
411 for c in chars[at]..=chars[at + 2] {
412 admitted.insert(c);
413 }
414 at += 3;
415 } else {
416 admitted.insert(chars[at]);
417 at += 1;
418 }
419 }
420 for byte in 0..=127u8 {
421 let c = char::from(byte);
422 assert_eq!(
423 super::scope_is_shaped(&c.to_string()),
424 admitted.contains(&c),
425 "the predicate and {SCOPE_SHAPE} disagree on {c:?}"
426 );
427 }
428 assert!(super::scope_is_shaped("guides/release"));
429 assert!(!super::scope_is_shaped(""), "a scope is never empty");
430 assert!(!super::scope_is_shaped("Specs Ugly"));
431 }
432
433 #[test]
437 fn the_shared_zone_composes_into_the_pair() {
438 let mut github = super::Params::for_test("acme/widget", Some(Style::Trunk));
439 github.set_pair_for_test("rust", "github");
440 let github = destinations(&github);
441 assert!(
442 github.contains(&".github/workflows/pr-title.yml".to_owned()),
443 "the shared title check lands with the pair"
444 );
445 assert!(github.contains(&"SECURITY.md".to_owned()));
446 let mut gitlab = super::Params::for_test("acme/widget", Some(Style::Trunk));
447 gitlab.set_pair_for_test("rust", "gitlab");
448 let gitlab = destinations(&gitlab);
449 assert!(
450 gitlab.contains(&".gitlab/ci/mr-title.yml".to_owned()),
451 "the shared title job lands with the pair"
452 );
453 assert!(
454 !crate::profile::catalog::known_drivers()
455 .iter()
456 .any(|driver| driver.starts_with('_')),
457 "the shared zone is no driver"
458 );
459 }
460
461 #[test]
464 fn params_from_a_record_round_trips() {
465 use super::{Params, manifest};
466 let dir = tempfile::tempdir().expect("a scratch target exists");
467 let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
468 for tech in ["rust", "bash"] {
469 for forge in ["github", "gitlab"] {
470 for (checkout_mode, integration) in MODE_PAIRS {
471 for style in [None, Some(Style::Trunk), Some(Style::Lines)] {
472 for ((nix, scorecard), code_scanning) in [
473 ((false, false), None),
474 ((false, true), Some(Provider::Semgrep)),
475 ((true, false), Some(Provider::CodeQl)),
476 ((true, true), None),
477 ] {
478 let record = manifest::Manifest {
479 schema_version: manifest::SCHEMA_VERSION,
480 rk_version: "0.1.0".to_owned(),
481 origin: "init".to_owned(),
482 landed_at: "2026-08-29T00:00:00Z".to_owned(),
483 profile: ProfileSnapshot {
484 technologies: vec![tech.to_owned()],
485 forge: Some(forge.to_owned()),
486 release: ReleaseIntent {
487 mode: ReleaseMode::Automatic,
488 driver: Some(tech.to_owned()),
489 style,
490 line_prefix: Some(
491 crate::config::LINE_PREFIX_DEFAULT.to_owned(),
492 ),
493 },
494 },
495 git: GitWorkflow {
496 trunk: crate::config::TRUNK_DEFAULT.to_owned(),
497 checkout_mode,
498 integration,
499 merge_form: crate::landing::MergeForm::Squash,
500 },
501 capabilities: CapabilityRequests {
502 nix_packaging: nix,
503 reporting_policy: true,
504 scorecard,
505 code_scanning,
506 workflow_guards: Some(true),
507 },
508 parameters: manifest::Parameters {
509 repo: "acme/team/widget".to_owned(),
510 security_contact: String::new(),
511 security_response: crate::config::RESPONSE_DEFAULT.to_owned(),
512 required_check: "gate".to_owned(),
513 required_workflow: "ci".to_owned(),
514 },
515 files: Vec::new(),
516 pins: std::collections::BTreeMap::new(),
517 };
518 manifest::write(target, &record).expect("the record writes");
519 let loaded = manifest::load(target)
520 .expect("the record loads")
521 .expect("the record exists");
522 let params = Params::from_record(&loaded);
523 assert_eq!(params.driver(), Some(tech));
524 assert_eq!(params.forge(), Some(forge));
525 assert_eq!(params.repo(), "acme/team/widget");
526 assert_eq!(params.integration(), integration);
527 assert_eq!(params.style(), style);
528 assert_eq!(params.nix_packaging(), nix);
529 assert_eq!(params.scorecard(), scorecard);
530 assert_eq!(params.code_scanning(), code_scanning);
531 let mut direct = super::Params::for_test("acme/team/widget", style);
534 direct.set_pair_for_test(tech, forge);
535 direct.set_checkout_mode_for_test(checkout_mode);
536 direct.set_integration_for_test(integration);
537 direct.set_nix_for_test(nix);
538 direct.set_scorecard_for_test(scorecard);
539 direct.set_code_scanning_for_test(code_scanning);
540 assert_eq!(params, direct);
541 let projected = destinations(¶ms);
542 for block in
543 [AGENTS_DESTINATION, GLOSSARY_DESTINATION, HOOKS_DESTINATION]
544 {
545 assert!(projected.contains(&block.to_owned()), "{block}");
546 }
547 for destination in super::NIX_DESTINATIONS {
548 assert_eq!(
549 projected.contains(&destination.to_owned()),
550 nix && tech == "rust",
551 "{tech} {forge} nix={nix}: {destination}"
552 );
553 }
554 for destination in super::SCORECARD_DESTINATIONS {
558 assert_eq!(
559 projected.contains(&destination.to_owned()),
560 scorecard && forge == "github",
561 "{tech} {forge} scorecard={scorecard}: {destination}"
562 );
563 }
564 }
565 }
566 }
567 }
568 }
569 }
570
571 fn resolved_test_params(
572 tech: &str,
573 resolved: &super::Resolved,
574 checkout_mode: CheckoutMode,
575 style: Option<Style>,
576 nix: bool,
577 scorecard: bool,
578 code_scanning: Option<Provider>,
579 ) -> Result<super::Params, crate::error::RkError> {
580 let technologies = vec![tech.to_owned()];
581 super::Params::resolve(
582 camino::Utf8Path::new("."),
583 &super::Inputs {
584 technologies: &technologies,
585 forge: Some(&resolved.forge),
586 repo: resolved.repo.as_deref(),
587 release_mode: Some(ReleaseMode::Automatic),
588 release_driver: Some(tech),
589 style,
590 required_check: (resolved.forge == "github").then_some("gate"),
592 required_workflow: (resolved.forge == "github").then_some("ci"),
593 trunk: None,
594 checkout_mode: Some(checkout_mode),
595 integration: None,
596 merge_form: None,
597 nix: Some(nix),
598 reporting_policy: None,
599 scorecard: Some(scorecard),
600 code_scanning: Some(code_scanning),
601 workflow_guards: Some(true),
602 },
603 None,
604 None,
605 super::Purpose::Init,
606 )
607 }
608
609 #[test]
613 fn a_projection_renders_owned_files_and_keeps_seeded_judgment() {
614 let params = resolved_test_params(
615 "rust",
616 &super::Resolved {
617 forge: "github".to_owned(),
618 repo: Some("acme/widget".to_owned()),
619 },
620 CheckoutMode::MainWorktree,
621 Some(Style::Trunk),
622 false,
623 false,
624 None,
625 )
626 .expect("the parameters resolve");
627 let entries = Projection::compute(&ProjectionInput {
628 params,
629 evidence: TargetEvidence::default(),
630 })
631 .expect("the pair projects")
632 .candidates;
633 let workflow = entries
634 .iter()
635 .find(|entry| entry.destination.ends_with("release-plz.yml"))
636 .expect("the workflow projects");
637 assert_eq!(workflow.kind, Kind::Rendered);
638 let text = String::from_utf8_lossy(&workflow.bytes);
639 assert!(!text.contains("OWNER"), "an owner token survived rendering");
640 assert!(text.contains("'acme'"));
641 assert!(!text.contains("TODO(release-kit)"));
642 let title = entries
643 .iter()
644 .find(|entry| entry.destination.ends_with("pr-title.yml"))
645 .expect("the title check projects");
646 let text = String::from_utf8_lossy(&title.bytes);
647 assert!(text.contains(SCOPE_SHAPE), "{text}");
648 assert!(
649 !text.contains("RK_SCOPE_SHAPE"),
650 "a scope token survived: {text}"
651 );
652 let seeded = entries
653 .iter()
654 .find(|entry| entry.destination == "release-plz.toml")
655 .expect("the seeded file projects");
656 assert_eq!(seeded.kind, Kind::Seeded);
657 let authored = embedded::SNIPPETS
658 .get_file("rust/github/release-plz.toml")
659 .expect("the seed ships")
660 .contents();
661 assert_eq!(seeded.bytes, authored, "a seeded file lands as authored");
662 assert!(String::from_utf8_lossy(&seeded.bytes).contains("TODO(release-kit)"));
663 for block in BLOCK_DESTINATIONS {
664 let entry = entries
665 .iter()
666 .find(|entry| entry.destination == block)
667 .expect("every block is part of the projection");
668 let text = String::from_utf8_lossy(&entry.bytes);
669 assert!(
670 !text.contains("RK_SCOPE_SHAPE"),
671 "{block} kept a token: {text}"
672 );
673 }
674 }
675
676 #[test]
681 fn the_nix_destinations_project_only_under_the_opt_in() {
682 use super::NIX_DESTINATIONS;
683 let paths = |nix: bool, forge: &str| -> Vec<String> {
684 destinations(
685 &resolved_test_params(
686 "rust",
687 &super::Resolved {
688 forge: forge.to_owned(),
689 repo: Some("acme/widget".to_owned()),
690 },
691 CheckoutMode::LinkedWorktree,
692 Some(Style::Trunk),
693 nix,
694 false,
695 None,
696 )
697 .expect("the parameters resolve"),
698 )
699 };
700 let off = paths(false, "github");
701 for destination in NIX_DESTINATIONS {
702 assert!(!off.contains(&destination.to_owned()), "{destination}");
703 }
704 let on = paths(true, "github");
705 for destination in ["nix/package.nix", "flake.nix", "flake.lock"] {
706 assert!(on.contains(&destination.to_owned()), "{destination}");
707 }
708 let gitlab = paths(true, "gitlab");
713 assert!(gitlab.contains(&"nix/package.nix".to_owned()));
714 assert!(
715 !on.iter()
716 .chain(gitlab.iter())
717 .any(|destination| destination.contains("nix.yml"))
718 );
719 let bash = destinations(
720 &resolved_test_params(
721 "bash",
722 &super::Resolved {
723 forge: "github".to_owned(),
724 repo: Some("acme/widget".to_owned()),
725 },
726 CheckoutMode::LinkedWorktree,
727 Some(Style::Trunk),
728 true,
729 false,
730 None,
731 )
732 .expect("the parameters resolve"),
733 );
734 assert!(
735 bash.iter()
736 .all(|destination| !NIX_DESTINATIONS.contains(&destination.as_str()))
737 );
738 }
739
740 #[test]
745 fn the_nix_seeds_are_identical_across_forge_pairs() {
746 for name in ["nix/package.nix", "flake.nix", "flake.lock"] {
747 let github = embedded::SNIPPETS
748 .get_file(format!("rust/github/{name}"))
749 .expect("the github copy ships")
750 .contents();
751 let gitlab = embedded::SNIPPETS
752 .get_file(format!("rust/gitlab/{name}"))
753 .expect("the gitlab copy ships")
754 .contents();
755 assert_eq!(github, gitlab, "{name} diverged between the pairs");
756 }
757 }
758
759 #[test]
764 fn the_nix_withhold_judgment_covers_the_three_shapes() {
765 use super::NIX_DESTINATIONS;
766 let dir = tempfile::tempdir().expect("a scratch target exists");
767 let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8 path");
768 let project = |nix: bool| {
769 let params = resolved_test_params(
770 "rust",
771 &super::Resolved {
772 forge: "github".to_owned(),
773 repo: Some("acme/widget".to_owned()),
774 },
775 CheckoutMode::LinkedWorktree,
776 Some(Style::Trunk),
777 nix,
778 false,
779 None,
780 )
781 .expect("the parameters resolve");
782 let evidence = TargetEvidence::gather(target, None).expect("the evidence reads");
783 Projection::compute(&ProjectionInput { params, evidence }).expect("the pair projects")
784 };
785 let withheld = |projection: &Projection| -> Vec<String> {
786 projection
787 .omissions
788 .iter()
789 .map(|omission| omission.destination.clone())
790 .collect()
791 };
792 let landed = |projection: &Projection, destination: &str| {
793 projection
794 .candidates
795 .iter()
796 .any(|candidate| candidate.destination == destination)
797 };
798
799 let all = project(true);
801 assert_eq!(
802 withheld(&all),
803 ["flake.lock", "flake.nix", "nix/package.nix"]
804 );
805 assert!(
806 all.candidates
807 .iter()
808 .all(|entry| !NIX_DESTINATIONS.contains(&entry.destination.as_str()))
809 );
810
811 std::fs::write(
814 target.join("Cargo.toml"),
815 "[package]\nname = \"widget\"\nversion = \"0.1.0\"\n",
816 )
817 .expect("the crate manifest writes");
818 std::fs::write(target.join("Cargo.lock"), "version = 4\n").expect("the lock writes");
819 std::fs::create_dir_all(target.join("src")).expect("the src dir exists");
820 std::fs::write(target.join("src/main.rs"), "fn main() {}\n").expect("the main writes");
821 std::fs::write(target.join("flake.nix"), "{ }\n").expect("the flake writes");
822 let all = project(true);
823 assert_eq!(withheld(&all), ["flake.lock", "flake.nix"]);
824 assert!(landed(&all, "nix/package.nix"));
825
826 std::fs::remove_file(target.join("flake.nix")).expect("the flake removes");
828 let all = project(true);
829 assert!(all.omissions.is_empty());
830 assert!(landed(&all, "flake.nix"));
831
832 let all = project(false);
834 assert!(all.omissions.is_empty());
835 assert!(!landed(&all, "flake.nix"));
836 }
837
838 #[test]
842 fn the_glossary_splices_into_every_shape() {
843 let owned = glossary_block();
844 let block = owned.as_str();
845
846 let fresh = spliced(None, block);
847 assert_eq!(fresh, format!("{block}\n"));
848 assert_eq!(extract_block(&fresh, BLOCK_BEGIN, BLOCK_END), Some(block));
849
850 let own = "# Glossary\n\n- `spike` — a throwaway branch.\n";
851 let appended = spliced(Some(own), block);
852 assert!(appended.starts_with(own));
853 assert_eq!(
854 extract_block(&appended, BLOCK_BEGIN, BLOCK_END),
855 Some(block)
856 );
857
858 let stale = appended.replace("full-implement", "do-everything");
859 let refreshed = spliced(Some(&stale), block);
860 assert_eq!(
861 extract_block(&refreshed, BLOCK_BEGIN, BLOCK_END),
862 Some(block)
863 );
864 assert_eq!(
865 refreshed.matches("BEGIN release-kit").count(),
866 1,
867 "a re-splice must replace, not accumulate"
868 );
869 }
870
871 #[test]
875 fn the_glossary_leaves_the_targets_region_alone() {
876 let owned = glossary_block();
877 let block = owned.as_str();
878 let below = "\n## Our own terms\n\n- `spike` — a throwaway branch, never merged.\n";
879 let landed = format!("{block}\n{below}");
880
881 let refreshed = spliced(Some(&landed), block);
882 assert!(
883 refreshed.ends_with(below),
884 "the target's own region changed: {refreshed}"
885 );
886 assert_eq!(
887 extract_block(&refreshed, BLOCK_BEGIN, BLOCK_END),
888 Some(block)
889 );
890 }
891
892 #[test]
896 fn an_append_rewrites_no_byte_the_target_wrote() {
897 let owned = glossary_block();
898 let block = owned.as_str();
899 for own in [
900 "# Glossary\n\n- `spike` — throwaway. \n\n\n",
901 "# Glossary\n\n- `spike` — throwaway.",
902 "# Glossary\r\n\r\n- `spike` — throwaway.\r\n",
903 ] {
904 let appended = spliced(Some(own), block);
905 assert!(
906 appended.starts_with(own),
907 "the target's bytes changed: {appended:?}"
908 );
909 assert_eq!(
910 extract_block(&appended, BLOCK_BEGIN, BLOCK_END),
911 Some(block),
912 "{appended:?}"
913 );
914 let marker = appended.find(BLOCK_BEGIN).expect("the block landed");
915 assert!(
916 appended[..marker].ends_with('\n'),
917 "the block must open its own line: {appended:?}"
918 );
919 }
920 }
921
922 #[test]
926 fn a_splice_decodes_no_byte_the_target_wrote() {
927 let owned = glossary_block();
928 let block = owned.as_str();
929
930 let own = b"# Glossary\n\ncaf\xe9\n";
932 let appended = splice_marked_block(Some(own), block);
933 assert!(
934 appended.starts_with(own),
935 "the target's bytes changed: {appended:?}"
936 );
937 assert!(!appended.contains(&0xEF), "a replacement character landed");
938
939 let mut landed = Vec::new();
941 landed.extend_from_slice(block.replace("full-implement", "do-everything").as_bytes());
942 landed.extend_from_slice(b"\n\ncaf\xe9\n");
943 let refreshed = splice_marked_block(Some(&landed), block);
944 assert!(
945 refreshed.ends_with(b"\n\ncaf\xe9\n"),
946 "the target's region below the markers changed: {refreshed:?}"
947 );
948 assert!(refreshed.starts_with(block.as_bytes()), "{refreshed:?}");
949 }
950
951 #[test]
954 fn the_glossary_block_carries_no_parameter() {
955 let block = glossary_block();
956 assert!(block.starts_with(BLOCK_BEGIN), "{block}");
957 assert!(block.ends_with(BLOCK_END), "{block}");
958 assert!(!block.contains("RK_"), "a token survived: {block}");
959 assert!(!block.contains("OWNER"), "an owner token survived: {block}");
960 for term in [
961 "implement-and-request",
962 "implement-and-merge",
963 "full-implement",
964 ] {
965 assert!(block.contains(term), "{term} is missing from {block}");
966 }
967 assert!(
968 routing_block(true).contains(GLOSSARY_DESTINATION),
969 "the routing block must name the destination it indexes"
970 );
971 assert!(
972 !routing_block(false).contains(GLOSSARY_DESTINATION),
973 "a target without the workflow guards lands no glossary to route to"
974 );
975 }
976
977 #[test]
978 fn the_block_splices_into_every_agents_shape() {
979 let owned = routing_block(false);
980 let block = owned.as_str();
981 let fresh = spliced(None, block);
982 assert_eq!(fresh, format!("{block}\n"));
983 assert_eq!(extract_block(&fresh, BLOCK_BEGIN, BLOCK_END), Some(block));
984
985 let appended = spliced(Some("# My project\n\nOwn rules.\n"), block);
986 assert!(appended.starts_with("# My project\n\nOwn rules.\n\n<!-- BEGIN release-kit -->"));
987 assert_eq!(
988 extract_block(&appended, BLOCK_BEGIN, BLOCK_END),
989 Some(block)
990 );
991
992 let stale = appended.replace("Never author a tag", "Do author a tag");
993 let refreshed = spliced(Some(&stale), block);
994 assert_eq!(
995 extract_block(&refreshed, BLOCK_BEGIN, BLOCK_END),
996 Some(block)
997 );
998 assert!(refreshed.starts_with("# My project"));
999 assert_eq!(
1000 refreshed.matches("BEGIN release-kit").count(),
1001 1,
1002 "a re-splice must replace, not accumulate"
1003 );
1004 }
1005
1006 #[test]
1009 fn the_hook_block_splices_under_repos() {
1010 let owned = hooks_block(CheckoutMode::MainWorktree);
1011 let block = owned.as_str();
1012 let fresh = splice_hooks_block(None, block).expect("a fresh file splices");
1013 assert!(fresh.starts_with(HOOK_TYPES_LINE));
1014 assert!(fresh.contains("\nrepos:\n# BEGIN release-kit\n"));
1015 assert_eq!(extract_block(&fresh, HOOKS_BEGIN, HOOKS_END), Some(block));
1016
1017 let own =
1018 "repos:\n - repo: https://example.com/own\n rev: v1\n hooks:\n - id: own\n";
1019 let spliced = splice_hooks_block(Some(own), block).expect("an unmarked file splices");
1020 assert!(spliced.starts_with("repos:\n# BEGIN release-kit\n"));
1021 assert!(spliced.contains("- id: own"), "the target's hooks survive");
1022 assert!(
1023 !spliced.contains(HOOK_TYPES_LINE),
1024 "an existing file's top level is the skills' duty, not the splice's"
1025 );
1026
1027 let stale = spliced.replace("--force-scope", "--no-scope");
1028 let refreshed = splice_hooks_block(Some(&stale), block).expect("a marked file re-splices");
1029 assert_eq!(
1030 extract_block(&refreshed, HOOKS_BEGIN, HOOKS_END),
1031 Some(block)
1032 );
1033 assert_eq!(refreshed.matches(HOOKS_BEGIN).count(), 1);
1034
1035 let err = splice_hooks_block(Some("minimum_pre_commit_version: '3.2.0'\n"), block)
1036 .expect_err("no repos: line refuses");
1037 assert!(err.contains("repos:"), "{err}");
1038
1039 let doubled = format!("repos:\n{block}\n{block}\n");
1043 let err = splice_hooks_block(Some(&doubled), block).expect_err("a second block refuses");
1044 assert!(err.contains("one block"), "{err}");
1045 let unmatched = "repos:\n# BEGIN release-kit\n - repo: local\n";
1046 let err =
1047 splice_hooks_block(Some(unmatched), block).expect_err("an unmatched marker refuses");
1048 assert!(err.contains("unmatched"), "{err}");
1049 }
1050
1051 #[test]
1057 fn the_blocks_render_per_mode_and_carry_the_one_grammar() {
1058 let worktree_hooks = hooks_block(CheckoutMode::LinkedWorktree);
1059 let branches_hooks = hooks_block(CheckoutMode::MainWorktree);
1060 assert!(worktree_hooks.contains("- id: rk-worktree-location"));
1061 assert!(
1062 worktree_hooks.contains("SKIP=no-commit-to-branch,rk-worktree-location"),
1063 "{worktree_hooks}"
1064 );
1065 assert!(!branches_hooks.contains("rk-worktree-location"));
1066 assert!(branches_hooks.contains("SKIP=no-commit-to-branch in"));
1067 for block in [&worktree_hooks, &branches_hooks] {
1068 assert!(block.contains(BRANCH_GRAMMAR), "the grammar has one owner");
1069 for token in [
1070 "RK_BRANCH_GRAMMAR",
1071 "RK_SWEEP_SKIP",
1072 "RK_SWEEP_NOTE",
1073 "RK_WORKTREE_GUARD",
1074 "RK_TRUNK_COMMIT_GUARD",
1075 "RK_TRUNK_PUSH_GUARD",
1076 ] {
1077 assert!(!block.contains(token), "{token} survived: {block}");
1078 }
1079 }
1080 for block in [&worktree_hooks, &branches_hooks] {
1085 for line in block.lines() {
1086 if let Some(value) = line.trim_start().strip_prefix("entry: ") {
1087 assert!(
1088 !value.contains(": "),
1089 "an entry value breaks the YAML plain scalar: {line}"
1090 );
1091 }
1092 }
1093 }
1094 let guard_line = worktree_hooks
1095 .lines()
1096 .position(|line| line.contains("id: rk-worktree-location"))
1097 .expect("the guard entry exists");
1098 let name_line = worktree_hooks
1099 .lines()
1100 .position(|line| line.contains("id: rk-branch-name"))
1101 .expect("the name hook exists");
1102 assert!(
1103 guard_line > name_line,
1104 "the guard lands directly after rk-branch-name"
1105 );
1106 }
1107
1108 #[test]
1113 fn the_routing_block_adds_only_the_policy_lines_under_the_guards() {
1114 let guarded = routing_block(true);
1115 let plain = routing_block(false);
1116 for block in [&guarded, &plain] {
1117 for token in ["RK_AGENT_POLICY", "RK_COMMIT_POLICY"] {
1118 assert!(!block.contains(token), "{token} survived: {block}");
1119 }
1120 for kept in [
1121 "runs the release-kit convention",
1122 "MUST be a scoped Conventional Commit",
1123 "Never author a tag",
1124 "Run `rk status` before changing",
1125 "`rk method --list`",
1126 ] {
1127 assert!(block.contains(kept), "{kept}: {block}");
1128 }
1129 for gone in [
1130 "`rk integrate <branch>`",
1131 "squash-merged pull request",
1132 "`rk issue start <issue>`",
1133 "`rk worktree add <branch>`",
1134 "Branches are worked in the main checkout",
1135 ] {
1136 assert!(!block.contains(gone), "{gone}: {block}");
1137 }
1138 }
1139 assert!(guarded.contains("guides and never drives"), "{guarded}");
1140 assert!(guarded.contains("`GLOSSARY.md`"), "{guarded}");
1141 assert!(guarded.contains("Every commit follows the same scoped convention"));
1142 assert!(!plain.contains("guides and never drives"), "{plain}");
1143 assert!(!plain.contains("Every commit follows"), "{plain}");
1144 let mut guarded_lines = guarded.lines();
1147 for line in plain.lines() {
1148 assert!(
1149 guarded_lines.any(|other| other == line),
1150 "the guards changed a line the plain block carries: {line}"
1151 );
1152 }
1153 }
1154
1155 fn release_words(text: &str) -> Vec<String> {
1159 text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
1160 .filter(|word| {
1161 matches!(
1162 *word,
1163 "version" | "versions" | "changelog" | "changelogs" | "tag" | "tags"
1164 )
1165 })
1166 .map(str::to_owned)
1167 .collect()
1168 }
1169
1170 fn shape(
1172 workflow_guards: bool,
1173 release: bool,
1174 merge_form: crate::landing::MergeForm,
1175 ) -> projection::BlockShape {
1176 projection::BlockShape {
1177 checkout_mode: CheckoutMode::LinkedWorktree,
1178 integration: Integration::Local,
1179 merge_form,
1180 workflow_guards,
1181 release,
1182 }
1183 }
1184
1185 #[test]
1194 fn workflow_only_routing_block_carries_no_release_text() {
1195 use crate::landing::MergeForm;
1196 for form in [MergeForm::Squash, MergeForm::Rebase] {
1197 for guards in [true, false] {
1198 let workflow = projection::routing_block_of(&shape(guards, false, form))
1199 .expect("the binary embeds the block");
1200 let at = format!("{form:?} guards {guards}");
1201 assert!(!workflow.contains("## Releases"), "{at}: {workflow}");
1202 assert!(workflow.contains("## Workflow"), "{at}: {workflow}");
1203 assert_eq!(release_words(&workflow), Vec::<String>::new(), "{at}");
1204 assert!(!workflow.contains("rk method recovery"), "{at}");
1205 for token in [
1206 "RK_AGENT_POLICY",
1207 "RK_COMMIT_POLICY",
1208 "RK_COMMIT_SOURCE",
1209 "RK_COMMIT_SCOPE",
1210 ] {
1211 assert!(!workflow.contains(token), "{at}: {token} survived");
1212 }
1213 assert!(
1214 workflow.contains("MUST be a Conventional Commit"),
1215 "{at}: {workflow}"
1216 );
1217 if guards {
1218 for kept in [
1219 "guides and never drives",
1220 "`implement-and-request` and `implement-and-merge`",
1221 "A scope is preferred and not required.",
1222 "names no internal planning artifact and carries no agent attribution",
1223 ] {
1224 assert!(workflow.contains(kept), "{at}: {kept}: {workflow}");
1225 }
1226 assert!(!workflow.contains("full-implement"), "{at}: {workflow}");
1227 assert!(!workflow.contains("requires a scope"), "{at}: {workflow}");
1228 }
1229 let releasing = projection::routing_block_of(&shape(guards, true, form))
1230 .expect("the binary embeds the block");
1231 assert!(releasing.contains("## Releases"), "{at}");
1232 assert!(releasing.contains("Never author a tag"), "{at}");
1233 if guards {
1234 assert!(releasing.contains("requires a scope on every one"), "{at}");
1235 assert_eq!(
1236 releasing.contains("The request's title becomes that commit's message"),
1237 form == MergeForm::Squash,
1238 "{at}: the title is the message under squash alone"
1239 );
1240 assert_eq!(
1241 releasing.contains(
1242 "Every commit of a branch reaches the trunk with its own message"
1243 ),
1244 form == MergeForm::Rebase,
1245 "{at}"
1246 );
1247 }
1248 }
1249 }
1250 assert_eq!(
1253 projection::routing_block_of(&shape(true, true, MergeForm::Squash))
1254 .expect("the binary embeds the block"),
1255 routing_block(true)
1256 );
1257 }
1258
1259 #[test]
1265 fn workflow_only_glossary_carries_no_release_term() {
1266 let workflow =
1267 projection::glossary_block_of(&shape(true, false, crate::landing::MergeForm::Squash))
1268 .expect("the binary embeds the block");
1269 assert!(workflow.contains("`implement-and-request`"), "{workflow}");
1270 assert!(workflow.contains("`implement-and-merge`"), "{workflow}");
1271 assert!(!workflow.contains("full-implement"), "{workflow}");
1272 assert!(!workflow.contains("release,"), "{workflow}");
1273 assert!(!workflow.contains("before the release"), "{workflow}");
1274 assert_eq!(release_words(&workflow), Vec::<String>::new());
1275 assert!(workflow.starts_with(BLOCK_BEGIN), "{workflow}");
1276 assert!(workflow.ends_with(BLOCK_END), "{workflow}");
1277 assert_eq!(
1278 projection::glossary_block_of(&shape(true, true, crate::landing::MergeForm::Squash))
1279 .expect("the binary embeds the block"),
1280 glossary_block()
1281 );
1282 }
1283
1284 #[test]
1290 fn workflow_only_hook_block_drops_the_tag_guard_and_the_forced_scope() {
1291 let authored = projection::embedded_block(projection::PRE_COMMIT_MESSAGE_GUARDS)
1292 .expect("the binary embeds the block");
1293 assert_eq!(
1294 authored.matches(projection::FORCE_SCOPE_ARG).count(),
1295 1,
1296 "the authored commit hook carries the argument the renderer drops: {authored}"
1297 );
1298 for (mode, integration) in MODE_PAIRS {
1299 for guards in [true, false] {
1300 let at = format!("{mode:?} {integration:?} guards {guards}");
1301 let release_less = projection::hooks_block_of(&projection::BlockShape {
1302 checkout_mode: mode,
1303 integration,
1304 merge_form: crate::landing::MergeForm::Squash,
1305 workflow_guards: guards,
1306 release: false,
1307 })
1308 .expect("the binary embeds the block");
1309 assert!(!release_less.contains("rk-no-hand-authored-tag"), "{at}");
1310 assert!(!release_less.contains("--force-scope"), "{at}");
1311 assert!(release_less.contains("- id: rk-status-check"), "{at}");
1312 assert!(!release_less.contains("RK_TAG_GUARD"), "{at}");
1313 assert!(!release_less.contains("RK_STATUS_RELEASE_FILES"), "{at}");
1314 assert!(!release_less.contains("release-plz"), "{at}");
1315 assert!(
1316 release_less.contains("\\.pre-commit-config\\.yaml$)'"),
1317 "{at}: {release_less}"
1318 );
1319 assert_eq!(release_words(&release_less), Vec::<String>::new(), "{at}");
1320 if guards {
1321 assert!(release_less.contains("args: [--strict]\n"), "{at}");
1322 }
1323 let releasing = if guards {
1324 hooks_block_for(mode, integration)
1325 } else {
1326 unguarded_hooks_block(mode, integration)
1327 };
1328 assert!(releasing.contains("- id: rk-no-hand-authored-tag"), "{at}");
1329 assert!(
1330 releasing.contains(r"\.pre-commit-config\.yaml$|release-plz\.toml$|dist-workspace\.toml$|release-please-config\.json$|cliff\.toml$|\.release-please-manifest\.json$|VERSION$)'"),
1331 "{at}: the release-bearing pattern is unchanged: {releasing}"
1332 );
1333 assert_eq!(releasing.contains("--force-scope"), guards, "{at}");
1334 }
1335 }
1336 }
1337
1338 #[test]
1342 fn the_hook_block_without_the_guards_keeps_the_release_hooks_alone() {
1343 for mode in [CheckoutMode::LinkedWorktree, CheckoutMode::MainWorktree] {
1344 for integration in [Integration::Forge, Integration::Local] {
1345 let block = unguarded_hooks_block(mode, integration);
1346 for kept in ["- id: rk-no-hand-authored-tag", "- id: rk-status-check"] {
1347 assert!(block.contains(kept), "{kept}: {block}");
1348 }
1349 for gone in [
1350 "conventional-pre-commit",
1351 "rk-message",
1352 "rk-branch-name",
1353 "rk-worktree-location",
1354 "rk-no-push-to-trunk",
1355 "no-commit-to-branch",
1356 ] {
1357 assert!(!block.contains(gone), "{gone}: {block}");
1358 }
1359 assert!(block.contains("A CI sweep needs no SKIP here"), "{block}");
1360 for token in [
1361 "RK_MESSAGE_GUARDS",
1362 "RK_BRANCH_NAME_GUARD",
1363 "RK_WORKTREE_GUARD",
1364 "RK_TRUNK_COMMIT_GUARD",
1365 "RK_TRUNK_PUSH_GUARD",
1366 "RK_SWEEP_NOTE",
1367 ] {
1368 assert!(!block.contains(token), "{token} survived: {block}");
1369 }
1370 assert_eq!(
1371 block.contains("--hook-stage manual"),
1372 integration == Integration::Local,
1373 "{block}"
1374 );
1375 }
1376 }
1377 }
1378
1379 #[test]
1393 fn the_integration_mode_decides_which_trunk_guards_render() {
1394 for mode in [CheckoutMode::LinkedWorktree, CheckoutMode::MainWorktree] {
1395 let forge = hooks_block_for(mode, Integration::Forge);
1396 let local = hooks_block_for(mode, Integration::Local);
1397 assert!(forge.contains("- id: no-commit-to-branch"), "{forge}");
1398 assert!(forge.contains("- id: rk-no-push-to-trunk"), "{forge}");
1399 assert!(!forge.contains("rk-no-force-push-to-trunk"), "{forge}");
1400 assert!(!forge.contains("rk-no-merge-commit-to-trunk"), "{forge}");
1401 assert!(local.contains("- id: no-commit-to-branch"), "{local}");
1402 assert!(
1403 local.contains("args: [--branch, RK_TRUNK_BRANCH]\n stages: [pre-commit]"),
1404 "the local trunk guard runs at the pre-commit stage alone: {local}"
1405 );
1406 assert!(local.contains("- id: rk-no-force-push-to-trunk"), "{local}");
1407 assert!(
1408 local.contains("- id: rk-no-merge-commit-to-trunk"),
1409 "{local}"
1410 );
1411 assert!(!local.contains("rk-no-push-to-trunk"), "{local}");
1412 for kept in [
1414 "- id: conventional-pre-commit",
1415 "- id: rk-message",
1416 "- id: rk-branch-name",
1417 "- id: rk-no-hand-authored-tag",
1418 "- id: rk-status-check",
1419 ] {
1420 assert!(forge.contains(kept), "{kept}: {forge}");
1421 assert!(local.contains(kept), "{kept}: {local}");
1422 }
1423 let located = mode == CheckoutMode::LinkedWorktree;
1426 assert_eq!(forge.contains("- id: rk-worktree-location"), located);
1427 assert_eq!(local.contains("- id: rk-worktree-location"), located);
1428 assert!(
1430 local.contains("pre-commit run --hook-stage manual --all-files"),
1431 "{local}"
1432 );
1433 assert!(!forge.contains("--hook-stage manual"), "{forge}");
1434 for token in [
1435 "RK_TRUNK_COMMIT_GUARD",
1436 "RK_TRUNK_PUSH_GUARD",
1437 "RK_SWEEP_NOTE",
1438 ] {
1439 assert!(!local.contains(token), "{token} survived: {local}");
1440 assert!(!forge.contains(token), "{token} survived: {forge}");
1441 }
1442 }
1443 assert!(
1447 hooks_block_for(CheckoutMode::LinkedWorktree, Integration::Local)
1448 .contains("SKIP=no-commit-to-branch,rk-worktree-location in")
1449 );
1450 assert!(
1451 hooks_block_for(CheckoutMode::MainWorktree, Integration::Local)
1452 .contains("SKIP=no-commit-to-branch in")
1453 );
1454 assert!(
1455 unguarded_hooks_block(CheckoutMode::MainWorktree, Integration::Local)
1456 .contains("A CI sweep needs no SKIP here")
1457 );
1458 }
1459
1460 #[test]
1466 fn a_landed_sweep_note_invites_the_projects_own_skips() {
1467 let with_skip = hooks_block_for(CheckoutMode::LinkedWorktree, Integration::Local);
1468 assert!(
1469 with_skip.contains("SKIP=no-commit-to-branch,rk-worktree-location in"),
1470 "{with_skip}"
1471 );
1472 assert!(with_skip.contains("local-only"), "{with_skip}");
1473 assert!(with_skip.contains("the value is a list the"), "{with_skip}");
1474
1475 let without = unguarded_hooks_block(CheckoutMode::MainWorktree, Integration::Local);
1476 assert!(
1477 without.contains("A CI sweep needs no SKIP here"),
1478 "{without}"
1479 );
1480 assert!(without.contains("local-only"), "{without}");
1481 }
1482
1483 #[test]
1489 fn a_landed_integrate_note_names_both_axes() {
1490 for mode in [CheckoutMode::LinkedWorktree, CheckoutMode::MainWorktree] {
1491 let local = hooks_block_for(mode, Integration::Local);
1492 assert!(
1493 local.contains("pre-commit run --hook-stage manual --all-files"),
1494 "{local}"
1495 );
1496 assert!(
1497 local.contains("continuous integration invoke the same stages"),
1498 "{local}"
1499 );
1500 assert!(
1501 local.contains("guards one side alone"),
1502 "the note states the consequence: {local}"
1503 );
1504 let forge = hooks_block_for(mode, Integration::Forge);
1506 assert!(!forge.contains("--hook-stage manual"), "{forge}");
1507 }
1508 }
1509
1510 #[test]
1514 fn the_hook_marker_defects_are_named() {
1515 use super::hooks_marker_defect;
1516 let owned = hooks_block(CheckoutMode::MainWorktree);
1517 let block = owned.as_str();
1518 assert_eq!(hooks_marker_defect(""), None);
1519 assert_eq!(hooks_marker_defect(&format!("repos:\n{block}\n")), None);
1520 for (case, text) in [
1521 (
1522 "a second begin",
1523 format!("repos:\n{block}\n# BEGIN release-kit\n"),
1524 ),
1525 (
1526 "a second end",
1527 format!("repos:\n{block}\n# END release-kit\n"),
1528 ),
1529 (
1530 "an unpaired begin",
1531 "repos:\n# BEGIN release-kit\n".to_owned(),
1532 ),
1533 ("an unpaired end", "repos:\n# END release-kit\n".to_owned()),
1534 (
1535 "an end before its begin",
1536 "repos:\n# END release-kit\n# BEGIN release-kit\n".to_owned(),
1537 ),
1538 ] {
1539 assert!(
1540 hooks_marker_defect(&text).is_some(),
1541 "{case} must be a defect"
1542 );
1543 }
1544 }
1545}