1pub mod evidence;
32
33use std::collections::BTreeMap;
34
35use serde::{Deserialize, Serialize};
36
37use crate::embedded;
38use crate::error::RkError;
39pub use crate::landing::manifest::Provider;
40use crate::landing::{CheckoutMode, Integration, Params};
41use crate::profile::ReleaseMode;
42use crate::profile::catalog::{self, Availability, Selection, Status};
43
44#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct ProjectionInput {
48 pub params: Params,
50 pub evidence: TargetEvidence,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Default)]
57#[allow(
58 clippy::struct_excessive_bools,
59 reason = "each field is one independent fact read off the target, not a state a smaller type could carry"
60)]
61pub struct TargetEvidence {
62 pub documents: BTreeMap<String, Vec<u8>>,
66 pub crate_shape: CrateShape,
68 pub flake_nix_present: bool,
70 pub flake_lock_present: bool,
72 pub flake_recorded: bool,
75 pub root_pipeline_present: bool,
77 pub root_pipeline_recorded: bool,
80}
81
82impl TargetEvidence {
83 #[must_use]
85 pub fn document(&self, destination: &str) -> Option<&[u8]> {
86 self.documents.get(destination).map(Vec::as_slice)
87 }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Default)]
93pub struct CrateShape {
94 pub cargo_toml: Option<String>,
96 pub cargo_lock: bool,
98 pub main_rs: bool,
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct Projection {
109 pub capabilities: Vec<Selection>,
112 pub candidates: Vec<Candidate>,
114 pub omissions: Vec<Omission>,
119 pub collisions: Vec<Collision>,
122 pub licence_refusal: Option<String>,
128 pub record_defects: Vec<String>,
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Candidate {
138 pub capability: &'static str,
140 pub destination: String,
142 pub kind: Kind,
144 pub placement: Placement,
146 pub bytes: Vec<u8>,
150 pub region: Option<Vec<u8>>,
153 pub sources: Vec<String>,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum Placement {
161 Whole,
163 Region {
166 begin: &'static str,
168 end: &'static str,
170 },
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct Omission {
176 pub destination: String,
178 pub reason: String,
180 pub action: Option<String>,
184}
185
186#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct Collision {
189 pub destination: String,
191 pub reason: String,
193}
194
195impl Projection {
196 pub fn compute(input: &ProjectionInput) -> Result<Self, RkError> {
206 Self::compute_over(&embedded_snippets(), input)
207 }
208
209 #[allow(
213 clippy::too_many_lines,
214 reason = "one pass selects, renders, splices, and withholds; splitting it would separate a withheld destination from the selection that offered it"
215 )]
216 fn compute_over(files: &[(String, &[u8])], input: &ProjectionInput) -> Result<Self, RkError> {
217 let params = &input.params;
218 let evidence = &input.evidence;
219 let availability = Availability::over(
220 files
221 .iter()
222 .filter_map(|(path, _)| path.strip_prefix("snippets/").map(str::to_owned))
223 .collect(),
224 );
225 let mut capabilities = catalog::select(params, &availability);
226 let mut candidates: Vec<Candidate> = Vec::new();
227 for selection in &capabilities {
228 if !selection.lands() {
229 continue;
230 }
231 for source in &selection.sources {
232 let destination = source
233 .splitn(3, '/')
234 .nth(2)
235 .ok_or_else(|| {
236 anyhow::anyhow!(
237 "{source}: a snippet path has a zone, a forge, and a destination"
238 )
239 })?
240 .to_owned();
241 let path = format!("snippets/{source}");
242 let bytes = files
243 .iter()
244 .find(|(candidate, _)| *candidate == path)
245 .map(|(_, bytes)| *bytes)
246 .ok_or_else(|| {
247 anyhow::anyhow!(
248 "{path}: the catalog selected a source the tree does not carry"
249 )
250 })?;
251 if let Some(existing) = candidates
252 .iter()
253 .find(|candidate| candidate.destination == destination)
254 {
255 return Err(anyhow::anyhow!(
256 "{} and {} both ship {destination}: {} and {path}; the embedded sources are defective",
257 existing.capability,
258 selection.id,
259 existing.sources.join(", ")
260 )
261 .into());
262 }
263 let kind = kind_of(&destination).ok_or_else(|| {
264 anyhow::anyhow!(
265 "the embedded sources do not classify {destination}; the kind table is stale"
266 )
267 })?;
268 let rendered = match kind {
269 Kind::Rendered => render(bytes, params),
270 Kind::Seeded | Kind::State => bytes.to_vec(),
271 };
272 candidates.push(Candidate {
273 capability: selection.id,
274 destination,
275 kind,
276 placement: Placement::Whole,
277 bytes: rendered,
278 region: None,
279 sources: vec![path],
280 });
281 }
282 }
283 let mut collisions = Vec::new();
284 for destination in BLOCK_DESTINATIONS {
285 let (template, sources) =
286 block_template(destination, params.checkout_mode(), params.integration())?;
287 if let Some(whole) = candidates
288 .iter()
289 .find(|candidate| candidate.destination == destination)
290 {
291 return Err(anyhow::anyhow!(
292 "{destination} is both a whole file from {} and a marked region from {}; the embedded sources are defective",
293 whole.sources.join(", "),
294 sources.join(", ")
295 )
296 .into());
297 }
298 let region = render(template.as_bytes(), params);
299 let (begin, end) = block_markers(destination).ok_or_else(|| {
300 anyhow::anyhow!("{destination} is a block destination with no markers")
301 })?;
302 match propose_document(destination, evidence.document(destination), ®ion) {
303 Ok(bytes) => candidates.push(Candidate {
304 capability: catalog::GUARDS,
305 destination: destination.to_owned(),
306 kind: Kind::Rendered,
307 placement: Placement::Region { begin, end },
308 bytes,
309 region: Some(region),
310 sources,
311 }),
312 Err(reason) => collisions.push(Collision {
313 destination: destination.to_owned(),
314 reason,
315 }),
316 }
317 }
318 let mut omissions = Vec::new();
319 if let Some((set, reason)) = nix_withholding(params.nix_packaging(), evidence)
320 && candidates
321 .iter()
322 .any(|candidate| candidate.capability == catalog::PACKAGING_NIX)
323 {
324 candidates.retain(|candidate| {
325 if set.contains(&candidate.destination.as_str()) {
326 omissions.push(Omission {
327 destination: candidate.destination.clone(),
328 reason: reason.clone(),
329 action: None,
330 });
331 false
332 } else {
333 true
334 }
335 });
336 withhold(&mut capabilities, catalog::PACKAGING_NIX, &reason, None);
337 }
338 let title_root = candidates.iter().position(|candidate| {
344 candidate.capability == catalog::TITLE_CHECK
345 && candidate.destination == GITLAB_ROOT_PIPELINE
346 });
347 if let Some(index) = title_root
348 && evidence.root_pipeline_present
349 && !evidence.root_pipeline_recorded
350 {
351 let candidate = candidates.remove(index);
352 let reason = format!(
353 "the target owns {GITLAB_ROOT_PIPELINE}, so the release-less root pipeline that would activate the title gate stays out; the fragment lands as the gate's prerequisite"
354 );
355 let action = format!(
356 "add the include to the target's own {GITLAB_ROOT_PIPELINE}: include:\n - local: {GITLAB_TITLE_FRAGMENT}"
357 );
358 omissions.push(Omission {
359 destination: candidate.destination,
360 reason: reason.clone(),
361 action: Some(action.clone()),
362 });
363 withhold(
364 &mut capabilities,
365 catalog::TITLE_CHECK,
366 &reason,
367 Some(action),
368 );
369 }
370 candidates.sort_by(|a, b| a.destination.cmp(&b.destination));
371 omissions.sort_by(|a, b| a.destination.cmp(&b.destination));
372 let scanning_selected = capabilities.iter().any(|selection| {
378 selection.id == catalog::CODE_SCANNING && selection.status == Status::Selected
379 });
380 let licence_refusal = scanning_selected
381 .then(|| {
382 code_scanning_licence_refusal(
383 params.code_scanning(),
384 params.driver(),
385 &evidence.crate_shape,
386 )
387 })
388 .flatten();
389 let mut record_defects: Vec<String> = Vec::new();
394 if params.release_mode() == ReleaseMode::Automatic
398 && let Some(selection) = capabilities
399 .iter()
400 .find(|selection| selection.id == catalog::RELEASE_AUTOMATION)
401 && matches!(selection.status, Status::Unavailable | Status::Unknown)
402 && let Some(reason) = &selection.reason
403 {
404 record_defects.push(reason.clone());
405 }
406 Ok(Self {
407 capabilities,
408 candidates,
409 omissions,
410 collisions,
411 licence_refusal,
412 record_defects,
413 })
414 }
415
416 #[must_use]
420 pub fn release_unavailable(&self) -> Option<&str> {
421 self.capabilities
422 .iter()
423 .find(|selection| {
424 selection.id == catalog::RELEASE_AUTOMATION
425 && matches!(selection.status, Status::Unavailable | Status::Unknown)
426 })
427 .and_then(|selection| selection.reason.as_deref())
428 }
429
430 #[must_use]
432 pub fn capability(&self, id: &str) -> Option<&Selection> {
433 self.capabilities
434 .iter()
435 .find(|selection| selection.id == id)
436 }
437}
438
439fn withhold(capabilities: &mut [Selection], id: &str, reason: &str, action: Option<String>) {
441 if let Some(selection) = capabilities.iter_mut().find(|selection| selection.id == id) {
442 selection.status = Status::Withheld;
443 selection.reason = Some(reason.to_owned());
444 selection.action = action;
445 }
446}
447
448pub const GITLAB_ROOT_PIPELINE: &str = ".gitlab-ci.yml";
451
452pub const GITLAB_TITLE_FRAGMENT: &str = ".gitlab/ci/mr-title.yml";
454
455fn embedded_snippets() -> Vec<(String, &'static [u8])> {
458 embedded::walk(&embedded::SNIPPETS)
459 .into_iter()
460 .map(|(path, bytes)| (format!("snippets/{path}"), bytes))
461 .collect()
462}
463
464#[must_use]
467pub fn supported_pairs() -> Vec<(String, String)> {
468 Availability::embedded()
469 .automation_tuples()
470 .into_iter()
471 .filter_map(|entry| {
472 entry
473 .split_once(", ")
474 .map(|(driver, forge)| (driver.to_owned(), forge.to_owned()))
475 })
476 .collect()
477}
478
479#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
481#[serde(rename_all = "lowercase")]
482pub enum Kind {
483 Rendered,
486 Seeded,
489 State,
492}
493
494impl Kind {
495 #[must_use]
497 pub const fn as_str(self) -> &'static str {
498 match self {
499 Self::Rendered => "rendered",
500 Self::Seeded => "seeded",
501 Self::State => "state",
502 }
503 }
504}
505
506const KINDS: [(&str, Kind); 20] = [
512 (".github/workflows/release-plz.yml", Kind::Rendered),
513 (".github/workflows/release-please.yml", Kind::Rendered),
514 (".github/workflows/release.yml", Kind::Rendered),
515 (".github/workflows/pr-title.yml", Kind::Rendered),
516 (".github/workflows/scorecard.yml", Kind::Rendered),
517 (".github/workflows/code-scanning-codeql.yml", Kind::Rendered),
518 (
519 ".github/workflows/code-scanning-semgrep.yml",
520 Kind::Rendered,
521 ),
522 (".gitlab/ci/code-scanning-semgrep.yml", Kind::Rendered),
523 (".gitlab-ci.yml", Kind::Rendered),
524 ("SECURITY.md", Kind::Rendered),
525 (".gitlab/ci/mr-title.yml", Kind::Rendered),
526 ("release-plz.toml", Kind::Seeded),
527 ("dist-workspace.toml", Kind::Seeded),
528 ("release-please-config.json", Kind::Seeded),
529 ("cliff.toml", Kind::Seeded),
530 ("nix/package.nix", Kind::Seeded),
531 ("flake.nix", Kind::Seeded),
532 (".release-please-manifest.json", Kind::State),
533 ("VERSION", Kind::State),
534 ("flake.lock", Kind::State),
535];
536
537pub const NIX_DESTINATIONS: [&str; 3] = ["nix/package.nix", "flake.nix", "flake.lock"];
551
552pub const NIX_WITHHOLDABLE: [&str; 2] = ["flake.nix", "flake.lock"];
558
559pub const SCORECARD_DESTINATIONS: [&str; 1] = [".github/workflows/scorecard.yml"];
574
575pub const CODE_SCANNING_DESTINATIONS: [(&str, Provider); 3] = [
589 (
590 ".github/workflows/code-scanning-codeql.yml",
591 Provider::CodeQl,
592 ),
593 (
594 ".github/workflows/code-scanning-semgrep.yml",
595 Provider::Semgrep,
596 ),
597 (".gitlab/ci/code-scanning-semgrep.yml", Provider::Semgrep),
598];
599
600pub const CODE_SCANNING_TECHS: [&str; 1] = ["rust"];
608
609#[must_use]
626pub fn code_scanning_incompatibility(
627 provider: Option<Provider>,
628 driver: Option<&str>,
629 forge: Option<&str>,
630) -> Option<String> {
631 let named = provider?;
632 let Some(driver) = driver else {
633 return Some(format!(
634 "a scanner reads the release driver's language, and the profile names no automatic release driver; the bindings that carry one are: {}",
635 CODE_SCANNING_TECHS.join(", ")
636 ));
637 };
638 if !CODE_SCANNING_TECHS.contains(&driver) {
639 return Some(format!(
640 "the {driver} binding ships no code scanning workflow; a scanner reads one language, and the bindings that carry one are: {}",
641 CODE_SCANNING_TECHS.join(", ")
642 ));
643 }
644 let Some(forge) = forge else {
645 return Some(
646 "a code scanning workflow runs at a forge, and the profile names none".to_owned(),
647 );
648 };
649 if named == Provider::CodeQl && forge != "github" {
650 return Some(format!(
651 "codeql is GitHub's own analyzer and the {forge} pair ships no workflow for it; pass --code-scanning semgrep"
652 ));
653 }
654 None
655}
656
657const OSI_APPROVED: [&str; 18] = [
667 "0bsd",
668 "agpl-3.0",
669 "agpl-3.0-only",
670 "agpl-3.0-or-later",
671 "apache-2.0",
672 "bsd-2-clause",
673 "bsd-3-clause",
674 "bsl-1.0",
675 "epl-2.0",
676 "gpl-2.0",
677 "gpl-2.0-only",
678 "gpl-2.0-or-later",
679 "gpl-3.0",
680 "gpl-3.0-only",
681 "gpl-3.0-or-later",
682 "isc",
683 "mit",
684 "mpl-2.0",
685];
686
687const CONTENT_LICENCES: [&str; 4] = ["cc-by-3.0", "cc-by-4.0", "cc-by-sa-3.0", "cc-by-sa-4.0"];
705
706const SPDX_EXCEPTIONS: [&str; 86] = [
723 "389-exception",
724 "asterisk-exception",
725 "asterisk-linking-protocols-exception",
726 "autoconf-exception-2.0",
727 "autoconf-exception-3.0",
728 "autoconf-exception-generic",
729 "autoconf-exception-generic-3.0",
730 "autoconf-exception-macro",
731 "bison-exception-1.24",
732 "bison-exception-2.2",
733 "bootloader-exception",
734 "cgal-linking-exception",
735 "classpath-exception-2.0",
736 "classpath-exception-2.0-short",
737 "clisp-exception-2.0",
738 "cryptsetup-openssl-exception",
739 "digia-qt-lgpl-exception-1.1",
740 "digirule-foss-exception",
741 "ecos-exception-2.0",
742 "erlang-otp-linking-exception",
743 "fawkes-runtime-exception",
744 "fltk-exception",
745 "fmt-exception",
746 "font-exception-2.0",
747 "freertos-exception-2.0",
748 "gcc-exception-2.0",
749 "gcc-exception-2.0-note",
750 "gcc-exception-3.1",
751 "gmsh-exception",
752 "gnat-exception",
753 "gnome-examples-exception",
754 "gnu-compiler-exception",
755 "gnu-javamail-exception",
756 "google-patent-webm",
757 "gpl-3.0-389-ds-base-exception",
758 "gpl-3.0-interface-exception",
759 "gpl-3.0-linking-exception",
760 "gpl-3.0-linking-source-exception",
761 "gpl-cc-1.0",
762 "gstreamer-exception-2005",
763 "gstreamer-exception-2008",
764 "harbour-exception",
765 "i2p-gpl-java-exception",
766 "independent-modules-exception",
767 "kicad-libraries-exception",
768 "kvirc-openssl-exception",
769 "lgpl-3.0-linking-exception",
770 "libpri-openh323-exception",
771 "libtool-exception",
772 "linux-syscall-note",
773 "llgpl",
774 "llvm-exception",
775 "lzma-exception",
776 "mif-exception",
777 "mxml-exception",
778 "nokia-qt-exception-1.1",
779 "ocaml-lgpl-linking-exception",
780 "occt-exception-1.0",
781 "openjdk-assembly-exception-1.0",
782 "openvpn-openssl-exception",
783 "pcre2-exception",
784 "polyparse-exception",
785 "ps-or-pdf-font-exception-20170817",
786 "qpl-1.0-inria-2004-exception",
787 "qt-gpl-exception-1.0",
788 "qt-lgpl-exception-1.1",
789 "qwt-exception-1.0",
790 "romic-exception",
791 "rrdtool-floss-exception-2.0",
792 "rsync-linking-exception",
793 "sane-exception",
794 "shl-2.0",
795 "shl-2.1",
796 "simple-library-usage-exception",
797 "spelling-provider-lgpl-exception",
798 "sqlitestudio-openssl-exception",
799 "stunnel-exception",
800 "swi-exception",
801 "swift-exception",
802 "texinfo-exception",
803 "u-boot-exception-2.0",
804 "ubdl-exception",
805 "universal-foss-exception-1.0",
806 "vsftpd-openssl-exception",
807 "wxwindows-exception-3.1",
808 "x11vnc-openssl-exception",
809];
810
811fn listed(list: &[&str], identifier: &str) -> bool {
818 let lowered = identifier.to_ascii_lowercase();
819 list.contains(&lowered.as_str())
820}
821
822#[derive(Debug, Clone, Copy, PartialEq, Eq)]
824enum Token<'a> {
825 Open,
827 Close,
829 And,
831 Or,
833 With,
836 Identifier(&'a str),
839}
840
841fn tokenize(expression: &str) -> Option<Vec<Token<'_>>> {
849 let mut tokens = Vec::new();
850 let bytes = expression.as_bytes();
851 let mut at = 0;
852 while at < bytes.len() {
853 let byte = bytes[at];
854 if byte.is_ascii_whitespace() {
855 at += 1;
856 continue;
857 }
858 if byte == b'(' {
859 tokens.push(Token::Open);
860 at += 1;
861 continue;
862 }
863 if byte == b')' {
864 tokens.push(Token::Close);
865 at += 1;
866 continue;
867 }
868 let start = at;
869 while at < bytes.len() {
870 let byte = bytes[at];
871 if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'+' | b':') {
872 at += 1;
873 } else {
874 break;
875 }
876 }
877 if at == start {
878 return None;
879 }
880 let word = &expression[start..at];
881 tokens.push(match word {
882 "AND" => Token::And,
883 "OR" => Token::Or,
884 "WITH" => Token::With,
885 other => Token::Identifier(other),
886 });
887 }
888 Some(tokens)
889}
890
891#[derive(Debug, Clone, Copy)]
898struct Verdict {
899 grants: bool,
901 clean: bool,
903}
904
905struct Spdx<'a> {
914 tokens: &'a [Token<'a>],
915 at: usize,
916}
917
918impl<'a> Spdx<'a> {
919 fn peek(&self) -> Option<Token<'a>> {
921 self.tokens.get(self.at).copied()
922 }
923
924 fn bump(&mut self) -> Option<Token<'a>> {
926 let token = self.peek()?;
927 self.at += 1;
928 Some(token)
929 }
930
931 fn expression(&mut self) -> Option<Verdict> {
941 let mut verdict = self.conjunction()?;
942 while self.peek() == Some(Token::Or) {
943 self.bump();
944 let right = self.conjunction()?;
945 verdict = Verdict {
946 grants: verdict.grants && right.grants,
947 clean: verdict.clean && right.clean,
948 };
949 }
950 Some(verdict)
951 }
952
953 fn conjunction(&mut self) -> Option<Verdict> {
963 let mut verdict = self.operand()?;
964 while self.peek() == Some(Token::And) {
965 self.bump();
966 let right = self.operand()?;
967 verdict = Verdict {
968 grants: verdict.grants || right.grants,
969 clean: verdict.clean && right.clean,
970 };
971 }
972 Some(verdict)
973 }
974
975 fn operand(&mut self) -> Option<Verdict> {
985 match self.bump()? {
986 Token::Open => {
987 let inner = self.expression()?;
990 (self.bump()? == Token::Close).then_some(inner)
991 }
992 Token::Identifier(name) => {
993 let identifier = name.strip_suffix('+').unwrap_or(name);
994 let approved = listed(&OSI_APPROVED, identifier);
995 let verdict = Verdict {
996 grants: approved,
997 clean: approved || listed(&CONTENT_LICENCES, identifier),
998 };
999 if self.peek() == Some(Token::With) {
1000 self.bump();
1001 match self.bump()? {
1005 Token::Identifier(exception) if listed(&SPDX_EXCEPTIONS, exception) => {}
1006 _ => return None,
1007 }
1008 }
1009 Some(verdict)
1010 }
1011 Token::And | Token::Or | Token::With | Token::Close => None,
1012 }
1013 }
1014}
1015
1016#[must_use]
1032pub fn licence_states_an_open_source_codebase(expression: &str) -> bool {
1033 let Some(tokens) = tokenize(expression) else {
1034 return false;
1035 };
1036 let mut reader = Spdx {
1037 tokens: &tokens,
1038 at: 0,
1039 };
1040 let Some(verdict) = reader.expression() else {
1041 return false;
1042 };
1043 verdict.grants && verdict.clean && reader.at == tokens.len()
1044}
1045
1046#[must_use]
1060pub fn code_scanning_licence_refusal(
1061 provider: Option<Provider>,
1062 driver: Option<&str>,
1063 shape: &CrateShape,
1064) -> Option<String> {
1065 if provider != Some(Provider::CodeQl) {
1066 return None;
1067 }
1068 if driver != Some("rust") {
1069 return Some(format!(
1070 "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",
1071 driver.unwrap_or("release-less")
1072 ));
1073 }
1074 let fallback = "land --code-scanning semgrep, which carries no licence condition";
1075 let Some(text) = shape.cargo_toml.as_deref() else {
1076 return Some(format!(
1077 "the target has no readable Cargo.toml, so the licence codeql's terms depend on cannot be read; {fallback}"
1078 ));
1079 };
1080 let Ok(table) = text.parse::<toml::Table>() else {
1081 return Some(format!(
1082 "the target's Cargo.toml does not parse, so the licence codeql's terms depend on cannot be read; {fallback}"
1083 ));
1084 };
1085 let licence = table
1086 .get("package")
1087 .and_then(toml::Value::as_table)
1088 .and_then(|package| package.get("license"))
1089 .and_then(toml::Value::as_str);
1090 match licence {
1091 None => Some(format!(
1092 "the target's Cargo.toml declares no license field, and codeql's terms cover an open-source codebase alone; declare one, or {fallback}"
1093 )),
1094 Some(expression) if !licence_states_an_open_source_codebase(expression) => Some(format!(
1095 "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}"
1096 )),
1097 Some(_) => None,
1098 }
1099}
1100
1101#[must_use]
1104pub fn kind_of(destination: &str) -> Option<Kind> {
1105 if BLOCK_DESTINATIONS.contains(&destination) {
1106 return Some(Kind::Rendered);
1107 }
1108 KINDS
1109 .iter()
1110 .find(|(name, _)| *name == destination)
1111 .map(|(_, kind)| *kind)
1112}
1113
1114pub fn destinations() -> impl Iterator<Item = &'static str> {
1119 KINDS
1120 .iter()
1121 .map(|(name, _)| *name)
1122 .chain(BLOCK_DESTINATIONS)
1123}
1124
1125pub const OWNER_TOKEN: &[u8] = b"OWNER";
1132
1133pub const REPO_PLACEHOLDER: &str = "OWNER";
1138
1139pub const REPO_TOKEN: &[u8] = b"RK_REPO";
1141
1142pub const SCOPE_SHAPE_TOKEN: &[u8] = b"RK_SCOPE_SHAPE";
1144
1145pub const STYLE_TOKEN: &[u8] = b"RK_STYLE";
1148
1149pub const TRUNK_BRANCH_TOKEN: &[u8] = b"RK_TRUNK_BRANCH";
1153
1154pub const LINE_PREFIX_TOKEN: &[u8] = b"RK_LINE_PREFIX";
1157
1158pub const LINE_PREFIX_RE_TOKEN: &[u8] = b"RK_LINE_PREFIX_RE";
1164
1165pub const SECURITY_SPANS: [(&[u8], &[u8]); 3] = [
1176 (
1177 b"<!--RK_SECURITY_CONTACT_BEGIN-->",
1178 b"<!--RK_SECURITY_CONTACT_END-->",
1179 ),
1180 (
1181 b"<!--RK_SECURITY_RESPONSE_BEGIN-->",
1182 b"<!--RK_SECURITY_RESPONSE_END-->",
1183 ),
1184 (
1185 b"<!--RK_SECURITY_DEADLINE_BEGIN-->",
1186 b"<!--RK_SECURITY_DEADLINE_END-->",
1187 ),
1188];
1189
1190fn acknowledgment(response: &str) -> String {
1193 format!("Maintainers acknowledge a report within {response}.")
1194}
1195
1196const DISCLOSURE_ONLY: &[u8] = b"This policy commits to no disclosure deadline.";
1200
1201fn security_replacements(params: &Params) -> [Option<Vec<u8>>; 3] {
1204 let contact = (!params.security_contact().is_empty())
1205 .then(|| params.security_contact().as_bytes().to_vec());
1206 let promised = params.security_response() != crate::config::RESPONSE_DEFAULT;
1207 [
1208 contact,
1209 promised.then(|| acknowledgment(params.security_response()).into_bytes()),
1210 promised.then(|| DISCLOSURE_ONLY.to_vec()),
1211 ]
1212}
1213
1214fn replace_span(baseline: &[u8], begin: &[u8], end: &[u8], value: Option<&[u8]>) -> Vec<u8> {
1220 let ordered = find(baseline, begin)
1221 .zip(find(baseline, end))
1222 .filter(|(start, stop)| stop > start);
1223 let Some((start, stop)) = ordered else {
1224 return baseline.to_vec();
1225 };
1226 let mut out = Vec::with_capacity(baseline.len());
1227 out.extend_from_slice(&baseline[..start]);
1228 out.extend_from_slice(value.unwrap_or_else(|| &baseline[start + begin.len()..stop]));
1229 out.extend_from_slice(&baseline[stop + end.len()..]);
1230 out
1231}
1232
1233#[must_use]
1251pub fn render(baseline: &[u8], params: &Params) -> Vec<u8> {
1252 let repo = params.repo();
1253 let owner = repo.split('/').next().unwrap_or(repo);
1254 let mut out = substitute(baseline, OWNER_TOKEN, owner.as_bytes());
1255 if let Some(style) = params.style() {
1256 out = substitute(&out, STYLE_TOKEN, style.as_str().as_bytes());
1257 }
1258 out = substitute(&out, SCOPE_SHAPE_TOKEN, SCOPE_SHAPE.as_bytes());
1259 out = substitute(&out, TRUNK_BRANCH_TOKEN, params.trunk().as_bytes());
1260 let escaped = params.line_prefix().replace('/', "\\/");
1261 out = substitute(&out, LINE_PREFIX_RE_TOKEN, escaped.as_bytes());
1262 out = substitute(&out, LINE_PREFIX_TOKEN, params.line_prefix().as_bytes());
1263 out = substitute(&out, REPO_TOKEN, repo.as_bytes());
1264 for ((begin, end), value) in SECURITY_SPANS.iter().zip(security_replacements(params)) {
1265 out = replace_span(&out, begin, end, value.as_deref());
1266 }
1267 out
1268}
1269
1270#[must_use]
1272pub fn substitute(baseline: &[u8], token: &[u8], value: &[u8]) -> Vec<u8> {
1273 let mut out = Vec::with_capacity(baseline.len());
1274 let mut rest = baseline;
1275 while let Some(at) = find(rest, token) {
1276 out.extend_from_slice(&rest[..at]);
1277 out.extend_from_slice(value);
1278 rest = &rest[at + token.len()..];
1279 }
1280 out.extend_from_slice(rest);
1281 out
1282}
1283
1284fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1286 haystack
1287 .windows(needle.len())
1288 .position(|window| window == needle)
1289}
1290
1291pub const AGENTS_DESTINATION: &str = "AGENTS.md";
1293
1294pub const BLOCK_BEGIN: &str = "<!-- BEGIN release-kit -->";
1296
1297pub const BLOCK_END: &str = "<!-- END release-kit -->";
1299
1300pub const GLOSSARY_DESTINATION: &str = "GLOSSARY.md";
1305
1306pub const HOOKS_DESTINATION: &str = ".pre-commit-config.yaml";
1308
1309pub const BLOCK_DESTINATIONS: [&str; 3] =
1315 [AGENTS_DESTINATION, GLOSSARY_DESTINATION, HOOKS_DESTINATION];
1316
1317pub const HOOKS_BEGIN: &str = "# BEGIN release-kit";
1319
1320pub const HOOKS_END: &str = "# END release-kit";
1322
1323pub const HOOK_TYPES_LINE: &str = "default_install_hook_types: [pre-commit, commit-msg, pre-push]";
1327
1328pub const AGENTS_BLOCK: &str = "blocks/agents-block.md.in";
1330
1331pub const GLOSSARY_BLOCK: &str = "blocks/glossary.md.in";
1333
1334pub const AGENTS_LINE_WORKTREE: &str = "blocks/agents-line-worktree.md.in";
1336
1337pub const AGENTS_LINE_BRANCHES: &str = "blocks/agents-line-branches.md.in";
1339
1340pub const AGENTS_LINE_INTEGRATION_FORGE: &str = "blocks/agents-line-integration-forge.md.in";
1342
1343pub const AGENTS_LINE_INTEGRATION_LOCAL: &str = "blocks/agents-line-integration-local.md.in";
1345
1346#[must_use]
1348pub const fn integration_line(integration: Integration) -> &'static str {
1349 match integration {
1350 Integration::Forge => AGENTS_LINE_INTEGRATION_FORGE,
1351 Integration::Local => AGENTS_LINE_INTEGRATION_LOCAL,
1352 }
1353}
1354
1355pub const PRE_COMMIT_BLOCK: &str = "blocks/pre-commit-block.yaml.in";
1357
1358pub const PRE_COMMIT_WORKTREE_GUARD: &str = "blocks/pre-commit-worktree-guard.yaml.in";
1360
1361pub const PRE_COMMIT_TRUNK_COMMIT_GUARD: &str = "blocks/pre-commit-trunk-commit-guard.yaml.in";
1363
1364pub const PRE_COMMIT_TRUNK_PUSH_GUARD: &str = "blocks/pre-commit-trunk-push-guard.yaml.in";
1366
1367pub const PRE_COMMIT_SWEEP_SKIP: &str = "blocks/pre-commit-sweep-skip.yaml.in";
1369
1370pub const PRE_COMMIT_SWEEP_NONE: &str = "blocks/pre-commit-sweep-none.yaml.in";
1372
1373pub const PRE_COMMIT_INTEGRATE_NOTE: &str = "blocks/pre-commit-integrate-note.yaml.in";
1375
1376#[must_use]
1378pub const fn routing_line(mode: CheckoutMode) -> &'static str {
1379 match mode {
1380 CheckoutMode::LinkedWorktree => AGENTS_LINE_WORKTREE,
1381 CheckoutMode::MainWorktree => AGENTS_LINE_BRANCHES,
1382 }
1383}
1384
1385pub fn embedded_block(path: &str) -> Result<&'static str, RkError> {
1392 let name = path.strip_prefix("blocks/").unwrap_or(path);
1393 let file = embedded::BLOCKS
1394 .get_file(name)
1395 .ok_or_else(|| anyhow::anyhow!("{path}: this binary embeds no such block"))?;
1396 std::str::from_utf8(file.contents())
1397 .map_err(|_| anyhow::anyhow!("{path}: a block is UTF-8").into())
1398}
1399
1400#[must_use]
1404pub fn authored(text: &str) -> &str {
1405 text.strip_suffix('\n').unwrap_or(text)
1406}
1407
1408pub 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[-/].+)$";
1416
1417pub const SCOPE_SHAPE: &str = "[a-z0-9._/-]+";
1427
1428#[must_use]
1435pub fn scope_is_shaped(scope: &str) -> bool {
1436 !scope.is_empty()
1437 && scope.chars().all(|c| {
1438 c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '/' | '-')
1439 })
1440}
1441
1442#[must_use]
1449pub fn compose_routing(template: &str, line: &str, integration_line: &str) -> String {
1450 authored(template)
1451 .replacen("RK_WORKFLOW_LINE", authored(line), 1)
1452 .replacen("RK_INTEGRATION_LINE", authored(integration_line), 1)
1453}
1454
1455#[must_use]
1459pub fn compose_glossary(template: &str) -> String {
1460 authored(template).to_owned()
1461}
1462
1463#[must_use]
1482pub fn compose_hooks(template: &str, guard: Option<&str>, parts: &TrunkGuards) -> String {
1483 let guard = guard.map_or_else(String::new, |entry| format!("{}\n", authored(entry)));
1484 let mut skips: Vec<&str> = Vec::new();
1485 if parts.integration == Integration::Forge {
1486 skips.push("no-commit-to-branch");
1487 }
1488 if !guard.is_empty() {
1489 skips.push("rk-worktree-location");
1490 }
1491 let sweep = if skips.is_empty() {
1492 format!("{}\n", authored(parts.sweep_none))
1493 } else {
1494 format!(
1495 "{}\n",
1496 authored(parts.sweep_skip).replacen("RK_SWEEP_SKIP", &skips.join(","), 1)
1497 )
1498 };
1499 let (commit_guard, push_guard, note) = match parts.integration {
1500 Integration::Forge => (
1501 format!("{}\n", authored(parts.trunk_commit)),
1502 format!("{}\n", authored(parts.trunk_push)),
1503 String::new(),
1504 ),
1505 Integration::Local => (
1506 String::new(),
1507 String::new(),
1508 format!("{}\n", authored(parts.integrate_note)),
1509 ),
1510 };
1511 authored(template)
1512 .replacen("RK_BRANCH_GRAMMAR", BRANCH_GRAMMAR, 1)
1513 .replacen("RK_SWEEP_NOTE", &format!("{sweep}{note}"), 1)
1514 .replacen("RK_TRUNK_COMMIT_GUARD", &commit_guard, 1)
1515 .replacen("RK_WORKTREE_GUARD", &guard, 1)
1516 .replacen("RK_TRUNK_PUSH_GUARD", &push_guard, 1)
1517}
1518
1519pub struct TrunkGuards<'a> {
1522 pub integration: Integration,
1524 pub trunk_commit: &'a str,
1526 pub trunk_push: &'a str,
1528 pub sweep_skip: &'a str,
1530 pub sweep_none: &'a str,
1532 pub integrate_note: &'a str,
1534}
1535
1536pub fn routing_block(mode: CheckoutMode, integration: Integration) -> Result<String, RkError> {
1543 Ok(compose_routing(
1544 embedded_block(AGENTS_BLOCK)?,
1545 embedded_block(routing_line(mode))?,
1546 embedded_block(integration_line(integration))?,
1547 ))
1548}
1549
1550pub fn glossary_block() -> Result<String, RkError> {
1556 Ok(compose_glossary(embedded_block(GLOSSARY_BLOCK)?))
1557}
1558
1559pub fn hooks_block(mode: CheckoutMode, integration: Integration) -> Result<String, RkError> {
1566 let guard = match mode {
1567 CheckoutMode::LinkedWorktree => Some(embedded_block(PRE_COMMIT_WORKTREE_GUARD)?),
1568 CheckoutMode::MainWorktree => None,
1569 };
1570 let parts = TrunkGuards {
1571 integration,
1572 trunk_commit: embedded_block(PRE_COMMIT_TRUNK_COMMIT_GUARD)?,
1573 trunk_push: embedded_block(PRE_COMMIT_TRUNK_PUSH_GUARD)?,
1574 sweep_skip: embedded_block(PRE_COMMIT_SWEEP_SKIP)?,
1575 sweep_none: embedded_block(PRE_COMMIT_SWEEP_NONE)?,
1576 integrate_note: embedded_block(PRE_COMMIT_INTEGRATE_NOTE)?,
1577 };
1578 Ok(compose_hooks(
1579 embedded_block(PRE_COMMIT_BLOCK)?,
1580 guard,
1581 &parts,
1582 ))
1583}
1584
1585fn block_template(
1588 destination: &str,
1589 mode: CheckoutMode,
1590 integration: Integration,
1591) -> Result<(String, Vec<String>), RkError> {
1592 match destination {
1593 AGENTS_DESTINATION => Ok((
1594 routing_block(mode, integration)?,
1595 vec![
1596 AGENTS_BLOCK.to_owned(),
1597 routing_line(mode).to_owned(),
1598 integration_line(integration).to_owned(),
1599 ],
1600 )),
1601 GLOSSARY_DESTINATION => Ok((glossary_block()?, vec![GLOSSARY_BLOCK.to_owned()])),
1602 HOOKS_DESTINATION => {
1603 let mut sources = vec![PRE_COMMIT_BLOCK.to_owned()];
1604 if mode == CheckoutMode::LinkedWorktree {
1605 sources.push(PRE_COMMIT_WORKTREE_GUARD.to_owned());
1606 }
1607 match integration {
1608 Integration::Forge => {
1609 sources.push(PRE_COMMIT_TRUNK_COMMIT_GUARD.to_owned());
1610 sources.push(PRE_COMMIT_TRUNK_PUSH_GUARD.to_owned());
1611 sources.push(PRE_COMMIT_SWEEP_SKIP.to_owned());
1612 }
1613 Integration::Local => {
1614 if mode == CheckoutMode::LinkedWorktree {
1615 sources.push(PRE_COMMIT_SWEEP_SKIP.to_owned());
1616 } else {
1617 sources.push(PRE_COMMIT_SWEEP_NONE.to_owned());
1618 }
1619 sources.push(PRE_COMMIT_INTEGRATE_NOTE.to_owned());
1620 }
1621 }
1622 Ok((hooks_block(mode, integration)?, sources))
1623 }
1624 other => Err(anyhow::anyhow!("{other} is not a block destination").into()),
1625 }
1626}
1627
1628#[must_use]
1630pub fn block_markers(destination: &str) -> Option<(&'static str, &'static str)> {
1631 match destination {
1632 AGENTS_DESTINATION | GLOSSARY_DESTINATION => Some((BLOCK_BEGIN, BLOCK_END)),
1633 HOOKS_DESTINATION => Some((HOOKS_BEGIN, HOOKS_END)),
1634 _ => None,
1635 }
1636}
1637
1638#[must_use]
1641pub fn extract_block<'a>(text: &'a str, begin: &str, end: &str) -> Option<&'a str> {
1642 let start = text.find(begin)?;
1643 let stop = text[start..].find(end)? + start + end.len();
1644 Some(&text[start..stop])
1645}
1646
1647#[must_use]
1654pub fn splice_marked_block(existing: Option<&[u8]>, block: &str) -> Vec<u8> {
1655 let block = block.as_bytes();
1656 let Some(text) = existing else {
1657 return [block, b"\n"].concat();
1658 };
1659 if let Some(start) = find(text, BLOCK_BEGIN.as_bytes())
1663 && let Some(offset) = find(&text[start..], BLOCK_END.as_bytes())
1664 {
1665 let stop = start + offset + BLOCK_END.len();
1666 return [&text[..start], block, &text[stop..]].concat();
1667 }
1668 let mut out = Vec::with_capacity(text.len() + block.len() + 3);
1672 out.extend_from_slice(text);
1673 if !text.ends_with(b"\n") {
1674 out.push(b'\n');
1675 }
1676 out.push(b'\n');
1677 out.extend_from_slice(block);
1678 out.push(b'\n');
1679 out
1680}
1681
1682pub fn splice_hooks_block(existing: Option<&str>, block: &str) -> Result<String, String> {
1695 let Some(text) = existing else {
1696 return Ok(format!("{HOOK_TYPES_LINE}\n\nrepos:\n{block}\n"));
1697 };
1698 if let Some(defect) = hooks_marker_defect(text) {
1699 return Err(defect);
1700 }
1701 if let Some(found) = extract_block(text, HOOKS_BEGIN, HOOKS_END) {
1702 return Ok(text.replacen(found, block, 1));
1703 }
1704 let mut out = String::with_capacity(text.len() + block.len() + 1);
1705 let mut placed = false;
1706 for line in text.split_inclusive('\n') {
1707 out.push_str(line);
1708 if !placed && line.trim_end() == "repos:" {
1709 if !out.ends_with('\n') {
1710 out.push('\n');
1711 }
1712 out.push_str(block);
1713 out.push('\n');
1714 placed = true;
1715 }
1716 }
1717 if placed {
1718 Ok(out)
1719 } else {
1720 Err(format!(
1721 "{HOOKS_DESTINATION} exists with no repos: line, so the hook block has nowhere to land"
1722 ))
1723 }
1724}
1725
1726#[must_use]
1736pub fn marker_defect(destination: &str, text: &str) -> Option<String> {
1737 let (begin, end) = block_markers(destination)?;
1738 let begins = text.matches(begin).count();
1739 let ends = text.matches(end).count();
1740 if begins > 1 || ends > 1 {
1741 return Some(format!(
1742 "{destination} carries more than one release-kit marker pair; release-kit owns exactly one block"
1743 ));
1744 }
1745 match (text.find(begin), text.find(end)) {
1746 (Some(begin), Some(end)) if end > begin => None,
1747 (None, None) => None,
1748 _ => Some(format!(
1749 "{destination} carries an unmatched or misordered release-kit marker, so the block's extent is ambiguous"
1750 )),
1751 }
1752}
1753
1754#[must_use]
1757pub fn hooks_marker_defect(text: &str) -> Option<String> {
1758 marker_defect(HOOKS_DESTINATION, text)
1759}
1760
1761fn propose_document(
1765 destination: &str,
1766 existing: Option<&[u8]>,
1767 region: &[u8],
1768) -> Result<Vec<u8>, String> {
1769 let block = String::from_utf8_lossy(region).into_owned();
1774 if let Some(text) = existing
1775 && let Some(defect) = marker_defect(destination, &String::from_utf8_lossy(text))
1776 {
1777 return Err(defect);
1778 }
1779 if destination == HOOKS_DESTINATION {
1780 let text = match existing {
1784 None => None,
1785 Some(bytes) => Some(std::str::from_utf8(bytes).map_err(|_| {
1786 format!(
1787 "{destination} is not UTF-8, so the hook block has nowhere to land without rewriting the target's bytes"
1788 )
1789 })?),
1790 };
1791 return splice_hooks_block(text, &block).map(String::into_bytes);
1792 }
1793 Ok(splice_marked_block(existing, &block))
1794}
1795
1796#[must_use]
1808pub fn nix_unsupported_shape(shape: &CrateShape) -> Option<String> {
1809 let Some(text) = shape.cargo_toml.as_deref() else {
1810 return Some(
1811 "the target has no readable Cargo.toml, which the seeded package expression reads; no Nix file lands".to_owned(),
1812 );
1813 };
1814 let Ok(table) = text.parse::<toml::Table>() else {
1815 return Some(
1816 "the target's Cargo.toml does not parse, and the seeded package expression reads it; no Nix file lands".to_owned(),
1817 );
1818 };
1819 if !table.contains_key("package") {
1820 return Some(
1821 "the target's Cargo.toml has no [package] table; the seed supports a single crate, so no Nix file lands".to_owned(),
1822 );
1823 }
1824 if !shape.cargo_lock {
1825 return Some(
1826 "the target has no Cargo.lock, which the seeded package expression builds from; commit one, then opt in".to_owned(),
1827 );
1828 }
1829 let implicit_bin = shape.main_rs
1830 && table
1831 .get("package")
1832 .and_then(toml::Value::as_table)
1833 .and_then(|package| package.get("autobins"))
1834 .and_then(toml::Value::as_bool)
1835 != Some(false);
1836 let explicit_bins = table.get("bin").and_then(toml::Value::as_array);
1837 if explicit_bins.is_none() && !implicit_bin {
1838 return Some(
1839 "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(),
1840 );
1841 }
1842 if let Some(bins) = explicit_bins {
1848 let required = bins
1849 .first()
1850 .and_then(toml::Value::as_table)
1851 .and_then(|bin| bin.get("required-features"))
1852 .and_then(toml::Value::as_array);
1853 if let Some(required) = required {
1854 let enabled = default_features(&table);
1855 let missing = required
1856 .iter()
1857 .filter_map(toml::Value::as_str)
1858 .any(|feature| !enabled.contains(feature));
1859 if missing {
1860 return Some(
1861 "the target's first [[bin]] entry requires features a default build does not enable; no Nix file lands".to_owned(),
1862 );
1863 }
1864 }
1865 }
1866 None
1867}
1868
1869fn dep_edge_suppresses(features: &toml::Table, name: &str) -> bool {
1872 let edge = format!("dep:{name}");
1873 features.values().any(|list| {
1874 list.as_array().is_some_and(|entries| {
1875 entries
1876 .iter()
1877 .filter_map(toml::Value::as_str)
1878 .any(|entry| entry == edge)
1879 })
1880 })
1881}
1882
1883fn is_optional_dependency(table: &toml::Table, name: &str) -> bool {
1886 ["dependencies", "build-dependencies"]
1887 .iter()
1888 .any(|section| {
1889 table
1890 .get(*section)
1891 .and_then(toml::Value::as_table)
1892 .and_then(|dependencies| dependencies.get(name))
1893 .and_then(toml::Value::as_table)
1894 .and_then(|dependency| dependency.get("optional"))
1895 .and_then(toml::Value::as_bool)
1896 == Some(true)
1897 })
1898}
1899
1900fn default_features(table: &toml::Table) -> std::collections::BTreeSet<String> {
1907 let Some(features) = table.get("features").and_then(toml::Value::as_table) else {
1908 return std::collections::BTreeSet::new();
1909 };
1910 let mut enabled = std::collections::BTreeSet::new();
1911 let mut queue = vec!["default".to_owned()];
1912 while let Some(name) = queue.pop() {
1913 if !enabled.insert(name.clone()) {
1914 continue;
1915 }
1916 if let Some(implies) = features.get(&name).and_then(toml::Value::as_array) {
1917 for implied in implies.iter().filter_map(toml::Value::as_str) {
1918 if implied.starts_with("dep:") || implied.contains("?/") {
1919 continue;
1923 }
1924 if let Some((package, _)) = implied.split_once('/') {
1925 let feature_exists =
1933 features.contains_key(package) || !dep_edge_suppresses(features, package);
1934 if is_optional_dependency(table, package) && feature_exists {
1935 queue.push(package.to_owned());
1936 }
1937 } else {
1938 queue.push(implied.to_owned());
1939 }
1940 }
1941 }
1942 }
1943 enabled
1944}
1945
1946#[must_use]
1954pub fn flake_pair_withheld(
1955 flake_recorded: bool,
1956 flake_nix_present: bool,
1957 flake_lock_present: bool,
1958) -> Option<String> {
1959 if flake_recorded {
1960 return None;
1961 }
1962 let present: Vec<&str> = [
1963 ("flake.nix", flake_nix_present),
1964 ("flake.lock", flake_lock_present),
1965 ]
1966 .into_iter()
1967 .filter_map(|(name, present)| present.then_some(name))
1968 .collect();
1969 if present.is_empty() {
1970 return None;
1971 }
1972 Some(format!(
1973 "the target already carries {}; its flake pair stays its own",
1974 present.join(" and ")
1975 ))
1976}
1977
1978#[must_use]
1988pub fn nix_withholding(
1989 nix: bool,
1990 evidence: &TargetEvidence,
1991) -> Option<(&'static [&'static str], String)> {
1992 if !nix {
1993 return None;
1994 }
1995 if let Some(reason) = nix_unsupported_shape(&evidence.crate_shape) {
1996 return Some((&NIX_DESTINATIONS[..], reason));
1997 }
1998 flake_pair_withheld(
1999 evidence.flake_recorded,
2000 evidence.flake_nix_present,
2001 evidence.flake_lock_present,
2002 )
2003 .map(|reason| (&NIX_WITHHOLDABLE[..], reason))
2004}
2005
2006#[cfg(test)]
2007mod tests {
2008 use super::{
2009 AGENTS_DESTINATION, BLOCK_BEGIN, BLOCK_DESTINATIONS, BLOCK_END, Candidate, Collision,
2010 CrateShape, GLOSSARY_DESTINATION, HOOK_TYPES_LINE, HOOKS_BEGIN, HOOKS_DESTINATION,
2011 HOOKS_END, Placement, Projection, ProjectionInput, TargetEvidence, extract_block,
2012 };
2013 use crate::landing::{Params, Style};
2014
2015 fn supported_shape() -> CrateShape {
2017 CrateShape {
2018 cargo_toml: Some("[package]\nname = \"widget\"\nversion = \"0.1.0\"\n".to_owned()),
2019 cargo_lock: true,
2020 main_rs: true,
2021 }
2022 }
2023
2024 fn input(evidence: TargetEvidence) -> ProjectionInput {
2025 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2026 params.set_nix_for_test(true);
2027 ProjectionInput { params, evidence }
2028 }
2029
2030 fn compute(evidence: TargetEvidence) -> Projection {
2031 Projection::compute(&input(evidence)).expect("the embedded pair projects")
2032 }
2033
2034 fn candidate<'a>(projection: &'a Projection, destination: &str) -> &'a Candidate {
2035 projection
2036 .candidates
2037 .iter()
2038 .find(|candidate| candidate.destination == destination)
2039 .expect("the destination projects")
2040 }
2041
2042 fn outside(bytes: &[u8], begin: &str, end: &str) -> (Vec<u8>, Vec<u8>) {
2044 let text = String::from_utf8_lossy(bytes);
2045 let start = text.find(begin).expect("the begin marker is present");
2046 let stop = text[start..].find(end).expect("the end marker is present") + start + end.len();
2047 (bytes[..start].to_vec(), bytes[stop..].to_vec())
2048 }
2049
2050 #[test]
2051 fn equal_projection_inputs_yield_byte_identical_projections() {
2052 let mut documents = std::collections::BTreeMap::new();
2053 documents.insert(
2054 AGENTS_DESTINATION.to_owned(),
2055 b"# Widget\n\nOwn rules.\n".to_vec(),
2056 );
2057 let evidence = TargetEvidence {
2058 documents,
2059 crate_shape: supported_shape(),
2060 ..TargetEvidence::default()
2061 };
2062 let first = input(evidence.clone());
2063 let second = input(evidence);
2064 assert_eq!(first, second, "the inputs are values and compare equal");
2065 let a = Projection::compute(&first).expect("the pair projects");
2066 let b = Projection::compute(&second).expect("the pair projects");
2067 assert_eq!(a.candidates.len(), b.candidates.len());
2068 for (x, y) in a.candidates.iter().zip(&b.candidates) {
2069 assert_eq!(x.destination, y.destination);
2070 assert_eq!(x.kind, y.kind);
2071 assert_eq!(x.placement, y.placement);
2072 assert_eq!(x.bytes, y.bytes, "{}", x.destination);
2073 assert_eq!(x.region, y.region, "{}", x.destination);
2074 assert_eq!(x.sources, y.sources, "{}", x.destination);
2075 }
2076 assert_eq!(a, b);
2077 let destinations: Vec<&str> = a
2078 .candidates
2079 .iter()
2080 .map(|candidate| candidate.destination.as_str())
2081 .collect();
2082 let mut sorted = destinations.clone();
2083 sorted.sort_unstable();
2084 assert_eq!(destinations, sorted, "candidates sort by destination");
2085 assert!(a.omissions.is_empty(), "{:?}", a.omissions);
2086 assert!(a.collisions.is_empty(), "{:?}", a.collisions);
2087 }
2088
2089 #[test]
2093 fn the_scorecard_destination_projects_only_under_the_opt_in() {
2094 use super::{Kind, SCORECARD_DESTINATIONS, kind_of};
2095 let destination = SCORECARD_DESTINATIONS[0];
2096 assert_eq!(kind_of(destination), Some(Kind::Rendered));
2097
2098 let project = |scorecard: bool| {
2099 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2100 params.set_scorecard_for_test(scorecard);
2101 Projection::compute(&ProjectionInput {
2102 params,
2103 evidence: TargetEvidence::default(),
2104 })
2105 .expect("the embedded pair projects")
2106 };
2107
2108 let off = project(false);
2109 assert!(
2110 !off.candidates
2111 .iter()
2112 .any(|candidate| candidate.destination == destination),
2113 "off by default, and an absent candidate is no omission"
2114 );
2115 assert!(off.omissions.is_empty(), "{:?}", off.omissions);
2116
2117 let on = project(true);
2118 let candidate = candidate(&on, destination);
2119 assert_eq!(candidate.kind, Kind::Rendered);
2120 assert_eq!(candidate.placement, Placement::Whole);
2121 let text = String::from_utf8_lossy(&candidate.bytes);
2122 assert!(!text.contains("RK_"), "a token survived: {text}");
2123 }
2124
2125 #[test]
2130 fn the_licence_judgment_reads_what_every_reader_obtains() {
2131 use super::licence_states_an_open_source_codebase as approved;
2132 for expression in [
2133 "MIT",
2134 "Apache-2.0",
2135 "MIT OR Apache-2.0",
2136 "MIT AND Apache-2.0",
2137 "(MIT OR Apache-2.0) AND ISC",
2138 "Apache-2.0 WITH LLVM-exception OR MIT",
2139 "GPL-3.0+",
2140 ] {
2141 assert!(approved(expression), "{expression} is OSI-approved");
2142 }
2143 for expression in [
2148 "MIT AND CC-BY-4.0",
2149 "CC-BY-4.0 AND MIT",
2150 "MIT AND (CC-BY-4.0 OR CC-BY-SA-4.0)",
2151 "(MIT OR CC-BY-4.0) AND MIT",
2152 "MIT OR Apache-2.0 AND CC-BY-4.0",
2153 "Apache-2.0 WITH LLVM-exception AND CC-BY-SA-3.0",
2154 ] {
2155 assert!(approved(expression), "{expression} states open source");
2156 }
2157 for expression in [
2158 "",
2159 " ",
2160 "LicenseRef-proprietary",
2161 "MIT AND LicenseRef-proprietary",
2162 "SEE LICENSE IN COPYING",
2163 "CC-BY-4.0",
2164 "DocumentRef-spdx:LicenseRef-proprietary",
2165 ] {
2166 assert!(!approved(expression), "{expression} is not recognized");
2167 }
2168 for expression in [
2173 "MIT OR CC-BY-4.0",
2174 "CC-BY-4.0 AND CC-BY-SA-4.0",
2175 "CC-BY-4.0 AND LicenseRef-proprietary",
2176 "CC0-1.0",
2177 "MIT AND CC-BY-4.0 AND LicenseRef-proprietary",
2178 ] {
2179 assert!(!approved(expression), "{expression} grants no code terms");
2180 }
2181 assert!(
2186 !approved("CC-BY-4.0 OR CC-BY-SA-4.0 AND MIT"),
2187 "AND binds tighter than OR"
2188 );
2189 }
2190
2191 #[test]
2197 fn the_licence_judgment_holds_the_expression_to_the_spdx_grammar() {
2198 use super::licence_states_an_open_source_codebase as approved;
2199 for expression in [
2204 "MIT OR",
2205 "OR MIT",
2206 "MIT AND",
2207 "MIT WITH",
2208 "WITH LLVM-exception",
2209 "(MIT",
2210 "MIT)",
2211 "MIT Apache-2.0",
2212 "()",
2213 "(MIT OR Apache-2.0",
2214 "MIT OR (Apache-2.0",
2215 "MIT OR ()",
2216 "AND",
2217 "(",
2218 ")",
2219 "MIT WITH AND ISC",
2220 "MIT OR OR ISC",
2221 "MIT @ Apache-2.0",
2222 ] {
2223 assert!(!approved(expression), "{expression} is malformed");
2224 }
2225 for expression in [
2227 "MIT AND (Apache-2.0 OR ISC)",
2228 "((MIT))",
2229 "Apache-2.0 WITH LLVM-exception AND ISC",
2230 "(Apache-2.0 WITH LLVM-exception)",
2231 ] {
2232 assert!(approved(expression), "{expression} is well formed");
2233 }
2234 for expression in [
2239 "mit",
2240 "MiT",
2241 "apache-2.0 OR mit",
2242 "APACHE-2.0 WITH llvm-exception",
2243 ] {
2244 assert!(
2245 approved(expression),
2246 "{expression} names an approved licence"
2247 );
2248 }
2249 for expression in [
2253 "MIT or Apache-2.0",
2254 "MIT and Apache-2.0",
2255 "MIT with LLVM-exception",
2256 ] {
2257 assert!(!approved(expression), "{expression} carries no operator");
2258 }
2259 for expression in [
2263 "MIT WITH definitely-not-an-spdx-exception",
2264 "MIT WITH MIT",
2265 "MIT WITH Apache-2.0",
2266 ] {
2267 assert!(!approved(expression), "{expression} names no exception");
2268 }
2269 for expression in [
2273 "GPL-2.0-only WITH GCC-exception-2.0",
2274 "GPL-2.0-or-later WITH Classpath-exception-2.0",
2275 "Apache-2.0 WITH Swift-exception",
2276 "GPL-3.0-only WITH Autoconf-exception-generic",
2277 ] {
2278 assert!(approved(expression), "{expression} names a real exception");
2279 }
2280 }
2281
2282 #[test]
2288 fn a_recorded_provider_its_pair_cannot_run_is_named() {
2289 use super::{Provider, code_scanning_incompatibility};
2290
2291 assert!(code_scanning_incompatibility(None, Some("bash"), Some("gitlab")).is_none());
2292 assert!(
2293 code_scanning_incompatibility(Some(Provider::Semgrep), Some("rust"), Some("gitlab"))
2294 .is_none()
2295 );
2296 assert!(
2297 code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("github"))
2298 .is_none()
2299 );
2300
2301 let bash =
2302 code_scanning_incompatibility(Some(Provider::Semgrep), Some("bash"), Some("github"))
2303 .expect("a binding with no scanner is named");
2304 assert!(bash.contains("bash binding"), "{bash}");
2305 let gitlab =
2306 code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("gitlab"))
2307 .expect("codeql on gitlab is named");
2308 assert!(gitlab.contains("codeql"), "{gitlab}");
2309 let release_less =
2310 code_scanning_incompatibility(Some(Provider::Semgrep), None, Some("github"))
2311 .expect("no driver is named");
2312 assert!(
2313 release_less.contains("no automatic release driver"),
2314 "{release_less}"
2315 );
2316
2317 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2320 params.set_code_scanning_for_test(Some(Provider::Semgrep));
2321 let clean = Projection::compute(&ProjectionInput {
2322 params: params.clone(),
2323 evidence: TargetEvidence::default(),
2324 })
2325 .expect("the pair projects");
2326 assert!(
2327 clean.record_defects.is_empty(),
2328 "{:?}",
2329 clean.record_defects
2330 );
2331 }
2332
2333 #[test]
2337 fn the_code_scanning_destinations_follow_the_recorded_provider() {
2338 use super::{
2339 CODE_SCANNING_DESTINATIONS, Kind, Provider, code_scanning_licence_refusal, kind_of,
2340 };
2341 for (destination, _) in CODE_SCANNING_DESTINATIONS {
2342 assert_eq!(kind_of(destination), Some(Kind::Rendered), "{destination}");
2343 }
2344
2345 let project = |provider: Option<Provider>| {
2346 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2347 params.set_code_scanning_for_test(provider);
2348 Projection::compute(&ProjectionInput {
2349 params,
2350 evidence: TargetEvidence {
2351 crate_shape: CrateShape {
2352 cargo_toml: Some(
2353 "[package]\nname = \"widget\"\nlicense = \"MIT\"\n".to_owned(),
2354 ),
2355 ..CrateShape::default()
2356 },
2357 ..TargetEvidence::default()
2358 },
2359 })
2360 .expect("the embedded pair projects")
2361 };
2362 let landed = |projection: &Projection, destination: &str| {
2363 projection
2364 .candidates
2365 .iter()
2366 .any(|candidate| candidate.destination == destination)
2367 };
2368
2369 let off = project(None);
2370 for (destination, _) in CODE_SCANNING_DESTINATIONS {
2371 assert!(!landed(&off, destination), "{destination}");
2372 }
2373 assert!(off.licence_refusal.is_none());
2374
2375 let codeql = project(Some(Provider::CodeQl));
2376 assert!(landed(
2377 &codeql,
2378 ".github/workflows/code-scanning-codeql.yml"
2379 ));
2380 assert!(!landed(
2381 &codeql,
2382 ".github/workflows/code-scanning-semgrep.yml"
2383 ));
2384 assert!(codeql.licence_refusal.is_none(), "MIT satisfies the terms");
2385
2386 let semgrep = project(Some(Provider::Semgrep));
2387 assert!(landed(
2388 &semgrep,
2389 ".github/workflows/code-scanning-semgrep.yml"
2390 ));
2391 assert!(!landed(
2392 &semgrep,
2393 ".github/workflows/code-scanning-codeql.yml"
2394 ));
2395
2396 let proprietary = CrateShape {
2398 cargo_toml: Some("[package]\nlicense = \"LicenseRef-proprietary\"\n".to_owned()),
2399 ..CrateShape::default()
2400 };
2401 assert!(
2402 code_scanning_licence_refusal(Some(Provider::Semgrep), Some("rust"), &proprietary)
2403 .is_none()
2404 );
2405 let refusal =
2406 code_scanning_licence_refusal(Some(Provider::CodeQl), Some("rust"), &proprietary)
2407 .expect("codeql refuses a licence its terms do not cover");
2408 assert!(refusal.contains("LicenseRef-proprietary"), "{refusal}");
2409 assert!(refusal.contains("semgrep"), "{refusal}");
2410 let bash =
2413 code_scanning_licence_refusal(Some(Provider::CodeQl), Some("bash"), &proprietary)
2414 .expect("an unread binding refuses");
2415 assert!(bash.contains("bash binding"), "{bash}");
2416 }
2417
2418 #[test]
2424 fn the_projection_performs_no_filesystem_git_environment_clock_registry_or_network_read() {
2425 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/projection.rs");
2426 let text = std::fs::read_to_string(&path).expect("the source reads");
2427 let production = text.split("#[cfg(test)]").next().unwrap_or("");
2428 let needles = [
2429 "std::fs",
2430 "std::env",
2431 "std::process",
2432 "std::time",
2433 "SystemTime",
2434 "Instant",
2435 "std::net",
2436 "Command::new",
2437 "registry::",
2438 "curl",
2439 "reqwest",
2440 "blob(",
2441 ];
2442 let mut hits = Vec::new();
2443 for (index, line) in production.lines().enumerate() {
2444 if line.trim_start().starts_with("//") {
2445 continue;
2446 }
2447 for needle in needles {
2448 if line.contains(needle) {
2449 hits.push(format!("src/projection.rs:{}: {needle}", index + 1));
2450 }
2451 }
2452 }
2453 assert!(
2454 hits.is_empty(),
2455 "the projection reads beyond its inputs: {hits:?}"
2456 );
2457 }
2458
2459 #[test]
2460 #[allow(
2461 clippy::too_many_lines,
2462 reason = "one test walks the three marked destinations and the three unmarked shapes"
2463 )]
2464 fn marked_region_projection_preserves_every_target_byte_outside_the_markers() {
2465 let agents_before = "# Widget\n\nOperator prose above.\n\n";
2466 let agents_after = "\n\n## Our rules\n\nOperator prose below. \n";
2467 let glossary_before = "# Glossary\n\n- `spike` is a throwaway branch.\n\n";
2468 let glossary_after = "\n\n## More terms\n\n- `own` is ours.";
2469 let hooks_before = "default_install_hook_types: [pre-commit]\n\nrepos:\n";
2470 let hooks_after =
2471 "\n - repo: https://example.com/own\n rev: v1\n hooks:\n - id: own\n";
2472 let stale = |begin: &str, end: &str| format!("{begin}\nstale block\n{end}");
2473 let mut documents = std::collections::BTreeMap::new();
2474 documents.insert(
2475 AGENTS_DESTINATION.to_owned(),
2476 format!(
2477 "{agents_before}{}{agents_after}",
2478 stale(BLOCK_BEGIN, BLOCK_END)
2479 )
2480 .into_bytes(),
2481 );
2482 documents.insert(
2483 GLOSSARY_DESTINATION.to_owned(),
2484 format!(
2485 "{glossary_before}{}{glossary_after}",
2486 stale(BLOCK_BEGIN, BLOCK_END)
2487 )
2488 .into_bytes(),
2489 );
2490 documents.insert(
2491 HOOKS_DESTINATION.to_owned(),
2492 format!(
2493 "{hooks_before}{}{hooks_after}",
2494 stale(HOOKS_BEGIN, HOOKS_END)
2495 )
2496 .into_bytes(),
2497 );
2498 let projection = compute(TargetEvidence {
2499 documents: documents.clone(),
2500 crate_shape: supported_shape(),
2501 ..TargetEvidence::default()
2502 });
2503 assert!(
2504 projection.collisions.is_empty(),
2505 "{:?}",
2506 projection.collisions
2507 );
2508 for (destination, before, after) in [
2509 (AGENTS_DESTINATION, agents_before, agents_after),
2510 (GLOSSARY_DESTINATION, glossary_before, glossary_after),
2511 (HOOKS_DESTINATION, hooks_before, hooks_after),
2512 ] {
2513 let candidate = candidate(&projection, destination);
2514 let Placement::Region { begin, end } = candidate.placement else {
2515 panic!("{destination} is a region");
2516 };
2517 let region = candidate
2518 .region
2519 .as_deref()
2520 .expect("a region carries its block");
2521 let (head, tail) = outside(&candidate.bytes, begin, end);
2522 assert_eq!(
2523 head,
2524 before.as_bytes(),
2525 "{destination}: bytes before the markers"
2526 );
2527 assert_eq!(
2528 tail,
2529 after.as_bytes(),
2530 "{destination}: bytes after the markers"
2531 );
2532 let inside = &candidate.bytes[head.len()..candidate.bytes.len() - tail.len()];
2533 assert_eq!(
2534 inside, region,
2535 "{destination}: the region is the rendered block"
2536 );
2537 let (existing_head, existing_tail) = outside(&documents[destination], begin, end);
2538 assert_eq!(head, existing_head);
2539 assert_eq!(tail, existing_tail);
2540 }
2541
2542 let own_hooks =
2546 "repos:\n - repo: https://example.com/own\n rev: v1\n hooks:\n - id: own\n";
2547 let own_agents = "# Widget\n\nOwn rules.";
2548 let mut documents = std::collections::BTreeMap::new();
2549 documents.insert(HOOKS_DESTINATION.to_owned(), own_hooks.as_bytes().to_vec());
2550 documents.insert(
2551 AGENTS_DESTINATION.to_owned(),
2552 own_agents.as_bytes().to_vec(),
2553 );
2554 let projection = compute(TargetEvidence {
2555 documents,
2556 crate_shape: supported_shape(),
2557 ..TargetEvidence::default()
2558 });
2559 assert!(
2560 projection.collisions.is_empty(),
2561 "{:?}",
2562 projection.collisions
2563 );
2564 let hooks = candidate(&projection, HOOKS_DESTINATION);
2565 let hooks_text = String::from_utf8_lossy(&hooks.bytes);
2566 let region = String::from_utf8_lossy(hooks.region.as_deref().expect("a region"));
2567 assert!(
2568 hooks_text.starts_with(&format!(
2569 "repos:\n{region}\n - repo: https://example.com/own"
2570 )),
2571 "{hooks_text}"
2572 );
2573 assert!(!hooks_text.contains(HOOK_TYPES_LINE));
2574 let agents = candidate(&projection, AGENTS_DESTINATION);
2575 assert!(agents.bytes.starts_with(own_agents.as_bytes()));
2576 assert_eq!(
2577 extract_block(
2578 &String::from_utf8_lossy(&agents.bytes),
2579 BLOCK_BEGIN,
2580 BLOCK_END
2581 )
2582 .map(str::as_bytes),
2583 agents.region.as_deref()
2584 );
2585 let glossary = candidate(&projection, GLOSSARY_DESTINATION);
2586 let region = glossary.region.as_deref().expect("a region");
2587 assert_eq!(
2588 glossary.bytes,
2589 [region, b"\n"].concat(),
2590 "an absent file is fresh"
2591 );
2592 }
2593
2594 #[test]
2600 fn a_hook_document_that_is_not_utf8_collides_instead_of_being_rewritten() {
2601 let mut documents = std::collections::BTreeMap::new();
2602 let mut invalid = b"repos:\n# own \xff above\n".to_vec();
2603 invalid.extend_from_slice(format!("{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n").as_bytes());
2604 invalid.extend_from_slice(b" - repo: local \xff below\n");
2605 documents.insert(HOOKS_DESTINATION.to_owned(), invalid);
2606 let mut agents = b"# Widget r\xe9sum\xe9\n\n".to_vec();
2607 agents.extend_from_slice(format!("{BLOCK_BEGIN}\nstale\n{BLOCK_END}\n\n").as_bytes());
2608 agents.extend_from_slice(b"r\xe9sum\xe9\n");
2609 documents.insert(AGENTS_DESTINATION.to_owned(), agents.clone());
2610 let projection = compute(TargetEvidence {
2611 documents,
2612 crate_shape: supported_shape(),
2613 ..TargetEvidence::default()
2614 });
2615 let collided: Vec<&str> = projection
2616 .collisions
2617 .iter()
2618 .map(|c| c.destination.as_str())
2619 .collect();
2620 assert_eq!(collided, [HOOKS_DESTINATION]);
2621 assert!(
2622 projection.collisions[0].reason.contains("not UTF-8"),
2623 "{}",
2624 projection.collisions[0].reason
2625 );
2626 assert!(
2627 !projection
2628 .candidates
2629 .iter()
2630 .any(|c| c.destination == HOOKS_DESTINATION),
2631 "a colliding destination projects no candidate"
2632 );
2633 let agents = candidate(&projection, AGENTS_DESTINATION);
2634 assert!(
2635 agents.bytes.starts_with(b"# Widget r\xe9sum\xe9\n\n"),
2636 "{:?}",
2637 agents.bytes
2638 );
2639 assert!(
2640 agents.bytes.ends_with(b"\n\nr\xe9sum\xe9\n"),
2641 "{:?}",
2642 agents.bytes
2643 );
2644 assert!(
2645 !agents.bytes.contains(&0xEF),
2646 "a replacement character landed"
2647 );
2648
2649 let mut documents = std::collections::BTreeMap::new();
2650 let valid =
2651 format!("repos:\n# own above\n{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n - repo: local\n");
2652 documents.insert(HOOKS_DESTINATION.to_owned(), valid.into_bytes());
2653 let projection = compute(TargetEvidence {
2654 documents,
2655 crate_shape: supported_shape(),
2656 ..TargetEvidence::default()
2657 });
2658 assert!(
2659 projection.collisions.is_empty(),
2660 "{:?}",
2661 projection.collisions
2662 );
2663 let hooks = candidate(&projection, HOOKS_DESTINATION);
2664 let text = String::from_utf8(hooks.bytes.clone()).expect("a valid document stays text");
2665 assert!(text.starts_with("repos:\n# own above\n"), "{text}");
2666 assert!(text.ends_with("\n - repo: local\n"), "{text}");
2667 assert!(!text.contains("stale"), "the region is replaced: {text}");
2668 }
2669
2670 #[test]
2674 fn a_whole_file_colliding_with_a_marked_region_names_both_source_paths() {
2675 let files: Vec<(String, &[u8])> = vec![
2676 ("snippets/_shared/github/SECURITY.md".to_owned(), b"policy"),
2677 ("snippets/rust/github/AGENTS.md".to_owned(), b"whole"),
2678 ];
2679 let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
2680 .expect_err("a whole file at a block destination refuses");
2681 let text = err.to_string();
2682 assert!(text.contains("snippets/rust/github/AGENTS.md"), "{text}");
2683 assert!(text.contains(super::AGENTS_BLOCK), "{text}");
2684 assert!(text.contains(super::AGENTS_LINE_WORKTREE), "{text}");
2685 assert!(text.contains("embedded sources are defective"), "{text}");
2686 }
2687
2688 #[test]
2689 fn duplicate_whole_file_destinations_and_overlapping_marked_regions_refuse_with_the_conflicting_source_names()
2690 {
2691 let files: Vec<(String, &[u8])> = vec![
2694 ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
2695 ("snippets/rust/github/SECURITY.md".to_owned(), b"pair"),
2696 ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
2697 ];
2698 let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
2699 .expect_err("a doubled destination refuses");
2700 let text = err.to_string();
2701 assert!(
2702 text.contains("snippets/_shared/github/SECURITY.md"),
2703 "{text}"
2704 );
2705 assert!(text.contains("snippets/rust/github/SECURITY.md"), "{text}");
2706 assert!(text.contains("embedded sources are defective"), "{text}");
2707
2708 let clean: Vec<(String, &[u8])> = vec![
2709 ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
2710 ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
2711 ];
2712 let projection = Projection::compute_over(&clean, &input(TargetEvidence::default()))
2713 .expect("a clean list projects");
2714 let whole: Vec<&str> = projection
2715 .candidates
2716 .iter()
2717 .filter(|c| c.placement == Placement::Whole)
2718 .map(|c| c.destination.as_str())
2719 .collect();
2720 assert_eq!(whole, ["SECURITY.md", "release-plz.toml"]);
2721 assert_eq!(
2722 projection
2723 .candidates
2724 .iter()
2725 .find(|c| c.destination == "SECURITY.md")
2726 .map(|c| c.sources.clone()),
2727 Some(vec!["snippets/_shared/github/SECURITY.md".to_owned()])
2728 );
2729
2730 let doubled = format!("{BLOCK_BEGIN}\na\n{BLOCK_END}\n{BLOCK_BEGIN}\nb\n{BLOCK_END}\n");
2731 let unmatched = format!("repos:\n{HOOKS_BEGIN}\n - repo: local\n");
2732 let misordered = format!("# G\n{BLOCK_END}\n{BLOCK_BEGIN}\n");
2733 let mut documents = std::collections::BTreeMap::new();
2734 documents.insert(AGENTS_DESTINATION.to_owned(), doubled.into_bytes());
2735 documents.insert(HOOKS_DESTINATION.to_owned(), unmatched.into_bytes());
2736 documents.insert(GLOSSARY_DESTINATION.to_owned(), misordered.into_bytes());
2737 let projection = compute(TargetEvidence {
2738 documents,
2739 crate_shape: supported_shape(),
2740 ..TargetEvidence::default()
2741 });
2742 let mut collided: Vec<&str> = projection
2743 .collisions
2744 .iter()
2745 .map(|Collision { destination, .. }| destination.as_str())
2746 .collect();
2747 collided.sort_unstable();
2748 let mut expected = BLOCK_DESTINATIONS.to_vec();
2749 expected.sort_unstable();
2750 assert_eq!(collided, expected);
2751 for collision in &projection.collisions {
2752 assert!(
2753 collision.reason.contains(&collision.destination),
2754 "{collision:?}"
2755 );
2756 assert!(
2757 !projection
2758 .candidates
2759 .iter()
2760 .any(|candidate| candidate.destination == collision.destination),
2761 "{} collided and still projects",
2762 collision.destination
2763 );
2764 }
2765 let agents = projection
2766 .collisions
2767 .iter()
2768 .find(|c| c.destination == AGENTS_DESTINATION)
2769 .expect("the doubled document collides");
2770 assert!(agents.reason.contains("more than one"), "{}", agents.reason);
2771 let hooks = projection
2772 .collisions
2773 .iter()
2774 .find(|c| c.destination == HOOKS_DESTINATION)
2775 .expect("the unmatched document collides");
2776 assert!(hooks.reason.contains("unmatched"), "{}", hooks.reason);
2777 }
2778}