1pub mod evidence;
32
33use std::collections::BTreeMap;
34use std::fmt::Write as _;
35
36use serde::{Deserialize, Serialize};
37
38use crate::embedded;
39use crate::error::RkError;
40pub use crate::landing::manifest::Provider;
41use crate::landing::{CheckoutMode, Integration, MergeForm, Params};
42use crate::profile::ReleaseMode;
43use crate::profile::catalog::{self, Availability, Selection, Status};
44
45#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct ProjectionInput {
49 pub params: Params,
51 pub evidence: TargetEvidence,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Default)]
58#[allow(
59 clippy::struct_excessive_bools,
60 reason = "each field is one independent fact read off the target, not a state a smaller type could carry"
61)]
62pub struct TargetEvidence {
63 pub documents: BTreeMap<String, Vec<u8>>,
67 pub crate_shape: CrateShape,
69 pub flake_nix_present: bool,
71 pub flake_lock_present: bool,
73 pub flake_recorded: bool,
76 pub root_pipeline_present: bool,
78 pub root_pipeline_recorded: bool,
81}
82
83impl TargetEvidence {
84 #[must_use]
86 pub fn document(&self, destination: &str) -> Option<&[u8]> {
87 self.documents.get(destination).map(Vec::as_slice)
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Default)]
94pub struct CrateShape {
95 pub cargo_toml: Option<String>,
97 pub cargo_lock: bool,
99 pub main_rs: bool,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Projection {
110 pub capabilities: Vec<Selection>,
113 pub candidates: Vec<Candidate>,
115 pub omissions: Vec<Omission>,
120 pub collisions: Vec<Collision>,
123 pub licence_refusal: Option<String>,
129 pub record_defects: Vec<String>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct Candidate {
139 pub capability: &'static str,
141 pub destination: String,
143 pub kind: Kind,
145 pub placement: Placement,
147 pub bytes: Vec<u8>,
151 pub region: Option<Vec<u8>>,
154 pub sources: Vec<String>,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum Placement {
162 Whole,
164 Region {
167 begin: &'static str,
169 end: &'static str,
171 },
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct Omission {
177 pub destination: String,
179 pub reason: String,
181 pub action: Option<String>,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct Collision {
190 pub destination: String,
192 pub reason: String,
194}
195
196impl Projection {
197 pub fn compute(input: &ProjectionInput) -> Result<Self, RkError> {
207 Self::compute_over(&embedded_snippets(), input)
208 }
209
210 #[allow(
214 clippy::too_many_lines,
215 reason = "one pass selects, renders, splices, and withholds; splitting it would separate a withheld destination from the selection that offered it"
216 )]
217 fn compute_over(files: &[(String, &[u8])], input: &ProjectionInput) -> Result<Self, RkError> {
218 let params = &input.params;
219 let evidence = &input.evidence;
220 let availability = Availability::over(
221 files
222 .iter()
223 .filter_map(|(path, _)| path.strip_prefix("snippets/").map(str::to_owned))
224 .collect(),
225 );
226 let mut capabilities = catalog::select(params, &availability);
227 let mut candidates: Vec<Candidate> = Vec::new();
228 for selection in &capabilities {
229 if !selection.lands() {
230 continue;
231 }
232 for source in &selection.sources {
233 let destination = source
234 .splitn(3, '/')
235 .nth(2)
236 .ok_or_else(|| {
237 anyhow::anyhow!(
238 "{source}: a snippet path has a zone, a forge, and a destination"
239 )
240 })?
241 .to_owned();
242 let path = format!("snippets/{source}");
243 let bytes = files
244 .iter()
245 .find(|(candidate, _)| *candidate == path)
246 .map(|(_, bytes)| *bytes)
247 .ok_or_else(|| {
248 anyhow::anyhow!(
249 "{path}: the catalog selected a source the tree does not carry"
250 )
251 })?;
252 if let Some(existing) = candidates
253 .iter()
254 .find(|candidate| candidate.destination == destination)
255 {
256 return Err(anyhow::anyhow!(
257 "{} and {} both ship {destination}: {} and {path}; the embedded sources are defective",
258 existing.capability,
259 selection.id,
260 existing.sources.join(", ")
261 )
262 .into());
263 }
264 let kind = kind_of(&destination).ok_or_else(|| {
265 anyhow::anyhow!(
266 "the embedded sources do not classify {destination}; the kind table is stale"
267 )
268 })?;
269 let rendered = match kind {
272 Kind::Rendered => render(bytes, params),
273 Kind::Seeded => registry_lines(bytes, params),
274 Kind::State => bytes.to_vec(),
275 };
276 candidates.push(Candidate {
277 capability: selection.id,
278 destination,
279 kind,
280 placement: Placement::Whole,
281 bytes: rendered,
282 region: None,
283 sources: vec![path],
284 });
285 }
286 }
287 let mut collisions = Vec::new();
288 for destination in BLOCK_DESTINATIONS {
289 let Some((template, sources, capability)) = block_template(destination, params)? else {
290 continue;
291 };
292 if let Some(whole) = candidates
293 .iter()
294 .find(|candidate| candidate.destination == destination)
295 {
296 return Err(anyhow::anyhow!(
297 "{destination} is both a whole file from {} and a marked region from {}; the embedded sources are defective",
298 whole.sources.join(", "),
299 sources.join(", ")
300 )
301 .into());
302 }
303 let region = render(template.as_bytes(), params);
304 let (begin, end) = block_markers(destination).ok_or_else(|| {
305 anyhow::anyhow!("{destination} is a block destination with no markers")
306 })?;
307 match propose_document(destination, evidence.document(destination), ®ion) {
308 Ok(bytes) => candidates.push(Candidate {
309 capability,
310 destination: destination.to_owned(),
311 kind: Kind::Rendered,
312 placement: Placement::Region { begin, end },
313 bytes,
314 region: Some(region),
315 sources,
316 }),
317 Err(reason) => collisions.push(Collision {
318 destination: destination.to_owned(),
319 reason,
320 }),
321 }
322 }
323 let mut omissions = Vec::new();
324 if let Some((set, reason)) = nix_withholding(params.nix_packaging(), evidence)
325 && candidates
326 .iter()
327 .any(|candidate| candidate.capability == catalog::PACKAGING_NIX)
328 {
329 candidates.retain(|candidate| {
330 if set.contains(&candidate.destination.as_str()) {
331 omissions.push(Omission {
332 destination: candidate.destination.clone(),
333 reason: reason.clone(),
334 action: None,
335 });
336 false
337 } else {
338 true
339 }
340 });
341 withhold(&mut capabilities, catalog::PACKAGING_NIX, &reason, None);
342 }
343 let gate_root = candidates.iter().position(|candidate| {
349 (candidate.capability == catalog::TITLE_CHECK
350 || candidate.capability == catalog::COMMIT_CHECK)
351 && candidate.destination == GITLAB_ROOT_PIPELINE
352 });
353 if let Some(index) = gate_root
354 && evidence.root_pipeline_present
355 && !evidence.root_pipeline_recorded
356 {
357 let candidate = candidates.remove(index);
358 let (gate, fragment) = if candidate.capability == catalog::COMMIT_CHECK {
359 ("commit gate", GITLAB_COMMIT_FRAGMENT)
360 } else {
361 ("title gate", GITLAB_TITLE_FRAGMENT)
362 };
363 let reason = format!(
364 "the target owns {GITLAB_ROOT_PIPELINE}, so the release-less root pipeline that would activate the {gate} stays out; the fragment lands as the gate's prerequisite"
365 );
366 let action = format!(
367 "add the include to the target's own {GITLAB_ROOT_PIPELINE}: include:\n - local: {fragment}"
368 );
369 omissions.push(Omission {
370 destination: candidate.destination,
371 reason: reason.clone(),
372 action: Some(action.clone()),
373 });
374 withhold(
375 &mut capabilities,
376 candidate.capability,
377 &reason,
378 Some(action),
379 );
380 }
381 candidates.sort_by(|a, b| a.destination.cmp(&b.destination));
382 omissions.sort_by(|a, b| a.destination.cmp(&b.destination));
383 let scanning_selected = capabilities.iter().any(|selection| {
389 selection.id == catalog::CODE_SCANNING && selection.status == Status::Selected
390 });
391 let licence_refusal = scanning_selected
392 .then(|| {
393 code_scanning_licence_refusal(
394 params.code_scanning(),
395 params.driver(),
396 &evidence.crate_shape,
397 )
398 })
399 .flatten();
400 let mut record_defects: Vec<String> = Vec::new();
405 if params.release_mode() == ReleaseMode::Automatic
409 && let Some(selection) = capabilities
410 .iter()
411 .find(|selection| selection.id == catalog::RELEASE_AUTOMATION)
412 && matches!(selection.status, Status::Unavailable | Status::Unknown)
413 && let Some(reason) = &selection.reason
414 {
415 record_defects.push(reason.clone());
416 }
417 Ok(Self {
418 capabilities,
419 candidates,
420 omissions,
421 collisions,
422 licence_refusal,
423 record_defects,
424 })
425 }
426
427 #[must_use]
431 pub fn release_unavailable(&self) -> Option<&str> {
432 self.capabilities
433 .iter()
434 .find(|selection| {
435 selection.id == catalog::RELEASE_AUTOMATION
436 && matches!(selection.status, Status::Unavailable | Status::Unknown)
437 })
438 .and_then(|selection| selection.reason.as_deref())
439 }
440
441 #[must_use]
443 pub fn capability(&self, id: &str) -> Option<&Selection> {
444 self.capabilities
445 .iter()
446 .find(|selection| selection.id == id)
447 }
448}
449
450fn withhold(capabilities: &mut [Selection], id: &str, reason: &str, action: Option<String>) {
452 if let Some(selection) = capabilities.iter_mut().find(|selection| selection.id == id) {
453 selection.status = Status::Withheld;
454 selection.reason = Some(reason.to_owned());
455 selection.action = action;
456 }
457}
458
459pub const GITLAB_ROOT_PIPELINE: &str = ".gitlab-ci.yml";
462
463pub const GITLAB_TITLE_FRAGMENT: &str = ".gitlab/ci/mr-title.yml";
465
466pub const GITLAB_COMMIT_FRAGMENT: &str = ".gitlab/ci/mr-commits.yml";
468
469fn embedded_snippets() -> Vec<(String, &'static [u8])> {
472 embedded::walk(&embedded::SNIPPETS)
473 .into_iter()
474 .map(|(path, bytes)| (format!("snippets/{path}"), bytes))
475 .collect()
476}
477
478#[must_use]
481pub fn supported_pairs() -> Vec<(String, String)> {
482 Availability::embedded()
483 .automation_tuples()
484 .into_iter()
485 .filter_map(|entry| {
486 entry
487 .split_once(", ")
488 .map(|(driver, forge)| (driver.to_owned(), forge.to_owned()))
489 })
490 .collect()
491}
492
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
495#[serde(rename_all = "lowercase")]
496pub enum Kind {
497 Rendered,
500 Seeded,
503 State,
506}
507
508impl Kind {
509 #[must_use]
511 pub const fn as_str(self) -> &'static str {
512 match self {
513 Self::Rendered => "rendered",
514 Self::Seeded => "seeded",
515 Self::State => "state",
516 }
517 }
518}
519
520const KINDS: [(&str, Kind); 22] = [
526 (".github/workflows/release-plz.yml", Kind::Rendered),
527 (".github/workflows/release-please.yml", Kind::Rendered),
528 (".github/workflows/release.yml", Kind::Rendered),
529 (".github/workflows/pr-title.yml", Kind::Rendered),
530 (".github/workflows/pr-commits.yml", Kind::Rendered),
531 (".github/workflows/scorecard.yml", Kind::Rendered),
532 (".github/workflows/code-scanning-codeql.yml", Kind::Rendered),
533 (
534 ".github/workflows/code-scanning-semgrep.yml",
535 Kind::Rendered,
536 ),
537 (".gitlab/ci/code-scanning-semgrep.yml", Kind::Rendered),
538 (".gitlab-ci.yml", Kind::Rendered),
539 ("SECURITY.md", Kind::Rendered),
540 (".gitlab/ci/mr-title.yml", Kind::Rendered),
541 (".gitlab/ci/mr-commits.yml", Kind::Rendered),
542 ("release-plz.toml", Kind::Seeded),
543 ("dist-workspace.toml", Kind::Seeded),
544 ("release-please-config.json", Kind::Seeded),
545 ("cliff.toml", Kind::Seeded),
546 ("nix/package.nix", Kind::Seeded),
547 ("flake.nix", Kind::Seeded),
548 (".release-please-manifest.json", Kind::State),
549 ("VERSION", Kind::State),
550 ("flake.lock", Kind::State),
551];
552
553pub const NIX_DESTINATIONS: [&str; 3] = ["nix/package.nix", "flake.nix", "flake.lock"];
567
568pub const NIX_WITHHOLDABLE: [&str; 2] = ["flake.nix", "flake.lock"];
574
575pub const SCORECARD_DESTINATIONS: [&str; 1] = [".github/workflows/scorecard.yml"];
590
591pub const CODE_SCANNING_DESTINATIONS: [(&str, Provider); 3] = [
605 (
606 ".github/workflows/code-scanning-codeql.yml",
607 Provider::CodeQl,
608 ),
609 (
610 ".github/workflows/code-scanning-semgrep.yml",
611 Provider::Semgrep,
612 ),
613 (".gitlab/ci/code-scanning-semgrep.yml", Provider::Semgrep),
614];
615
616pub const CODE_SCANNING_TECHS: [&str; 1] = ["rust"];
624
625#[must_use]
642pub fn code_scanning_incompatibility(
643 provider: Option<Provider>,
644 driver: Option<&str>,
645 forge: Option<&str>,
646) -> Option<String> {
647 let named = provider?;
648 let Some(driver) = driver else {
649 return Some(format!(
650 "a scanner reads the release driver's language, and the profile names no automatic release driver; the bindings that carry one are: {}",
651 CODE_SCANNING_TECHS.join(", ")
652 ));
653 };
654 if !CODE_SCANNING_TECHS.contains(&driver) {
655 return Some(format!(
656 "the {driver} binding ships no code scanning workflow; a scanner reads one language, and the bindings that carry one are: {}",
657 CODE_SCANNING_TECHS.join(", ")
658 ));
659 }
660 let Some(forge) = forge else {
661 return Some(
662 "a code scanning workflow runs at a forge, and the profile names none".to_owned(),
663 );
664 };
665 if named == Provider::CodeQl && forge != "github" {
666 return Some(format!(
667 "codeql is GitHub's own analyzer and the {forge} pair ships no workflow for it; pass --code-scanning semgrep"
668 ));
669 }
670 None
671}
672
673const OSI_APPROVED: [&str; 18] = [
683 "0bsd",
684 "agpl-3.0",
685 "agpl-3.0-only",
686 "agpl-3.0-or-later",
687 "apache-2.0",
688 "bsd-2-clause",
689 "bsd-3-clause",
690 "bsl-1.0",
691 "epl-2.0",
692 "gpl-2.0",
693 "gpl-2.0-only",
694 "gpl-2.0-or-later",
695 "gpl-3.0",
696 "gpl-3.0-only",
697 "gpl-3.0-or-later",
698 "isc",
699 "mit",
700 "mpl-2.0",
701];
702
703const CONTENT_LICENCES: [&str; 4] = ["cc-by-3.0", "cc-by-4.0", "cc-by-sa-3.0", "cc-by-sa-4.0"];
721
722const SPDX_EXCEPTIONS: [&str; 86] = [
739 "389-exception",
740 "asterisk-exception",
741 "asterisk-linking-protocols-exception",
742 "autoconf-exception-2.0",
743 "autoconf-exception-3.0",
744 "autoconf-exception-generic",
745 "autoconf-exception-generic-3.0",
746 "autoconf-exception-macro",
747 "bison-exception-1.24",
748 "bison-exception-2.2",
749 "bootloader-exception",
750 "cgal-linking-exception",
751 "classpath-exception-2.0",
752 "classpath-exception-2.0-short",
753 "clisp-exception-2.0",
754 "cryptsetup-openssl-exception",
755 "digia-qt-lgpl-exception-1.1",
756 "digirule-foss-exception",
757 "ecos-exception-2.0",
758 "erlang-otp-linking-exception",
759 "fawkes-runtime-exception",
760 "fltk-exception",
761 "fmt-exception",
762 "font-exception-2.0",
763 "freertos-exception-2.0",
764 "gcc-exception-2.0",
765 "gcc-exception-2.0-note",
766 "gcc-exception-3.1",
767 "gmsh-exception",
768 "gnat-exception",
769 "gnome-examples-exception",
770 "gnu-compiler-exception",
771 "gnu-javamail-exception",
772 "google-patent-webm",
773 "gpl-3.0-389-ds-base-exception",
774 "gpl-3.0-interface-exception",
775 "gpl-3.0-linking-exception",
776 "gpl-3.0-linking-source-exception",
777 "gpl-cc-1.0",
778 "gstreamer-exception-2005",
779 "gstreamer-exception-2008",
780 "harbour-exception",
781 "i2p-gpl-java-exception",
782 "independent-modules-exception",
783 "kicad-libraries-exception",
784 "kvirc-openssl-exception",
785 "lgpl-3.0-linking-exception",
786 "libpri-openh323-exception",
787 "libtool-exception",
788 "linux-syscall-note",
789 "llgpl",
790 "llvm-exception",
791 "lzma-exception",
792 "mif-exception",
793 "mxml-exception",
794 "nokia-qt-exception-1.1",
795 "ocaml-lgpl-linking-exception",
796 "occt-exception-1.0",
797 "openjdk-assembly-exception-1.0",
798 "openvpn-openssl-exception",
799 "pcre2-exception",
800 "polyparse-exception",
801 "ps-or-pdf-font-exception-20170817",
802 "qpl-1.0-inria-2004-exception",
803 "qt-gpl-exception-1.0",
804 "qt-lgpl-exception-1.1",
805 "qwt-exception-1.0",
806 "romic-exception",
807 "rrdtool-floss-exception-2.0",
808 "rsync-linking-exception",
809 "sane-exception",
810 "shl-2.0",
811 "shl-2.1",
812 "simple-library-usage-exception",
813 "spelling-provider-lgpl-exception",
814 "sqlitestudio-openssl-exception",
815 "stunnel-exception",
816 "swi-exception",
817 "swift-exception",
818 "texinfo-exception",
819 "u-boot-exception-2.0",
820 "ubdl-exception",
821 "universal-foss-exception-1.0",
822 "vsftpd-openssl-exception",
823 "wxwindows-exception-3.1",
824 "x11vnc-openssl-exception",
825];
826
827fn listed(list: &[&str], identifier: &str) -> bool {
834 let lowered = identifier.to_ascii_lowercase();
835 list.contains(&lowered.as_str())
836}
837
838#[derive(Debug, Clone, Copy, PartialEq, Eq)]
840enum Token<'a> {
841 Open,
843 Close,
845 And,
847 Or,
849 With,
852 Identifier(&'a str),
855}
856
857fn tokenize(expression: &str) -> Option<Vec<Token<'_>>> {
865 let mut tokens = Vec::new();
866 let bytes = expression.as_bytes();
867 let mut at = 0;
868 while at < bytes.len() {
869 let byte = bytes[at];
870 if byte.is_ascii_whitespace() {
871 at += 1;
872 continue;
873 }
874 if byte == b'(' {
875 tokens.push(Token::Open);
876 at += 1;
877 continue;
878 }
879 if byte == b')' {
880 tokens.push(Token::Close);
881 at += 1;
882 continue;
883 }
884 let start = at;
885 while at < bytes.len() {
886 let byte = bytes[at];
887 if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+' | b':') {
888 at += 1;
889 } else {
890 break;
891 }
892 }
893 if at == start {
894 return None;
895 }
896 let word = &expression[start..at];
897 tokens.push(match word {
898 "AND" => Token::And,
899 "OR" => Token::Or,
900 "WITH" => Token::With,
901 other => Token::Identifier(other),
902 });
903 }
904 Some(tokens)
905}
906
907#[derive(Debug, Clone, Copy)]
914struct Verdict {
915 grants: bool,
917 clean: bool,
919}
920
921struct Spdx<'a> {
930 tokens: &'a [Token<'a>],
931 at: usize,
932}
933
934impl<'a> Spdx<'a> {
935 fn peek(&self) -> Option<Token<'a>> {
937 self.tokens.get(self.at).copied()
938 }
939
940 fn bump(&mut self) -> Option<Token<'a>> {
942 let token = self.peek()?;
943 self.at += 1;
944 Some(token)
945 }
946
947 fn expression(&mut self) -> Option<Verdict> {
957 let mut verdict = self.conjunction()?;
958 while self.peek() == Some(Token::Or) {
959 self.bump();
960 let right = self.conjunction()?;
961 verdict = Verdict {
962 grants: verdict.grants && right.grants,
963 clean: verdict.clean && right.clean,
964 };
965 }
966 Some(verdict)
967 }
968
969 fn conjunction(&mut self) -> Option<Verdict> {
979 let mut verdict = self.operand()?;
980 while self.peek() == Some(Token::And) {
981 self.bump();
982 let right = self.operand()?;
983 verdict = Verdict {
984 grants: verdict.grants || right.grants,
985 clean: verdict.clean && right.clean,
986 };
987 }
988 Some(verdict)
989 }
990
991 fn operand(&mut self) -> Option<Verdict> {
1001 match self.bump()? {
1002 Token::Open => {
1003 let inner = self.expression()?;
1006 (self.bump()? == Token::Close).then_some(inner)
1007 }
1008 Token::Identifier(name) => {
1009 let identifier = name.strip_suffix('+').unwrap_or(name);
1010 let approved = listed(&OSI_APPROVED, identifier);
1011 let verdict = Verdict {
1012 grants: approved,
1013 clean: approved || listed(&CONTENT_LICENCES, identifier),
1014 };
1015 if self.peek() == Some(Token::With) {
1016 self.bump();
1017 match self.bump()? {
1021 Token::Identifier(exception) if listed(&SPDX_EXCEPTIONS, exception) => {}
1022 _ => return None,
1023 }
1024 }
1025 Some(verdict)
1026 }
1027 Token::And | Token::Or | Token::With | Token::Close => None,
1028 }
1029 }
1030}
1031
1032#[must_use]
1048pub fn licence_states_an_open_source_codebase(expression: &str) -> bool {
1049 let Some(tokens) = tokenize(expression) else {
1050 return false;
1051 };
1052 let mut reader = Spdx {
1053 tokens: &tokens,
1054 at: 0,
1055 };
1056 let Some(verdict) = reader.expression() else {
1057 return false;
1058 };
1059 verdict.grants && verdict.clean && reader.at == tokens.len()
1060}
1061
1062#[must_use]
1076pub fn code_scanning_licence_refusal(
1077 provider: Option<Provider>,
1078 driver: Option<&str>,
1079 shape: &CrateShape,
1080) -> Option<String> {
1081 if provider != Some(Provider::CodeQl) {
1082 return None;
1083 }
1084 if driver != Some("rust") {
1085 return Some(format!(
1086 "the {} binding declares no licence field this release reads, and codeql's terms cover an open-source codebase alone; land --code-scanning semgrep, which carries no licence condition",
1087 driver.unwrap_or("release-less")
1088 ));
1089 }
1090 let fallback = "land --code-scanning semgrep, which carries no licence condition";
1091 let Some(text) = shape.cargo_toml.as_deref() else {
1092 return Some(format!(
1093 "the target has no readable Cargo.toml, so the licence codeql's terms depend on cannot be read; {fallback}"
1094 ));
1095 };
1096 let Ok(table) = text.parse::<toml::Table>() else {
1097 return Some(format!(
1098 "the target's Cargo.toml does not parse, so the licence codeql's terms depend on cannot be read; {fallback}"
1099 ));
1100 };
1101 let licence = table
1102 .get("package")
1103 .and_then(toml::Value::as_table)
1104 .and_then(|package| package.get("license"))
1105 .and_then(toml::Value::as_str);
1106 match licence {
1107 None => Some(format!(
1108 "the target's Cargo.toml declares no license field, and codeql's terms cover an open-source codebase alone; declare one, or {fallback}"
1109 )),
1110 Some(expression) if !licence_states_an_open_source_codebase(expression) => Some(format!(
1111 "the target's license, {expression}, does not state a codebase this release recognizes as open source, and codeql's terms cover an open-source codebase alone; {fallback}"
1112 )),
1113 Some(_) => None,
1114 }
1115}
1116
1117#[must_use]
1120pub fn kind_of(destination: &str) -> Option<Kind> {
1121 if BLOCK_DESTINATIONS.contains(&destination) {
1122 return Some(Kind::Rendered);
1123 }
1124 KINDS
1125 .iter()
1126 .find(|(name, _)| *name == destination)
1127 .map(|(_, kind)| *kind)
1128}
1129
1130pub fn destinations() -> impl Iterator<Item = &'static str> {
1135 KINDS
1136 .iter()
1137 .map(|(name, _)| *name)
1138 .chain(BLOCK_DESTINATIONS)
1139}
1140
1141pub const OWNER_TOKEN: &[u8] = b"OWNER";
1148
1149pub const REPO_PLACEHOLDER: &str = "OWNER";
1154
1155pub const REPO_TOKEN: &[u8] = b"RK_REPO";
1157
1158pub const SCOPE_SHAPE_TOKEN: &[u8] = b"RK_SCOPE_SHAPE";
1160
1161pub const IF_RELEASE_TOKEN: &[u8] = b"RK_IF_RELEASE_";
1166
1167pub const IF_NO_RELEASE_TOKEN: &[u8] = b"RK_IF_NO_RELEASE_";
1170
1171pub const IF_REGISTRY_TOKEN: &[u8] = b" # RK_IF_REGISTRY";
1179
1180pub const IF_NO_REGISTRY_TOKEN: &[u8] = b"# RK_IF_NO_REGISTRY ";
1186
1187#[must_use]
1193pub fn registry_lines(baseline: &[u8], params: &Params) -> Vec<u8> {
1194 if find(baseline, IF_REGISTRY_TOKEN).is_none() && find(baseline, IF_NO_REGISTRY_TOKEN).is_none()
1195 {
1196 return baseline.to_vec();
1197 }
1198 let publishes = params.registry() != Some(crate::profile::RegistryAnswer::None);
1199 let mut out = Vec::with_capacity(baseline.len());
1200 for line in baseline.split_inclusive(|byte| *byte == b'\n') {
1201 let (token, wanted) = if find(line, IF_NO_REGISTRY_TOKEN).is_some() {
1202 (IF_NO_REGISTRY_TOKEN, !publishes)
1203 } else if find(line, IF_REGISTRY_TOKEN).is_some() {
1204 (IF_REGISTRY_TOKEN, publishes)
1205 } else {
1206 out.extend_from_slice(line);
1207 continue;
1208 };
1209 if wanted {
1210 out.extend(substitute(line, token, b""));
1211 }
1212 }
1213 out
1214}
1215
1216pub const SCOPED_TOKEN: &[u8] = b"RK_SCOPED";
1220
1221pub const SCOPE_OPEN_TOKEN: &[u8] = b"RK_SCOPE_OPEN";
1227
1228pub const SCOPE_CLOSE_TOKEN: &[u8] = b"RK_SCOPE_CLOSE";
1230
1231fn release_lines(baseline: &[u8], release: bool) -> Vec<u8> {
1236 if find(baseline, IF_RELEASE_TOKEN).is_none() && find(baseline, IF_NO_RELEASE_TOKEN).is_none() {
1237 return baseline.to_vec();
1238 }
1239 let mut out = Vec::with_capacity(baseline.len());
1240 for line in baseline.split_inclusive(|byte| *byte == b'\n') {
1241 let (token, wanted) = if find(line, IF_NO_RELEASE_TOKEN).is_some() {
1244 (IF_NO_RELEASE_TOKEN, !release)
1245 } else if find(line, IF_RELEASE_TOKEN).is_some() {
1246 (IF_RELEASE_TOKEN, release)
1247 } else {
1248 out.extend_from_slice(line);
1249 continue;
1250 };
1251 if wanted {
1252 out.extend(substitute(line, token, b""));
1253 }
1254 }
1255 out
1256}
1257
1258pub const GITLAB_GATE_FRAGMENT_TOKEN: &[u8] = b"RK_GITLAB_GATE_FRAGMENT";
1261
1262pub const MERGE_FLAG_TOKEN: &[u8] = b"RK_MERGE_FLAG";
1265
1266pub const SQUASH_ON_MERGE_TOKEN: &[u8] = b"RK_SQUASH_ON_MERGE";
1270
1271pub const STYLE_TOKEN: &[u8] = b"RK_STYLE";
1274
1275pub const TRUNK_BRANCH_TOKEN: &[u8] = b"RK_TRUNK_BRANCH";
1279
1280pub const LINE_PREFIX_TOKEN: &[u8] = b"RK_LINE_PREFIX";
1283
1284pub const LINE_PREFIX_RE_TOKEN: &[u8] = b"RK_LINE_PREFIX_RE";
1290
1291pub const PUSH_GUARD_TOKEN: &[u8] = b" # RK_PUSH_GUARD";
1301
1302pub const REQUIRED_CHECK_TOKEN: &[u8] = b"RK_REQUIRED_CHECK";
1304
1305pub const REQUIRED_WORKFLOW_TOKEN: &[u8] = b"RK_REQUIRED_WORKFLOW";
1307
1308pub const BRANCH_SHAPE_TOKEN: &[u8] = b"RK_BRANCH_SHAPE";
1310
1311pub const REQUEST_JOB_TOKEN: &[u8] = b"RK_REQUEST_JOB";
1313
1314pub const RELEASE_GATE_TRIGGER: &str = "blocks/release-gate-trigger.yaml.in";
1316
1317pub const RELEASE_GATE_JOB: &str = "blocks/release-gate-job.yaml.in";
1319
1320#[must_use]
1327pub fn release_driver_shape(driver: Option<&str>) -> Option<(&'static str, &'static str)> {
1328 match driver {
1329 Some("rust") => Some(("release-plz-", "release-plz-pr")),
1332 Some("bash") => Some(("chore/release-v", "release-request")),
1334 Some("python") => Some((
1338 "release-please--branches--RK_TRUNK_BRANCH",
1339 "release-please-pr",
1340 )),
1341 _ => None,
1342 }
1343}
1344
1345#[must_use]
1356pub fn release_gate_spans(driver: Option<&str>) -> [(&'static [u8], &'static [u8]); 3] {
1357 let arm: (&[u8], &[u8]) = if driver == Some("bash") {
1361 (
1362 b"\n # RK_GATE_ARM_BEGIN",
1363 b"\n # RK_GATE_ARM_END",
1364 )
1365 } else {
1366 (b"\n# RK_GATE_ARM_BEGIN", b"\n# RK_GATE_ARM_END")
1367 };
1368 [
1369 (b"\n# RK_GATE_TRIGGER_BEGIN", b"\n# RK_GATE_TRIGGER_END"),
1370 arm,
1371 (b"\n# RK_GATE_JOB_BEGIN", b"\n# RK_GATE_JOB_END"),
1372 ]
1373}
1374
1375#[must_use]
1383fn release_gates(params: &Params) -> bool {
1384 params.forge() == Some("github")
1385 && params.integration() == crate::landing::Integration::Local
1386 && params.release_mode() == ReleaseMode::Automatic
1387 && params.style() == Some(crate::landing::Style::Trunk)
1388 && !params.required_check().is_empty()
1389 && !params.required_workflow().is_empty()
1390 && release_driver_shape(params.driver()).is_some()
1391}
1392
1393fn release_gate_replacements(params: &Params) -> Result<[Option<Vec<u8>>; 3], RkError> {
1405 if !release_gates(params) {
1406 return Ok([None, None, None]);
1407 }
1408 let opened = |block: &str| -> Result<Vec<u8>, RkError> {
1411 let text = embedded_block(block)?;
1412 Ok(substitute_tokens(
1413 format!("\n{}", text.trim_end_matches('\n')).as_bytes(),
1414 params,
1415 ))
1416 };
1417 Ok([
1418 Some(opened(RELEASE_GATE_TRIGGER)?),
1419 Some(Vec::new()),
1422 Some(opened(RELEASE_GATE_JOB)?),
1423 ])
1424}
1425
1426pub const DEV_RUN_TOKEN: &[u8] = b"RK_DEV_RUN ";
1433
1434pub const DEV_SETUP_STEPS_TOKEN: &[u8] = b"RK_DEV_SETUP_STEPS";
1437
1438pub const DEV_GIT_USER_TOKEN: &[u8] = b"RK_DEV_GIT_USER";
1440
1441pub const DEV_ENVIRONMENT_RELEASE: &str = "blocks/dev-environment-release.yaml.in";
1443
1444pub const DEV_ENVIRONMENT_REQUEST: &str = "blocks/dev-environment-request.yaml.in";
1446
1447pub const DEV_ENVIRONMENT_GIT_USER: &str = "blocks/dev-environment-git-user.yaml.in";
1450
1451pub const DEV_ENVIRONMENT_SPANS: [(&[u8], &[u8]); 4] = [
1461 (
1462 b"\n# RK_DEV_ENV_RELEASE_BEGIN",
1463 b"\n# RK_DEV_ENV_RELEASE_END",
1464 ),
1465 (
1466 b"\n# RK_DEV_ENV_REQUEST_BEGIN",
1467 b"\n# RK_DEV_ENV_REQUEST_END",
1468 ),
1469 (b"\n# RK_DEV_ENV_IMAGE_BEGIN", b"\n# RK_DEV_ENV_IMAGE_END"),
1470 (b"\n# RK_DEV_ENV_SCRIPT_BEGIN", b"\n# RK_DEV_ENV_SCRIPT_END"),
1471];
1472
1473fn action_step_lines(step: &crate::config::dev_environment::ActionStep) -> String {
1476 let mut lines = format!(" - uses: {}", step.uses);
1477 if !step.tag.is_empty() {
1478 lines.push_str(" # ");
1479 lines.push_str(&step.tag);
1480 }
1481 lines.push('\n');
1482 if !step.inputs.is_empty() {
1483 lines.push_str(" with:\n");
1484 for (name, value) in &step.inputs {
1485 let _ = writeln!(lines, " {name}: {}", value.yaml());
1486 }
1487 }
1488 lines
1489}
1490
1491fn dev_environment_replacements(params: &Params) -> Result<[Option<Vec<u8>>; 4], RkError> {
1508 let Some(answer) = params.dev_environment() else {
1509 return Ok([None, None, None, None]);
1510 };
1511 let git_user = embedded_block(DEV_ENVIRONMENT_GIT_USER)?.trim_end_matches('\n');
1512 let half = |block: &str, steps: &[&crate::config::dev_environment::ActionStep]| {
1513 let text = embedded_block(block)?.trim_end_matches('\n');
1514 let text = substitute(text.as_bytes(), DEV_GIT_USER_TOKEN, git_user.as_bytes());
1515 let text = substitute_tokens(&text, params);
1516 let lines: String = steps.iter().map(|step| action_step_lines(step)).collect();
1517 let mut out = b"\n".to_vec();
1518 out.extend(substitute(&text, DEV_SETUP_STEPS_TOKEN, lines.as_bytes()));
1519 Ok::<_, RkError>(out)
1520 };
1521 let release: Vec<_> = answer.github.setup.iter().collect();
1522 let request: Vec<_> = answer
1523 .github
1524 .setup
1525 .iter()
1526 .chain(&answer.github.cache)
1527 .collect();
1528 let image = (!answer.gitlab.image.is_empty())
1529 .then(|| format!("\n image: {}", answer.gitlab.image).into_bytes());
1530 let script = if answer.gitlab.before_script.is_empty() {
1531 Vec::new()
1532 } else {
1533 let mut lines = "\n before_script:".to_owned();
1534 for line in &answer.gitlab.before_script {
1535 lines.push_str("\n - ");
1536 lines.push_str(&serde_json::Value::String(line.clone()).to_string());
1537 }
1538 lines.into_bytes()
1539 };
1540 Ok([
1541 Some(half(DEV_ENVIRONMENT_RELEASE, &release)?),
1542 Some(half(DEV_ENVIRONMENT_REQUEST, &request)?),
1543 image,
1544 Some(script),
1545 ])
1546}
1547
1548pub const SECURITY_SPANS: [(&[u8], &[u8]); 4] = [
1563 (
1564 b"<!--RK_SECURITY_CONTACT_BEGIN-->",
1565 b"<!--RK_SECURITY_CONTACT_END-->",
1566 ),
1567 (
1568 b"<!--RK_SECURITY_RESPONSE_BEGIN-->",
1569 b"<!--RK_SECURITY_RESPONSE_END-->",
1570 ),
1571 (
1572 b"<!--RK_SECURITY_DEADLINE_BEGIN-->",
1573 b"<!--RK_SECURITY_DEADLINE_END-->",
1574 ),
1575 (
1576 b"<!--RK_SECURITY_SCOPE_BEGIN-->",
1577 b"<!--RK_SECURITY_SCOPE_END-->",
1578 ),
1579];
1580
1581fn acknowledgment(response: &str) -> String {
1584 format!("Maintainers acknowledge a report within {response}.")
1585}
1586
1587const DISCLOSURE_ONLY: &[u8] = b"This policy commits to no disclosure deadline.";
1591
1592fn security_replacements(params: &Params) -> [Option<Vec<u8>>; 4] {
1595 let contact = (!params.security_contact().is_empty())
1596 .then(|| params.security_contact().as_bytes().to_vec());
1597 let promised = params.security_response() != crate::config::RESPONSE_DEFAULT;
1598 [
1599 contact,
1600 promised.then(|| acknowledgment(params.security_response()).into_bytes()),
1601 promised.then(|| DISCLOSURE_ONLY.to_vec()),
1602 (!params.security_scope().is_empty()).then(|| {
1605 ["\n".repeat(2).as_str(), params.security_scope()]
1606 .concat()
1607 .into_bytes()
1608 }),
1609 ]
1610}
1611
1612fn replace_span(baseline: &[u8], begin: &[u8], end: &[u8], value: Option<&[u8]>) -> Vec<u8> {
1618 let ordered = find(baseline, begin)
1619 .zip(find(baseline, end))
1620 .filter(|(start, stop)| stop > start);
1621 let Some((start, stop)) = ordered else {
1622 return baseline.to_vec();
1623 };
1624 let mut out = Vec::with_capacity(baseline.len());
1625 out.extend_from_slice(&baseline[..start]);
1626 out.extend_from_slice(value.unwrap_or_else(|| &baseline[start + begin.len()..stop]));
1627 out.extend_from_slice(&baseline[stop + end.len()..]);
1628 out
1629}
1630
1631#[must_use]
1649pub fn render(baseline: &[u8], params: &Params) -> Vec<u8> {
1650 let mut out = substitute_tokens(baseline, params);
1651 if let Ok(values) = release_gate_replacements(params) {
1657 for ((begin, end), value) in release_gate_spans(params.driver()).iter().zip(values) {
1658 out = replace_span(&out, begin, end, value.as_deref());
1659 }
1660 }
1661 let environment = dev_environment_replacements(params).unwrap_or_default();
1664 for ((begin, end), value) in DEV_ENVIRONMENT_SPANS.iter().zip(environment) {
1665 out = replace_span(&out, begin, end, value.as_deref());
1666 }
1667 for ((begin, end), value) in SECURITY_SPANS.iter().zip(security_replacements(params)) {
1668 out = replace_span(&out, begin, end, value.as_deref());
1669 }
1670 out
1671}
1672
1673#[must_use]
1678fn substitute_tokens(baseline: &[u8], params: &Params) -> Vec<u8> {
1679 let repo = params.repo();
1680 let owner = repo.split('/').next().unwrap_or(repo);
1681 let release = params.release_mode() != ReleaseMode::None;
1685 let mut out = release_lines(baseline, release);
1686 out = registry_lines(&out, params);
1687 let (scoped, open, close): (&[u8], &[u8], &[u8]) = if release {
1688 (b"scoped ", b"", b"")
1689 } else {
1690 (b"", b"(", b")?")
1691 };
1692 out = substitute(&out, SCOPED_TOKEN, scoped);
1693 out = substitute(&out, SCOPE_OPEN_TOKEN, open);
1694 out = substitute(&out, SCOPE_CLOSE_TOKEN, close);
1695 out = substitute(&out, OWNER_TOKEN, owner.as_bytes());
1696 if let Some(style) = params.style() {
1697 out = substitute(&out, STYLE_TOKEN, style.as_str().as_bytes());
1698 }
1699 out = substitute(&out, SCOPE_SHAPE_TOKEN, SCOPE_SHAPE.as_bytes());
1700 let (fragment, flag, squash): (&str, &[u8], &[u8]) = match params.merge_form() {
1704 crate::landing::MergeForm::Squash => (GITLAB_TITLE_FRAGMENT, b"--squash", b"true"),
1705 crate::landing::MergeForm::Rebase => (GITLAB_COMMIT_FRAGMENT, b"--rebase", b"false"),
1706 };
1707 out = substitute(&out, GITLAB_GATE_FRAGMENT_TOKEN, fragment.as_bytes());
1708 out = substitute(&out, MERGE_FLAG_TOKEN, flag);
1709 out = substitute(&out, SQUASH_ON_MERGE_TOKEN, squash);
1710 let (shape, job) = release_driver_shape(params.driver()).unwrap_or_default();
1715 out = substitute(&out, BRANCH_SHAPE_TOKEN, shape.as_bytes());
1716 out = substitute(&out, REQUEST_JOB_TOKEN, job.as_bytes());
1717 out = substitute(&out, TRUNK_BRANCH_TOKEN, params.trunk().as_bytes());
1718 let escaped = params.line_prefix().replace('/', "\\/");
1719 out = substitute(&out, LINE_PREFIX_RE_TOKEN, escaped.as_bytes());
1720 out = substitute(&out, LINE_PREFIX_TOKEN, params.line_prefix().as_bytes());
1721 let required_check = serde_json::Value::String(params.required_check().to_owned()).to_string();
1725 let required_workflow =
1726 serde_json::Value::String(params.required_workflow().to_owned()).to_string();
1727 out = substitute(&out, REQUIRED_CHECK_TOKEN, required_check.as_bytes());
1728 out = substitute(&out, REQUIRED_WORKFLOW_TOKEN, required_workflow.as_bytes());
1729 let guard: &[u8] = if release_gates(params) {
1732 b" && github.event_name == 'push'"
1733 } else {
1734 b""
1735 };
1736 out = substitute(&out, PUSH_GUARD_TOKEN, guard);
1737 out = substitute(&out, REPO_TOKEN, repo.as_bytes());
1738 let run = params
1741 .dev_environment()
1742 .map(|answer| format!("{} ", answer.run))
1743 .unwrap_or_default();
1744 out = substitute(&out, DEV_RUN_TOKEN, run.as_bytes());
1745 out
1746}
1747
1748#[must_use]
1750pub fn substitute(baseline: &[u8], token: &[u8], value: &[u8]) -> Vec<u8> {
1751 let mut out = Vec::with_capacity(baseline.len());
1752 let mut rest = baseline;
1753 while let Some(at) = find(rest, token) {
1754 out.extend_from_slice(&rest[..at]);
1755 out.extend_from_slice(value);
1756 rest = &rest[at + token.len()..];
1757 }
1758 out.extend_from_slice(rest);
1759 out
1760}
1761
1762fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1764 haystack
1765 .windows(needle.len())
1766 .position(|window| window == needle)
1767}
1768
1769pub const AGENTS_DESTINATION: &str = "AGENTS.md";
1771
1772pub const BLOCK_BEGIN: &str = "<!-- BEGIN release-kit -->";
1774
1775pub const BLOCK_END: &str = "<!-- END release-kit -->";
1777
1778pub const GLOSSARY_DESTINATION: &str = "GLOSSARY.md";
1783
1784pub const HOOKS_DESTINATION: &str = ".pre-commit-config.yaml";
1786
1787pub const BLOCK_DESTINATIONS: [&str; 3] =
1793 [AGENTS_DESTINATION, GLOSSARY_DESTINATION, HOOKS_DESTINATION];
1794
1795pub const HOOKS_BEGIN: &str = "# BEGIN release-kit";
1797
1798pub const HOOKS_END: &str = "# END release-kit";
1800
1801pub const HOOK_TYPES_LINE: &str = "default_install_hook_types: [pre-commit, commit-msg, pre-push]";
1805
1806pub const AGENTS_BLOCK: &str = "blocks/agents-block.md.in";
1808
1809pub const GLOSSARY_BLOCK: &str = "blocks/glossary.md.in";
1811
1812pub const AGENTS_LINE_AGENT_POLICY: &str = "blocks/agents-line-agent-policy.md.in";
1814
1815pub const AGENTS_LINE_COMMIT_POLICY: &str = "blocks/agents-line-commit-policy.md.in";
1819
1820pub const AGENTS_BLOCK_WORKFLOW: &str = "blocks/agents-block-workflow.md.in";
1823
1824pub const AGENTS_LINE_AGENT_POLICY_WORKFLOW: &str =
1827 "blocks/agents-line-agent-policy-workflow.md.in";
1828
1829pub const AGENTS_LINE_COMMIT_SOURCE_SQUASH: &str = "blocks/agents-line-commit-source-squash.md.in";
1832
1833pub const AGENTS_LINE_COMMIT_SOURCE_REBASE: &str = "blocks/agents-line-commit-source-rebase.md.in";
1836
1837pub const AGENTS_LINE_COMMIT_SCOPE_REQUIRED: &str =
1840 "blocks/agents-line-commit-scope-required.md.in";
1841
1842pub const AGENTS_LINE_COMMIT_SCOPE_PREFERRED: &str =
1844 "blocks/agents-line-commit-scope-preferred.md.in";
1845
1846pub const GLOSSARY_BLOCK_WORKFLOW: &str = "blocks/glossary-workflow.md.in";
1848
1849pub const PRE_COMMIT_BLOCK: &str = "blocks/pre-commit-block.yaml.in";
1851
1852pub const PRE_COMMIT_MESSAGE_GUARDS: &str = "blocks/pre-commit-message-guards.yaml.in";
1854
1855pub const PRE_COMMIT_BRANCH_NAME_GUARD: &str = "blocks/pre-commit-branch-name-guard.yaml.in";
1857
1858pub const PRE_COMMIT_WORKTREE_GUARD: &str = "blocks/pre-commit-worktree-guard.yaml.in";
1860
1861pub const PRE_COMMIT_TRUNK_COMMIT_GUARD: &str = "blocks/pre-commit-trunk-commit-guard.yaml.in";
1863
1864pub const PRE_COMMIT_TRUNK_PUSH_GUARD: &str = "blocks/pre-commit-trunk-push-guard.yaml.in";
1866
1867pub const PRE_COMMIT_SWEEP_SKIP: &str = "blocks/pre-commit-sweep-skip.yaml.in";
1869
1870pub const PRE_COMMIT_SWEEP_NONE: &str = "blocks/pre-commit-sweep-none.yaml.in";
1872
1873pub const PRE_COMMIT_INTEGRATE_NOTE: &str = "blocks/pre-commit-integrate-note.yaml.in";
1875
1876pub const PRE_COMMIT_TAG_GUARD: &str = "blocks/pre-commit-tag-guard.yaml.in";
1878
1879pub const PRE_COMMIT_STATUS_RELEASE_FILES: &str = "blocks/pre-commit-status-release-files.yaml.in";
1885
1886pub const PRE_COMMIT_LOCAL_TRUNK_COMMIT_GUARD: &str =
1889 "blocks/pre-commit-local-trunk-commit-guard.yaml.in";
1890
1891pub const PRE_COMMIT_LOCAL_TRUNK_PUSH_GUARDS: &str =
1894 "blocks/pre-commit-local-trunk-push-guards.yaml.in";
1895
1896pub const FORCE_SCOPE_ARG: &str = ", --force-scope";
1902
1903pub fn embedded_block(path: &str) -> Result<&'static str, RkError> {
1910 let name = path.strip_prefix("blocks/").unwrap_or(path);
1911 let file = embedded::BLOCKS
1912 .get_file(name)
1913 .ok_or_else(|| anyhow::anyhow!("{path}: this binary embeds no such block"))?;
1914 std::str::from_utf8(file.contents())
1915 .map_err(|_| anyhow::anyhow!("{path}: a block is UTF-8").into())
1916}
1917
1918#[must_use]
1922pub fn authored(text: &str) -> &str {
1923 text.strip_suffix('\n').unwrap_or(text)
1924}
1925
1926pub const BRANCH_GRAMMAR: &str = r"^((build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)/[A-Za-z0-9._/-]+|([0-9]+|[A-Z][A-Z0-9]+-[0-9]+)-[A-Za-z0-9._-]+|release[-/].+)$";
1934
1935pub const SCOPE_SHAPE: &str = "[a-z0-9._/-]+";
1945
1946#[must_use]
1953pub fn scope_is_shaped(scope: &str) -> bool {
1954 !scope.is_empty()
1955 && scope.chars().all(|c| {
1956 c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '/' | '-')
1957 })
1958}
1959
1960pub struct RoutingGuards<'a> {
1962 pub agent_policy: &'a str,
1964 pub commit_policy: &'a str,
1967 pub commit_source: &'a str,
1969 pub commit_scope: &'a str,
1971}
1972
1973#[must_use]
1980pub fn compose_routing(template: &str, guards: Option<&RoutingGuards<'_>>) -> String {
1981 let fragment = |text: &str| format!("{}\n", authored(text));
1982 let (agent, commit) = guards.map_or_else(
1983 || (String::new(), String::new()),
1984 |guards| {
1985 (
1986 fragment(guards.agent_policy),
1987 fragment(
1988 &authored(guards.commit_policy)
1989 .replacen("RK_COMMIT_SOURCE", &fragment(guards.commit_source), 1)
1990 .replacen("RK_COMMIT_SCOPE", &fragment(guards.commit_scope), 1),
1991 ),
1992 )
1993 },
1994 );
1995 authored(template)
1996 .replacen("RK_AGENT_POLICY", &agent, 1)
1997 .replacen("RK_COMMIT_POLICY", &commit, 1)
1998}
1999
2000#[must_use]
2004pub fn compose_glossary(template: &str) -> String {
2005 authored(template).to_owned()
2006}
2007
2008pub struct WorkflowHooks<'a> {
2010 pub message: &'a str,
2012 pub branch_name: &'a str,
2014 pub worktree: Option<&'a str>,
2019}
2020
2021#[must_use]
2041pub fn compose_hooks(
2042 template: &str,
2043 workflow: Option<&WorkflowHooks<'_>>,
2044 parts: &TrunkGuards,
2045) -> String {
2046 let fragment = |text: &str| format!("{}\n", authored(text));
2047 let worktree = workflow
2048 .and_then(|hooks| hooks.worktree)
2049 .map_or_else(String::new, fragment);
2050 let trunk_guards = workflow.is_some();
2051 let mut skips: Vec<&str> = Vec::new();
2052 if trunk_guards {
2053 skips.push("no-commit-to-branch");
2054 }
2055 if !worktree.is_empty() {
2056 skips.push("rk-worktree-location");
2057 }
2058 let sweep = if skips.is_empty() {
2059 fragment(parts.sweep_none)
2060 } else {
2061 fragment(&authored(parts.sweep_skip).replacen("RK_SWEEP_SKIP", &skips.join(","), 1))
2062 };
2063 let (commit_guard, push_guard) = match (trunk_guards, parts.integration) {
2064 (false, _) => (String::new(), String::new()),
2065 (true, Integration::Forge) => (fragment(parts.trunk_commit), fragment(parts.trunk_push)),
2066 (true, Integration::Local) => (
2067 fragment(parts.local_trunk_commit),
2068 fragment(parts.local_trunk_push),
2069 ),
2070 };
2071 let (tag_guard, release_files) = if parts.release {
2072 (fragment(parts.tag_guard), authored(parts.release_files))
2073 } else {
2074 (String::new(), "")
2075 };
2076 let note = match parts.integration {
2077 Integration::Forge => String::new(),
2078 Integration::Local => fragment(parts.integrate_note),
2079 };
2080 let (message, branch_name) = workflow.map_or_else(
2081 || (String::new(), String::new()),
2082 |hooks| {
2083 let message = fragment(hooks.message);
2084 (
2085 if parts.release {
2086 message
2087 } else {
2088 message.replacen(FORCE_SCOPE_ARG, "", 1)
2089 },
2090 fragment(hooks.branch_name),
2091 )
2092 },
2093 );
2094 authored(template)
2095 .replacen("RK_SWEEP_NOTE", &format!("{sweep}{note}"), 1)
2096 .replacen("RK_MESSAGE_GUARDS", &message, 1)
2097 .replacen("RK_TRUNK_COMMIT_GUARD", &commit_guard, 1)
2098 .replacen("RK_BRANCH_NAME_GUARD", &branch_name, 1)
2099 .replacen("RK_WORKTREE_GUARD", &worktree, 1)
2100 .replacen("RK_TRUNK_PUSH_GUARD", &push_guard, 1)
2101 .replacen("RK_TAG_GUARD", &tag_guard, 1)
2102 .replacen("RK_STATUS_RELEASE_FILES", release_files, 1)
2103 .replacen("RK_BRANCH_GRAMMAR", BRANCH_GRAMMAR, 1)
2104}
2105
2106pub struct TrunkGuards<'a> {
2109 pub integration: Integration,
2111 pub release: bool,
2114 pub trunk_commit: &'a str,
2117 pub trunk_push: &'a str,
2120 pub local_trunk_commit: &'a str,
2123 pub local_trunk_push: &'a str,
2126 pub tag_guard: &'a str,
2128 pub release_files: &'a str,
2131 pub sweep_skip: &'a str,
2133 pub sweep_none: &'a str,
2135 pub integrate_note: &'a str,
2137}
2138
2139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2142pub struct BlockShape {
2143 pub checkout_mode: CheckoutMode,
2145 pub integration: Integration,
2147 pub merge_form: MergeForm,
2149 pub workflow_guards: bool,
2151 pub release: bool,
2153}
2154
2155impl BlockShape {
2156 #[must_use]
2158 pub fn of(params: &Params) -> Self {
2159 Self {
2160 checkout_mode: params.checkout_mode(),
2161 integration: params.integration(),
2162 merge_form: params.merge_form(),
2163 workflow_guards: params.workflow_guards(),
2164 release: params.release_mode() != ReleaseMode::None,
2165 }
2166 }
2167
2168 #[must_use]
2172 pub const fn releasing(
2173 checkout_mode: CheckoutMode,
2174 integration: Integration,
2175 workflow_guards: bool,
2176 ) -> Self {
2177 Self {
2178 checkout_mode,
2179 integration,
2180 merge_form: MergeForm::Squash,
2181 workflow_guards,
2182 release: true,
2183 }
2184 }
2185
2186 const fn routing_sources(self) -> [&'static str; 4] {
2189 let (template, agent) = if self.release {
2190 (AGENTS_BLOCK, AGENTS_LINE_AGENT_POLICY)
2191 } else {
2192 (AGENTS_BLOCK_WORKFLOW, AGENTS_LINE_AGENT_POLICY_WORKFLOW)
2193 };
2194 let source = match self.merge_form {
2195 MergeForm::Squash => AGENTS_LINE_COMMIT_SOURCE_SQUASH,
2196 MergeForm::Rebase => AGENTS_LINE_COMMIT_SOURCE_REBASE,
2197 };
2198 let scope = if self.release {
2199 AGENTS_LINE_COMMIT_SCOPE_REQUIRED
2200 } else {
2201 AGENTS_LINE_COMMIT_SCOPE_PREFERRED
2202 };
2203 [template, agent, source, scope]
2204 }
2205
2206 const fn glossary_source(self) -> &'static str {
2208 if self.release {
2209 GLOSSARY_BLOCK
2210 } else {
2211 GLOSSARY_BLOCK_WORKFLOW
2212 }
2213 }
2214}
2215
2216pub fn routing_block(workflow_guards: bool) -> Result<String, RkError> {
2223 routing_block_of(&BlockShape::releasing(
2224 CheckoutMode::LinkedWorktree,
2225 Integration::Local,
2226 workflow_guards,
2227 ))
2228}
2229
2230pub fn routing_block_of(shape: &BlockShape) -> Result<String, RkError> {
2240 let [template, agent, source, scope] = shape.routing_sources();
2241 let guards = if shape.workflow_guards {
2242 Some(RoutingGuards {
2243 agent_policy: embedded_block(agent)?,
2244 commit_policy: embedded_block(AGENTS_LINE_COMMIT_POLICY)?,
2245 commit_source: embedded_block(source)?,
2246 commit_scope: embedded_block(scope)?,
2247 })
2248 } else {
2249 None
2250 };
2251 Ok(compose_routing(embedded_block(template)?, guards.as_ref()))
2252}
2253
2254pub fn glossary_block() -> Result<String, RkError> {
2261 Ok(compose_glossary(embedded_block(GLOSSARY_BLOCK)?))
2262}
2263
2264pub fn glossary_block_of(shape: &BlockShape) -> Result<String, RkError> {
2271 Ok(compose_glossary(embedded_block(shape.glossary_source())?))
2272}
2273
2274pub fn hooks_block(
2282 mode: CheckoutMode,
2283 integration: Integration,
2284 workflow_guards: bool,
2285) -> Result<String, RkError> {
2286 hooks_block_of(&BlockShape::releasing(mode, integration, workflow_guards))
2287}
2288
2289pub fn hooks_block_of(shape: &BlockShape) -> Result<String, RkError> {
2295 let workflow = if shape.workflow_guards {
2296 Some(WorkflowHooks {
2297 message: embedded_block(PRE_COMMIT_MESSAGE_GUARDS)?,
2298 branch_name: embedded_block(PRE_COMMIT_BRANCH_NAME_GUARD)?,
2299 worktree: match shape.checkout_mode {
2300 CheckoutMode::LinkedWorktree => Some(embedded_block(PRE_COMMIT_WORKTREE_GUARD)?),
2301 CheckoutMode::MainWorktree => None,
2302 },
2303 })
2304 } else {
2305 None
2306 };
2307 let parts = TrunkGuards {
2308 integration: shape.integration,
2309 release: shape.release,
2310 trunk_commit: embedded_block(PRE_COMMIT_TRUNK_COMMIT_GUARD)?,
2311 trunk_push: embedded_block(PRE_COMMIT_TRUNK_PUSH_GUARD)?,
2312 local_trunk_commit: embedded_block(PRE_COMMIT_LOCAL_TRUNK_COMMIT_GUARD)?,
2313 local_trunk_push: embedded_block(PRE_COMMIT_LOCAL_TRUNK_PUSH_GUARDS)?,
2314 tag_guard: embedded_block(PRE_COMMIT_TAG_GUARD)?,
2315 release_files: embedded_block(PRE_COMMIT_STATUS_RELEASE_FILES)?,
2316 sweep_skip: embedded_block(PRE_COMMIT_SWEEP_SKIP)?,
2317 sweep_none: embedded_block(PRE_COMMIT_SWEEP_NONE)?,
2318 integrate_note: embedded_block(PRE_COMMIT_INTEGRATE_NOTE)?,
2319 };
2320 Ok(compose_hooks(
2321 embedded_block(PRE_COMMIT_BLOCK)?,
2322 workflow.as_ref(),
2323 &parts,
2324 ))
2325}
2326
2327type BlockTemplate = (String, Vec<String>, &'static str);
2330
2331fn block_template(destination: &str, params: &Params) -> Result<Option<BlockTemplate>, RkError> {
2334 let shape = BlockShape::of(params);
2335 let guards = shape.workflow_guards;
2336 match destination {
2337 AGENTS_DESTINATION => {
2338 let [template, agent, source, scope] = shape.routing_sources();
2339 let mut sources = vec![template.to_owned()];
2340 if guards {
2341 sources.push(agent.to_owned());
2342 sources.push(AGENTS_LINE_COMMIT_POLICY.to_owned());
2343 sources.push(source.to_owned());
2344 sources.push(scope.to_owned());
2345 }
2346 Ok(Some((routing_block_of(&shape)?, sources, catalog::GUARDS)))
2347 }
2348 GLOSSARY_DESTINATION => Ok(guards
2349 .then(|| -> Result<_, RkError> {
2350 Ok((
2351 glossary_block_of(&shape)?,
2352 vec![shape.glossary_source().to_owned()],
2353 catalog::WORKFLOW_GUARDS,
2354 ))
2355 })
2356 .transpose()?),
2357 HOOKS_DESTINATION => {
2358 let mut sources = vec![PRE_COMMIT_BLOCK.to_owned()];
2359 if guards {
2360 sources.push(PRE_COMMIT_MESSAGE_GUARDS.to_owned());
2361 sources.push(PRE_COMMIT_BRANCH_NAME_GUARD.to_owned());
2362 if shape.checkout_mode == CheckoutMode::LinkedWorktree {
2363 sources.push(PRE_COMMIT_WORKTREE_GUARD.to_owned());
2364 }
2365 match shape.integration {
2366 Integration::Forge => {
2367 sources.push(PRE_COMMIT_TRUNK_COMMIT_GUARD.to_owned());
2368 sources.push(PRE_COMMIT_TRUNK_PUSH_GUARD.to_owned());
2369 }
2370 Integration::Local => {
2371 sources.push(PRE_COMMIT_LOCAL_TRUNK_COMMIT_GUARD.to_owned());
2372 sources.push(PRE_COMMIT_LOCAL_TRUNK_PUSH_GUARDS.to_owned());
2373 }
2374 }
2375 }
2376 if shape.release {
2377 sources.push(PRE_COMMIT_TAG_GUARD.to_owned());
2378 sources.push(PRE_COMMIT_STATUS_RELEASE_FILES.to_owned());
2379 }
2380 sources.push(if guards {
2381 PRE_COMMIT_SWEEP_SKIP.to_owned()
2382 } else {
2383 PRE_COMMIT_SWEEP_NONE.to_owned()
2384 });
2385 if shape.integration == Integration::Local {
2386 sources.push(PRE_COMMIT_INTEGRATE_NOTE.to_owned());
2387 }
2388 Ok(Some((hooks_block_of(&shape)?, sources, catalog::GUARDS)))
2389 }
2390 other => Err(anyhow::anyhow!("{other} is not a block destination").into()),
2391 }
2392}
2393
2394#[must_use]
2396pub fn block_markers(destination: &str) -> Option<(&'static str, &'static str)> {
2397 match destination {
2398 AGENTS_DESTINATION | GLOSSARY_DESTINATION => Some((BLOCK_BEGIN, BLOCK_END)),
2399 HOOKS_DESTINATION => Some((HOOKS_BEGIN, HOOKS_END)),
2400 _ => None,
2401 }
2402}
2403
2404#[must_use]
2407pub fn extract_block<'a>(text: &'a str, begin: &str, end: &str) -> Option<&'a str> {
2408 let start = text.find(begin)?;
2409 let stop = text[start..].find(end)? + start + end.len();
2410 Some(&text[start..stop])
2411}
2412
2413#[must_use]
2420pub fn splice_marked_block(existing: Option<&[u8]>, block: &str) -> Vec<u8> {
2421 let block = block.as_bytes();
2422 let Some(text) = existing else {
2423 return [block, b"\n"].concat();
2424 };
2425 if let Some(start) = find(text, BLOCK_BEGIN.as_bytes())
2429 && let Some(offset) = find(&text[start..], BLOCK_END.as_bytes())
2430 {
2431 let stop = start + offset + BLOCK_END.len();
2432 return [&text[..start], block, &text[stop..]].concat();
2433 }
2434 let mut out = Vec::with_capacity(text.len() + block.len() + 3);
2438 out.extend_from_slice(text);
2439 if !text.ends_with(b"\n") {
2440 out.push(b'\n');
2441 }
2442 out.push(b'\n');
2443 out.extend_from_slice(block);
2444 out.push(b'\n');
2445 out
2446}
2447
2448pub fn splice_hooks_block(existing: Option<&str>, block: &str) -> Result<String, String> {
2461 let Some(text) = existing else {
2462 return Ok(format!("{HOOK_TYPES_LINE}\n\nrepos:\n{block}\n"));
2463 };
2464 if let Some(defect) = hooks_marker_defect(text) {
2465 return Err(defect);
2466 }
2467 if let Some(found) = extract_block(text, HOOKS_BEGIN, HOOKS_END) {
2468 return Ok(text.replacen(found, block, 1));
2469 }
2470 let mut out = String::with_capacity(text.len() + block.len() + 1);
2471 let mut placed = false;
2472 for line in text.split_inclusive('\n') {
2473 out.push_str(line);
2474 if !placed && line.trim_end() == "repos:" {
2475 if !out.ends_with('\n') {
2476 out.push('\n');
2477 }
2478 out.push_str(block);
2479 out.push('\n');
2480 placed = true;
2481 }
2482 }
2483 if placed {
2484 Ok(out)
2485 } else {
2486 Err(format!(
2487 "{HOOKS_DESTINATION} exists with no repos: line, so the hook block has nowhere to land"
2488 ))
2489 }
2490}
2491
2492#[must_use]
2502pub fn marker_defect(destination: &str, text: &str) -> Option<String> {
2503 let (begin, end) = block_markers(destination)?;
2504 let begins = text.matches(begin).count();
2505 let ends = text.matches(end).count();
2506 if begins > 1 || ends > 1 {
2507 return Some(format!(
2508 "{destination} carries more than one release-kit marker pair; release-kit owns exactly one block"
2509 ));
2510 }
2511 match (text.find(begin), text.find(end)) {
2512 (Some(begin), Some(end)) if end > begin => None,
2513 (None, None) => None,
2514 _ => Some(format!(
2515 "{destination} carries an unmatched or misordered release-kit marker, so the block's extent is ambiguous"
2516 )),
2517 }
2518}
2519
2520#[must_use]
2523pub fn hooks_marker_defect(text: &str) -> Option<String> {
2524 marker_defect(HOOKS_DESTINATION, text)
2525}
2526
2527fn propose_document(
2531 destination: &str,
2532 existing: Option<&[u8]>,
2533 region: &[u8],
2534) -> Result<Vec<u8>, String> {
2535 let block = String::from_utf8_lossy(region).into_owned();
2540 if let Some(text) = existing
2541 && let Some(defect) = marker_defect(destination, &String::from_utf8_lossy(text))
2542 {
2543 return Err(defect);
2544 }
2545 if destination == HOOKS_DESTINATION {
2546 let text = match existing {
2550 None => None,
2551 Some(bytes) => Some(std::str::from_utf8(bytes).map_err(|_| {
2552 format!(
2553 "{destination} is not UTF-8, so the hook block has nowhere to land without rewriting the target's bytes"
2554 )
2555 })?),
2556 };
2557 return splice_hooks_block(text, &block).map(String::into_bytes);
2558 }
2559 Ok(splice_marked_block(existing, &block))
2560}
2561
2562#[must_use]
2574pub fn nix_unsupported_shape(shape: &CrateShape) -> Option<String> {
2575 let Some(text) = shape.cargo_toml.as_deref() else {
2576 return Some(
2577 "the target has no readable Cargo.toml, which the seeded package expression reads; no Nix file lands".to_owned(),
2578 );
2579 };
2580 let Ok(table) = text.parse::<toml::Table>() else {
2581 return Some(
2582 "the target's Cargo.toml does not parse, and the seeded package expression reads it; no Nix file lands".to_owned(),
2583 );
2584 };
2585 if !table.contains_key("package") {
2586 return Some(
2587 "the target's Cargo.toml has no [package] table; the seed supports a single crate, so no Nix file lands".to_owned(),
2588 );
2589 }
2590 if !shape.cargo_lock {
2591 return Some(
2592 "the target has no Cargo.lock, which the seeded package expression builds from; commit one, then opt in".to_owned(),
2593 );
2594 }
2595 let implicit_bin = shape.main_rs
2596 && table
2597 .get("package")
2598 .and_then(toml::Value::as_table)
2599 .and_then(|package| package.get("autobins"))
2600 .and_then(toml::Value::as_bool)
2601 != Some(false);
2602 let explicit_bins = table.get("bin").and_then(toml::Value::as_array);
2603 if explicit_bins.is_none() && !implicit_bin {
2604 return Some(
2605 "the target declares no binary — no effective src/main.rs and no [[bin]] entry — and the seed flake's smoke check runs one; no Nix file lands".to_owned(),
2606 );
2607 }
2608 if let Some(bins) = explicit_bins {
2614 let required = bins
2615 .first()
2616 .and_then(toml::Value::as_table)
2617 .and_then(|bin| bin.get("required-features"))
2618 .and_then(toml::Value::as_array);
2619 if let Some(required) = required {
2620 let enabled = default_features(&table);
2621 let missing = required
2622 .iter()
2623 .filter_map(toml::Value::as_str)
2624 .any(|feature| !enabled.contains(feature));
2625 if missing {
2626 return Some(
2627 "the target's first [[bin]] entry requires features a default build does not enable; no Nix file lands".to_owned(),
2628 );
2629 }
2630 }
2631 }
2632 None
2633}
2634
2635fn dep_edge_suppresses(features: &toml::Table, name: &str) -> bool {
2638 let edge = format!("dep:{name}");
2639 features.values().any(|list| {
2640 list.as_array().is_some_and(|entries| {
2641 entries
2642 .iter()
2643 .filter_map(toml::Value::as_str)
2644 .any(|entry| entry == edge)
2645 })
2646 })
2647}
2648
2649fn is_optional_dependency(table: &toml::Table, name: &str) -> bool {
2652 ["dependencies", "build-dependencies"]
2653 .iter()
2654 .any(|section| {
2655 table
2656 .get(*section)
2657 .and_then(toml::Value::as_table)
2658 .and_then(|dependencies| dependencies.get(name))
2659 .and_then(toml::Value::as_table)
2660 .and_then(|dependency| dependency.get("optional"))
2661 .and_then(toml::Value::as_bool)
2662 == Some(true)
2663 })
2664}
2665
2666fn default_features(table: &toml::Table) -> std::collections::BTreeSet<String> {
2673 let Some(features) = table.get("features").and_then(toml::Value::as_table) else {
2674 return std::collections::BTreeSet::new();
2675 };
2676 let mut enabled = std::collections::BTreeSet::new();
2677 let mut queue = vec!["default".to_owned()];
2678 while let Some(name) = queue.pop() {
2679 if !enabled.insert(name.clone()) {
2680 continue;
2681 }
2682 if let Some(implies) = features.get(&name).and_then(toml::Value::as_array) {
2683 for implied in implies.iter().filter_map(toml::Value::as_str) {
2684 if implied.starts_with("dep:") || implied.contains("?/") {
2685 continue;
2689 }
2690 if let Some((package, _)) = implied.split_once('/') {
2691 let feature_exists =
2699 features.contains_key(package) || !dep_edge_suppresses(features, package);
2700 if is_optional_dependency(table, package) && feature_exists {
2701 queue.push(package.to_owned());
2702 }
2703 } else {
2704 queue.push(implied.to_owned());
2705 }
2706 }
2707 }
2708 }
2709 enabled
2710}
2711
2712#[must_use]
2720pub fn flake_pair_withheld(
2721 flake_recorded: bool,
2722 flake_nix_present: bool,
2723 flake_lock_present: bool,
2724) -> Option<String> {
2725 if flake_recorded {
2726 return None;
2727 }
2728 let present: Vec<&str> = [
2729 ("flake.nix", flake_nix_present),
2730 ("flake.lock", flake_lock_present),
2731 ]
2732 .into_iter()
2733 .filter_map(|(name, present)| present.then_some(name))
2734 .collect();
2735 if present.is_empty() {
2736 return None;
2737 }
2738 Some(format!(
2739 "the target already carries {}; its flake pair stays its own",
2740 present.join(" and ")
2741 ))
2742}
2743
2744#[must_use]
2754pub fn nix_withholding(
2755 nix: bool,
2756 evidence: &TargetEvidence,
2757) -> Option<(&'static [&'static str], String)> {
2758 if !nix {
2759 return None;
2760 }
2761 if let Some(reason) = nix_unsupported_shape(&evidence.crate_shape) {
2762 return Some((&NIX_DESTINATIONS[..], reason));
2763 }
2764 flake_pair_withheld(
2765 evidence.flake_recorded,
2766 evidence.flake_nix_present,
2767 evidence.flake_lock_present,
2768 )
2769 .map(|reason| (&NIX_WITHHOLDABLE[..], reason))
2770}
2771
2772#[cfg(test)]
2773mod tests {
2774 use super::{
2775 AGENTS_DESTINATION, BLOCK_BEGIN, BLOCK_DESTINATIONS, BLOCK_END, Candidate, Collision,
2776 CrateShape, GLOSSARY_DESTINATION, HOOK_TYPES_LINE, HOOKS_BEGIN, HOOKS_DESTINATION,
2777 HOOKS_END, Placement, Projection, ProjectionInput, TargetEvidence, extract_block,
2778 };
2779 use crate::landing::{Params, Style};
2780
2781 fn supported_shape() -> CrateShape {
2783 CrateShape {
2784 cargo_toml: Some("[package]\nname = \"widget\"\nversion = \"0.1.0\"\n".to_owned()),
2785 cargo_lock: true,
2786 main_rs: true,
2787 }
2788 }
2789
2790 fn input(evidence: TargetEvidence) -> ProjectionInput {
2791 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2792 params.set_nix_for_test(true);
2793 ProjectionInput { params, evidence }
2794 }
2795
2796 fn compute(evidence: TargetEvidence) -> Projection {
2797 Projection::compute(&input(evidence)).expect("the embedded pair projects")
2798 }
2799
2800 fn candidate<'a>(projection: &'a Projection, destination: &str) -> &'a Candidate {
2801 projection
2802 .candidates
2803 .iter()
2804 .find(|candidate| candidate.destination == destination)
2805 .expect("the destination projects")
2806 }
2807
2808 #[test]
2813 fn the_workflow_guards_land_only_where_requested() {
2814 let mut plain = input(TargetEvidence {
2815 crate_shape: supported_shape(),
2816 ..TargetEvidence::default()
2817 });
2818 plain.params.set_workflow_guards_for_test(false);
2819 let plain = Projection::compute(&plain).expect("the embedded pair projects");
2820 assert!(
2821 !plain
2822 .candidates
2823 .iter()
2824 .any(|candidate| candidate.destination == GLOSSARY_DESTINATION),
2825 "a target without the guards takes no glossary"
2826 );
2827 let agents =
2828 String::from_utf8(candidate(&plain, AGENTS_DESTINATION).bytes.clone()).expect("text");
2829 assert!(!agents.contains("guides and never drives"), "{agents}");
2830 let hooks =
2831 String::from_utf8(candidate(&plain, HOOKS_DESTINATION).bytes.clone()).expect("text");
2832 assert!(!hooks.contains("conventional-pre-commit"), "{hooks}");
2833 assert!(hooks.contains("rk-no-hand-authored-tag"), "{hooks}");
2834
2835 let guarded = compute(TargetEvidence {
2836 crate_shape: supported_shape(),
2837 ..TargetEvidence::default()
2838 });
2839 let glossary = candidate(&guarded, GLOSSARY_DESTINATION);
2840 assert_eq!(
2841 glossary.capability,
2842 crate::profile::catalog::WORKFLOW_GUARDS
2843 );
2844 assert_eq!(
2845 candidate(&guarded, AGENTS_DESTINATION).capability,
2846 crate::profile::catalog::GUARDS
2847 );
2848 let hooks =
2849 String::from_utf8(candidate(&guarded, HOOKS_DESTINATION).bytes.clone()).expect("text");
2850 for hook in ["conventional-pre-commit", "rk-message", "rk-branch-name"] {
2851 assert!(hooks.contains(hook), "{hook}: {hooks}");
2852 }
2853 }
2854
2855 fn outside(bytes: &[u8], begin: &str, end: &str) -> (Vec<u8>, Vec<u8>) {
2857 let text = String::from_utf8_lossy(bytes);
2858 let start = text.find(begin).expect("the begin marker is present");
2859 let stop = text[start..].find(end).expect("the end marker is present") + start + end.len();
2860 (bytes[..start].to_vec(), bytes[stop..].to_vec())
2861 }
2862
2863 #[test]
2864 fn equal_projection_inputs_yield_byte_identical_projections() {
2865 let mut documents = std::collections::BTreeMap::new();
2866 documents.insert(
2867 AGENTS_DESTINATION.to_owned(),
2868 b"# Widget\n\nOwn rules.\n".to_vec(),
2869 );
2870 let evidence = TargetEvidence {
2871 documents,
2872 crate_shape: supported_shape(),
2873 ..TargetEvidence::default()
2874 };
2875 let first = input(evidence.clone());
2876 let second = input(evidence);
2877 assert_eq!(first, second, "the inputs are values and compare equal");
2878 let a = Projection::compute(&first).expect("the pair projects");
2879 let b = Projection::compute(&second).expect("the pair projects");
2880 assert_eq!(a.candidates.len(), b.candidates.len());
2881 for (x, y) in a.candidates.iter().zip(&b.candidates) {
2882 assert_eq!(x.destination, y.destination);
2883 assert_eq!(x.kind, y.kind);
2884 assert_eq!(x.placement, y.placement);
2885 assert_eq!(x.bytes, y.bytes, "{}", x.destination);
2886 assert_eq!(x.region, y.region, "{}", x.destination);
2887 assert_eq!(x.sources, y.sources, "{}", x.destination);
2888 }
2889 assert_eq!(a, b);
2890 let destinations: Vec<&str> = a
2891 .candidates
2892 .iter()
2893 .map(|candidate| candidate.destination.as_str())
2894 .collect();
2895 let mut sorted = destinations.clone();
2896 sorted.sort_unstable();
2897 assert_eq!(destinations, sorted, "candidates sort by destination");
2898 assert!(a.omissions.is_empty(), "{:?}", a.omissions);
2899 assert!(a.collisions.is_empty(), "{:?}", a.collisions);
2900 }
2901
2902 #[test]
2906 fn the_scorecard_destination_projects_only_under_the_opt_in() {
2907 use super::{Kind, SCORECARD_DESTINATIONS, kind_of};
2908 let destination = SCORECARD_DESTINATIONS[0];
2909 assert_eq!(kind_of(destination), Some(Kind::Rendered));
2910
2911 let project = |scorecard: bool| {
2912 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2913 params.set_scorecard_for_test(scorecard);
2914 Projection::compute(&ProjectionInput {
2915 params,
2916 evidence: TargetEvidence::default(),
2917 })
2918 .expect("the embedded pair projects")
2919 };
2920
2921 let off = project(false);
2922 assert!(
2923 !off.candidates
2924 .iter()
2925 .any(|candidate| candidate.destination == destination),
2926 "off by default, and an absent candidate is no omission"
2927 );
2928 assert!(off.omissions.is_empty(), "{:?}", off.omissions);
2929
2930 let on = project(true);
2931 let candidate = candidate(&on, destination);
2932 assert_eq!(candidate.kind, Kind::Rendered);
2933 assert_eq!(candidate.placement, Placement::Whole);
2934 let text = String::from_utf8_lossy(&candidate.bytes);
2935 assert!(!text.contains("RK_"), "a token survived: {text}");
2936 }
2937
2938 #[test]
2943 fn the_licence_judgment_reads_what_every_reader_obtains() {
2944 use super::licence_states_an_open_source_codebase as approved;
2945 for expression in [
2946 "MIT",
2947 "Apache-2.0",
2948 "MIT OR Apache-2.0",
2949 "MIT AND Apache-2.0",
2950 "(MIT OR Apache-2.0) AND ISC",
2951 "Apache-2.0 WITH LLVM-exception OR MIT",
2952 "GPL-3.0+",
2953 ] {
2954 assert!(approved(expression), "{expression} is OSI-approved");
2955 }
2956 for expression in [
2961 "MIT AND CC-BY-4.0",
2962 "CC-BY-4.0 AND MIT",
2963 "MIT AND (CC-BY-4.0 OR CC-BY-SA-4.0)",
2964 "(MIT OR CC-BY-4.0) AND MIT",
2965 "MIT OR Apache-2.0 AND CC-BY-4.0",
2966 "Apache-2.0 WITH LLVM-exception AND CC-BY-SA-3.0",
2967 ] {
2968 assert!(approved(expression), "{expression} states open source");
2969 }
2970 for expression in [
2971 "",
2972 " ",
2973 "LicenseRef-proprietary",
2974 "MIT AND LicenseRef-proprietary",
2975 "SEE LICENSE IN COPYING",
2976 "CC-BY-4.0",
2977 "DocumentRef-spdx:LicenseRef-proprietary",
2978 ] {
2979 assert!(!approved(expression), "{expression} is not recognized");
2980 }
2981 for expression in [
2986 "MIT OR CC-BY-4.0",
2987 "CC-BY-4.0 AND CC-BY-SA-4.0",
2988 "CC-BY-4.0 AND LicenseRef-proprietary",
2989 "CC0-1.0",
2990 "MIT AND CC-BY-4.0 AND LicenseRef-proprietary",
2991 ] {
2992 assert!(!approved(expression), "{expression} grants no code terms");
2993 }
2994 assert!(
2999 !approved("CC-BY-4.0 OR CC-BY-SA-4.0 AND MIT"),
3000 "AND binds tighter than OR"
3001 );
3002 }
3003
3004 #[test]
3010 fn the_licence_judgment_holds_the_expression_to_the_spdx_grammar() {
3011 use super::licence_states_an_open_source_codebase as approved;
3012 for expression in [
3017 "MIT OR",
3018 "OR MIT",
3019 "MIT AND",
3020 "MIT WITH",
3021 "WITH LLVM-exception",
3022 "(MIT",
3023 "MIT)",
3024 "MIT Apache-2.0",
3025 "()",
3026 "(MIT OR Apache-2.0",
3027 "MIT OR (Apache-2.0",
3028 "MIT OR ()",
3029 "AND",
3030 "(",
3031 ")",
3032 "MIT WITH AND ISC",
3033 "MIT OR OR ISC",
3034 "MIT @ Apache-2.0",
3035 ] {
3036 assert!(!approved(expression), "{expression} is malformed");
3037 }
3038 for expression in [
3040 "MIT AND (Apache-2.0 OR ISC)",
3041 "((MIT))",
3042 "Apache-2.0 WITH LLVM-exception AND ISC",
3043 "(Apache-2.0 WITH LLVM-exception)",
3044 ] {
3045 assert!(approved(expression), "{expression} is well formed");
3046 }
3047 for expression in [
3052 "mit",
3053 "MiT",
3054 "apache-2.0 OR mit",
3055 "APACHE-2.0 WITH llvm-exception",
3056 ] {
3057 assert!(
3058 approved(expression),
3059 "{expression} names an approved licence"
3060 );
3061 }
3062 for expression in [
3066 "MIT or Apache-2.0",
3067 "MIT and Apache-2.0",
3068 "MIT with LLVM-exception",
3069 ] {
3070 assert!(!approved(expression), "{expression} carries no operator");
3071 }
3072 for expression in [
3076 "MIT WITH definitely-not-an-spdx-exception",
3077 "MIT WITH MIT",
3078 "MIT WITH Apache-2.0",
3079 ] {
3080 assert!(!approved(expression), "{expression} names no exception");
3081 }
3082 for expression in [
3086 "GPL-2.0-only WITH GCC-exception-2.0",
3087 "GPL-2.0-or-later WITH Classpath-exception-2.0",
3088 "Apache-2.0 WITH Swift-exception",
3089 "GPL-3.0-only WITH Autoconf-exception-generic",
3090 ] {
3091 assert!(approved(expression), "{expression} names a real exception");
3092 }
3093 }
3094
3095 #[test]
3101 fn a_recorded_provider_its_pair_cannot_run_is_named() {
3102 use super::{Provider, code_scanning_incompatibility};
3103
3104 assert!(code_scanning_incompatibility(None, Some("bash"), Some("gitlab")).is_none());
3105 assert!(
3106 code_scanning_incompatibility(Some(Provider::Semgrep), Some("rust"), Some("gitlab"))
3107 .is_none()
3108 );
3109 assert!(
3110 code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("github"))
3111 .is_none()
3112 );
3113
3114 let bash =
3115 code_scanning_incompatibility(Some(Provider::Semgrep), Some("bash"), Some("github"))
3116 .expect("a binding with no scanner is named");
3117 assert!(bash.contains("bash binding"), "{bash}");
3118 let gitlab =
3119 code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("gitlab"))
3120 .expect("codeql on gitlab is named");
3121 assert!(gitlab.contains("codeql"), "{gitlab}");
3122 let release_less =
3123 code_scanning_incompatibility(Some(Provider::Semgrep), None, Some("github"))
3124 .expect("no driver is named");
3125 assert!(
3126 release_less.contains("no automatic release driver"),
3127 "{release_less}"
3128 );
3129
3130 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
3133 params.set_code_scanning_for_test(Some(Provider::Semgrep));
3134 let clean = Projection::compute(&ProjectionInput {
3135 params: params.clone(),
3136 evidence: TargetEvidence::default(),
3137 })
3138 .expect("the pair projects");
3139 assert!(
3140 clean.record_defects.is_empty(),
3141 "{:?}",
3142 clean.record_defects
3143 );
3144 }
3145
3146 #[test]
3150 fn the_code_scanning_destinations_follow_the_recorded_provider() {
3151 use super::{
3152 CODE_SCANNING_DESTINATIONS, Kind, Provider, code_scanning_licence_refusal, kind_of,
3153 };
3154 for (destination, _) in CODE_SCANNING_DESTINATIONS {
3155 assert_eq!(kind_of(destination), Some(Kind::Rendered), "{destination}");
3156 }
3157
3158 let project = |provider: Option<Provider>| {
3159 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
3160 params.set_code_scanning_for_test(provider);
3161 Projection::compute(&ProjectionInput {
3162 params,
3163 evidence: TargetEvidence {
3164 crate_shape: CrateShape {
3165 cargo_toml: Some(
3166 "[package]\nname = \"widget\"\nlicense = \"MIT\"\n".to_owned(),
3167 ),
3168 ..CrateShape::default()
3169 },
3170 ..TargetEvidence::default()
3171 },
3172 })
3173 .expect("the embedded pair projects")
3174 };
3175 let landed = |projection: &Projection, destination: &str| {
3176 projection
3177 .candidates
3178 .iter()
3179 .any(|candidate| candidate.destination == destination)
3180 };
3181
3182 let off = project(None);
3183 for (destination, _) in CODE_SCANNING_DESTINATIONS {
3184 assert!(!landed(&off, destination), "{destination}");
3185 }
3186 assert!(off.licence_refusal.is_none());
3187
3188 let codeql = project(Some(Provider::CodeQl));
3189 assert!(landed(
3190 &codeql,
3191 ".github/workflows/code-scanning-codeql.yml"
3192 ));
3193 assert!(!landed(
3194 &codeql,
3195 ".github/workflows/code-scanning-semgrep.yml"
3196 ));
3197 assert!(codeql.licence_refusal.is_none(), "MIT satisfies the terms");
3198
3199 let semgrep = project(Some(Provider::Semgrep));
3200 assert!(landed(
3201 &semgrep,
3202 ".github/workflows/code-scanning-semgrep.yml"
3203 ));
3204 assert!(!landed(
3205 &semgrep,
3206 ".github/workflows/code-scanning-codeql.yml"
3207 ));
3208
3209 let proprietary = CrateShape {
3211 cargo_toml: Some("[package]\nlicense = \"LicenseRef-proprietary\"\n".to_owned()),
3212 ..CrateShape::default()
3213 };
3214 assert!(
3215 code_scanning_licence_refusal(Some(Provider::Semgrep), Some("rust"), &proprietary)
3216 .is_none()
3217 );
3218 let refusal =
3219 code_scanning_licence_refusal(Some(Provider::CodeQl), Some("rust"), &proprietary)
3220 .expect("codeql refuses a licence its terms do not cover");
3221 assert!(refusal.contains("LicenseRef-proprietary"), "{refusal}");
3222 assert!(refusal.contains("semgrep"), "{refusal}");
3223 let bash =
3226 code_scanning_licence_refusal(Some(Provider::CodeQl), Some("bash"), &proprietary)
3227 .expect("an unread binding refuses");
3228 assert!(bash.contains("bash binding"), "{bash}");
3229 }
3230
3231 #[test]
3237 fn the_projection_performs_no_filesystem_git_environment_clock_registry_or_network_read() {
3238 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/projection.rs");
3239 let text = std::fs::read_to_string(&path).expect("the source reads");
3240 let production = text.split("#[cfg(test)]").next().unwrap_or("");
3241 let needles = [
3242 "std::fs",
3243 "std::env",
3244 "std::process",
3245 "std::time",
3246 "SystemTime",
3247 "Instant",
3248 "std::net",
3249 "Command::new",
3250 "registry::",
3251 "curl",
3252 "reqwest",
3253 "blob(",
3254 ];
3255 let mut hits = Vec::new();
3256 for (index, line) in production.lines().enumerate() {
3257 if line.trim_start().starts_with("//") {
3258 continue;
3259 }
3260 for needle in needles {
3261 if line.contains(needle) {
3262 hits.push(format!("src/projection.rs:{}: {needle}", index + 1));
3263 }
3264 }
3265 }
3266 assert!(
3267 hits.is_empty(),
3268 "the projection reads beyond its inputs: {hits:?}"
3269 );
3270 }
3271
3272 #[test]
3273 #[allow(
3274 clippy::too_many_lines,
3275 reason = "one test walks the three marked destinations and the three unmarked shapes"
3276 )]
3277 fn marked_region_projection_preserves_every_target_byte_outside_the_markers() {
3278 let agents_before = "# Widget\n\nOperator prose above.\n\n";
3279 let agents_after = "\n\n## Our rules\n\nOperator prose below. \n";
3280 let glossary_before = "# Glossary\n\n- `spike` is a throwaway branch.\n\n";
3281 let glossary_after = "\n\n## More terms\n\n- `own` is ours.";
3282 let hooks_before = "default_install_hook_types: [pre-commit]\n\nrepos:\n";
3283 let hooks_after =
3284 "\n - repo: https://example.com/own\n rev: v1\n hooks:\n - id: own\n";
3285 let stale = |begin: &str, end: &str| format!("{begin}\nstale block\n{end}");
3286 let mut documents = std::collections::BTreeMap::new();
3287 documents.insert(
3288 AGENTS_DESTINATION.to_owned(),
3289 format!(
3290 "{agents_before}{}{agents_after}",
3291 stale(BLOCK_BEGIN, BLOCK_END)
3292 )
3293 .into_bytes(),
3294 );
3295 documents.insert(
3296 GLOSSARY_DESTINATION.to_owned(),
3297 format!(
3298 "{glossary_before}{}{glossary_after}",
3299 stale(BLOCK_BEGIN, BLOCK_END)
3300 )
3301 .into_bytes(),
3302 );
3303 documents.insert(
3304 HOOKS_DESTINATION.to_owned(),
3305 format!(
3306 "{hooks_before}{}{hooks_after}",
3307 stale(HOOKS_BEGIN, HOOKS_END)
3308 )
3309 .into_bytes(),
3310 );
3311 let projection = compute(TargetEvidence {
3312 documents: documents.clone(),
3313 crate_shape: supported_shape(),
3314 ..TargetEvidence::default()
3315 });
3316 assert!(
3317 projection.collisions.is_empty(),
3318 "{:?}",
3319 projection.collisions
3320 );
3321 for (destination, before, after) in [
3322 (AGENTS_DESTINATION, agents_before, agents_after),
3323 (GLOSSARY_DESTINATION, glossary_before, glossary_after),
3324 (HOOKS_DESTINATION, hooks_before, hooks_after),
3325 ] {
3326 let candidate = candidate(&projection, destination);
3327 let Placement::Region { begin, end } = candidate.placement else {
3328 panic!("{destination} is a region");
3329 };
3330 let region = candidate
3331 .region
3332 .as_deref()
3333 .expect("a region carries its block");
3334 let (head, tail) = outside(&candidate.bytes, begin, end);
3335 assert_eq!(
3336 head,
3337 before.as_bytes(),
3338 "{destination}: bytes before the markers"
3339 );
3340 assert_eq!(
3341 tail,
3342 after.as_bytes(),
3343 "{destination}: bytes after the markers"
3344 );
3345 let inside = &candidate.bytes[head.len()..candidate.bytes.len() - tail.len()];
3346 assert_eq!(
3347 inside, region,
3348 "{destination}: the region is the rendered block"
3349 );
3350 let (existing_head, existing_tail) = outside(&documents[destination], begin, end);
3351 assert_eq!(head, existing_head);
3352 assert_eq!(tail, existing_tail);
3353 }
3354
3355 let own_hooks =
3359 "repos:\n - repo: https://example.com/own\n rev: v1\n hooks:\n - id: own\n";
3360 let own_agents = "# Widget\n\nOwn rules.";
3361 let mut documents = std::collections::BTreeMap::new();
3362 documents.insert(HOOKS_DESTINATION.to_owned(), own_hooks.as_bytes().to_vec());
3363 documents.insert(
3364 AGENTS_DESTINATION.to_owned(),
3365 own_agents.as_bytes().to_vec(),
3366 );
3367 let projection = compute(TargetEvidence {
3368 documents,
3369 crate_shape: supported_shape(),
3370 ..TargetEvidence::default()
3371 });
3372 assert!(
3373 projection.collisions.is_empty(),
3374 "{:?}",
3375 projection.collisions
3376 );
3377 let hooks = candidate(&projection, HOOKS_DESTINATION);
3378 let hooks_text = String::from_utf8_lossy(&hooks.bytes);
3379 let region = String::from_utf8_lossy(hooks.region.as_deref().expect("a region"));
3380 assert!(
3381 hooks_text.starts_with(&format!(
3382 "repos:\n{region}\n - repo: https://example.com/own"
3383 )),
3384 "{hooks_text}"
3385 );
3386 assert!(!hooks_text.contains(HOOK_TYPES_LINE));
3387 let agents = candidate(&projection, AGENTS_DESTINATION);
3388 assert!(agents.bytes.starts_with(own_agents.as_bytes()));
3389 assert_eq!(
3390 extract_block(
3391 &String::from_utf8_lossy(&agents.bytes),
3392 BLOCK_BEGIN,
3393 BLOCK_END
3394 )
3395 .map(str::as_bytes),
3396 agents.region.as_deref()
3397 );
3398 let glossary = candidate(&projection, GLOSSARY_DESTINATION);
3399 let region = glossary.region.as_deref().expect("a region");
3400 assert_eq!(
3401 glossary.bytes,
3402 [region, b"\n"].concat(),
3403 "an absent file is fresh"
3404 );
3405 }
3406
3407 #[test]
3413 fn a_hook_document_that_is_not_utf8_collides_instead_of_being_rewritten() {
3414 let mut documents = std::collections::BTreeMap::new();
3415 let mut invalid = b"repos:\n# own \xff above\n".to_vec();
3416 invalid.extend_from_slice(format!("{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n").as_bytes());
3417 invalid.extend_from_slice(b" - repo: local \xff below\n");
3418 documents.insert(HOOKS_DESTINATION.to_owned(), invalid);
3419 let mut agents = b"# Widget r\xe9sum\xe9\n\n".to_vec();
3420 agents.extend_from_slice(format!("{BLOCK_BEGIN}\nstale\n{BLOCK_END}\n\n").as_bytes());
3421 agents.extend_from_slice(b"r\xe9sum\xe9\n");
3422 documents.insert(AGENTS_DESTINATION.to_owned(), agents.clone());
3423 let projection = compute(TargetEvidence {
3424 documents,
3425 crate_shape: supported_shape(),
3426 ..TargetEvidence::default()
3427 });
3428 let collided: Vec<&str> = projection
3429 .collisions
3430 .iter()
3431 .map(|c| c.destination.as_str())
3432 .collect();
3433 assert_eq!(collided, [HOOKS_DESTINATION]);
3434 assert!(
3435 projection.collisions[0].reason.contains("not UTF-8"),
3436 "{}",
3437 projection.collisions[0].reason
3438 );
3439 assert!(
3440 !projection
3441 .candidates
3442 .iter()
3443 .any(|c| c.destination == HOOKS_DESTINATION),
3444 "a colliding destination projects no candidate"
3445 );
3446 let agents = candidate(&projection, AGENTS_DESTINATION);
3447 assert!(
3448 agents.bytes.starts_with(b"# Widget r\xe9sum\xe9\n\n"),
3449 "{:?}",
3450 agents.bytes
3451 );
3452 assert!(
3453 agents.bytes.ends_with(b"\n\nr\xe9sum\xe9\n"),
3454 "{:?}",
3455 agents.bytes
3456 );
3457 assert!(
3458 !agents.bytes.contains(&0xEF),
3459 "a replacement character landed"
3460 );
3461
3462 let mut documents = std::collections::BTreeMap::new();
3463 let valid =
3464 format!("repos:\n# own above\n{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n - repo: local\n");
3465 documents.insert(HOOKS_DESTINATION.to_owned(), valid.into_bytes());
3466 let projection = compute(TargetEvidence {
3467 documents,
3468 crate_shape: supported_shape(),
3469 ..TargetEvidence::default()
3470 });
3471 assert!(
3472 projection.collisions.is_empty(),
3473 "{:?}",
3474 projection.collisions
3475 );
3476 let hooks = candidate(&projection, HOOKS_DESTINATION);
3477 let text = String::from_utf8(hooks.bytes.clone()).expect("a valid document stays text");
3478 assert!(text.starts_with("repos:\n# own above\n"), "{text}");
3479 assert!(text.ends_with("\n - repo: local\n"), "{text}");
3480 assert!(!text.contains("stale"), "the region is replaced: {text}");
3481 }
3482
3483 #[test]
3487 fn a_whole_file_colliding_with_a_marked_region_names_both_source_paths() {
3488 let files: Vec<(String, &[u8])> = vec![
3489 ("snippets/_shared/github/SECURITY.md".to_owned(), b"policy"),
3490 ("snippets/rust/github/AGENTS.md".to_owned(), b"whole"),
3491 ];
3492 let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
3493 .expect_err("a whole file at a block destination refuses");
3494 let text = err.to_string();
3495 assert!(text.contains("snippets/rust/github/AGENTS.md"), "{text}");
3496 assert!(text.contains(super::AGENTS_BLOCK), "{text}");
3497 assert!(text.contains(super::AGENTS_LINE_AGENT_POLICY), "{text}");
3498 assert!(text.contains("embedded sources are defective"), "{text}");
3499 }
3500
3501 #[test]
3502 fn duplicate_whole_file_destinations_and_overlapping_marked_regions_refuse_with_the_conflicting_source_names()
3503 {
3504 let files: Vec<(String, &[u8])> = vec![
3507 ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
3508 ("snippets/rust/github/SECURITY.md".to_owned(), b"pair"),
3509 ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
3510 ];
3511 let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
3512 .expect_err("a doubled destination refuses");
3513 let text = err.to_string();
3514 assert!(
3515 text.contains("snippets/_shared/github/SECURITY.md"),
3516 "{text}"
3517 );
3518 assert!(text.contains("snippets/rust/github/SECURITY.md"), "{text}");
3519 assert!(text.contains("embedded sources are defective"), "{text}");
3520
3521 let clean: Vec<(String, &[u8])> = vec![
3522 ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
3523 ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
3524 ];
3525 let projection = Projection::compute_over(&clean, &input(TargetEvidence::default()))
3526 .expect("a clean list projects");
3527 let whole: Vec<&str> = projection
3528 .candidates
3529 .iter()
3530 .filter(|c| c.placement == Placement::Whole)
3531 .map(|c| c.destination.as_str())
3532 .collect();
3533 assert_eq!(whole, ["SECURITY.md", "release-plz.toml"]);
3534 assert_eq!(
3535 projection
3536 .candidates
3537 .iter()
3538 .find(|c| c.destination == "SECURITY.md")
3539 .map(|c| c.sources.clone()),
3540 Some(vec!["snippets/_shared/github/SECURITY.md".to_owned()])
3541 );
3542
3543 let doubled = format!("{BLOCK_BEGIN}\na\n{BLOCK_END}\n{BLOCK_BEGIN}\nb\n{BLOCK_END}\n");
3544 let unmatched = format!("repos:\n{HOOKS_BEGIN}\n - repo: local\n");
3545 let misordered = format!("# G\n{BLOCK_END}\n{BLOCK_BEGIN}\n");
3546 let mut documents = std::collections::BTreeMap::new();
3547 documents.insert(AGENTS_DESTINATION.to_owned(), doubled.into_bytes());
3548 documents.insert(HOOKS_DESTINATION.to_owned(), unmatched.into_bytes());
3549 documents.insert(GLOSSARY_DESTINATION.to_owned(), misordered.into_bytes());
3550 let projection = compute(TargetEvidence {
3551 documents,
3552 crate_shape: supported_shape(),
3553 ..TargetEvidence::default()
3554 });
3555 let mut collided: Vec<&str> = projection
3556 .collisions
3557 .iter()
3558 .map(|Collision { destination, .. }| destination.as_str())
3559 .collect();
3560 collided.sort_unstable();
3561 let mut expected = BLOCK_DESTINATIONS.to_vec();
3562 expected.sort_unstable();
3563 assert_eq!(collided, expected);
3564 for collision in &projection.collisions {
3565 assert!(
3566 collision.reason.contains(&collision.destination),
3567 "{collision:?}"
3568 );
3569 assert!(
3570 !projection
3571 .candidates
3572 .iter()
3573 .any(|candidate| candidate.destination == collision.destination),
3574 "{} collided and still projects",
3575 collision.destination
3576 );
3577 }
3578 let agents = projection
3579 .collisions
3580 .iter()
3581 .find(|c| c.destination == AGENTS_DESTINATION)
3582 .expect("the doubled document collides");
3583 assert!(agents.reason.contains("more than one"), "{}", agents.reason);
3584 let hooks = projection
3585 .collisions
3586 .iter()
3587 .find(|c| c.destination == HOOKS_DESTINATION)
3588 .expect("the unmatched document collides");
3589 assert!(hooks.reason.contains("unmatched"), "{}", hooks.reason);
3590 }
3591}