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 PUSH_GUARD_TOKEN: &[u8] = b" # RK_PUSH_GUARD";
1175
1176pub const REQUIRED_CHECK_TOKEN: &[u8] = b"RK_REQUIRED_CHECK";
1178
1179pub const REQUIRED_WORKFLOW_TOKEN: &[u8] = b"RK_REQUIRED_WORKFLOW";
1181
1182pub const BRANCH_SHAPE_TOKEN: &[u8] = b"RK_BRANCH_SHAPE";
1184
1185pub const REQUEST_JOB_TOKEN: &[u8] = b"RK_REQUEST_JOB";
1187
1188pub const RELEASE_GATE_TRIGGER: &str = "blocks/release-gate-trigger.yaml.in";
1190
1191pub const RELEASE_GATE_JOB: &str = "blocks/release-gate-job.yaml.in";
1193
1194#[must_use]
1201pub fn release_driver_shape(driver: Option<&str>) -> Option<(&'static str, &'static str)> {
1202 match driver {
1203 Some("rust") => Some(("release-plz-", "release-plz-pr")),
1206 Some("bash") => Some(("chore/release-v", "release-request")),
1208 Some("python") => Some((
1212 "release-please--branches--RK_TRUNK_BRANCH",
1213 "release-please-pr",
1214 )),
1215 _ => None,
1216 }
1217}
1218
1219#[must_use]
1230pub fn release_gate_spans(driver: Option<&str>) -> [(&'static [u8], &'static [u8]); 3] {
1231 let arm: (&[u8], &[u8]) = if driver == Some("bash") {
1235 (
1236 b"\n # RK_GATE_ARM_BEGIN",
1237 b"\n # RK_GATE_ARM_END",
1238 )
1239 } else {
1240 (b"\n# RK_GATE_ARM_BEGIN", b"\n# RK_GATE_ARM_END")
1241 };
1242 [
1243 (b"\n# RK_GATE_TRIGGER_BEGIN", b"\n# RK_GATE_TRIGGER_END"),
1244 arm,
1245 (b"\n# RK_GATE_JOB_BEGIN", b"\n# RK_GATE_JOB_END"),
1246 ]
1247}
1248
1249#[must_use]
1257fn release_gates(params: &Params) -> bool {
1258 params.forge() == Some("github")
1259 && params.integration() == crate::landing::Integration::Local
1260 && params.release_mode() == ReleaseMode::Automatic
1261 && params.style() == Some(crate::landing::Style::Trunk)
1262 && !params.required_check().is_empty()
1263 && !params.required_workflow().is_empty()
1264 && release_driver_shape(params.driver()).is_some()
1265}
1266
1267fn release_gate_replacements(params: &Params) -> Result<[Option<Vec<u8>>; 3], RkError> {
1279 if !release_gates(params) {
1280 return Ok([None, None, None]);
1281 }
1282 let opened = |block: &str| -> Result<Vec<u8>, RkError> {
1285 let text = embedded_block(block)?;
1286 Ok(substitute_tokens(
1287 format!("\n{}", text.trim_end_matches('\n')).as_bytes(),
1288 params,
1289 ))
1290 };
1291 Ok([
1292 Some(opened(RELEASE_GATE_TRIGGER)?),
1293 Some(Vec::new()),
1296 Some(opened(RELEASE_GATE_JOB)?),
1297 ])
1298}
1299
1300pub const SECURITY_SPANS: [(&[u8], &[u8]); 3] = [
1311 (
1312 b"<!--RK_SECURITY_CONTACT_BEGIN-->",
1313 b"<!--RK_SECURITY_CONTACT_END-->",
1314 ),
1315 (
1316 b"<!--RK_SECURITY_RESPONSE_BEGIN-->",
1317 b"<!--RK_SECURITY_RESPONSE_END-->",
1318 ),
1319 (
1320 b"<!--RK_SECURITY_DEADLINE_BEGIN-->",
1321 b"<!--RK_SECURITY_DEADLINE_END-->",
1322 ),
1323];
1324
1325fn acknowledgment(response: &str) -> String {
1328 format!("Maintainers acknowledge a report within {response}.")
1329}
1330
1331const DISCLOSURE_ONLY: &[u8] = b"This policy commits to no disclosure deadline.";
1335
1336fn security_replacements(params: &Params) -> [Option<Vec<u8>>; 3] {
1339 let contact = (!params.security_contact().is_empty())
1340 .then(|| params.security_contact().as_bytes().to_vec());
1341 let promised = params.security_response() != crate::config::RESPONSE_DEFAULT;
1342 [
1343 contact,
1344 promised.then(|| acknowledgment(params.security_response()).into_bytes()),
1345 promised.then(|| DISCLOSURE_ONLY.to_vec()),
1346 ]
1347}
1348
1349fn replace_span(baseline: &[u8], begin: &[u8], end: &[u8], value: Option<&[u8]>) -> Vec<u8> {
1355 let ordered = find(baseline, begin)
1356 .zip(find(baseline, end))
1357 .filter(|(start, stop)| stop > start);
1358 let Some((start, stop)) = ordered else {
1359 return baseline.to_vec();
1360 };
1361 let mut out = Vec::with_capacity(baseline.len());
1362 out.extend_from_slice(&baseline[..start]);
1363 out.extend_from_slice(value.unwrap_or_else(|| &baseline[start + begin.len()..stop]));
1364 out.extend_from_slice(&baseline[stop + end.len()..]);
1365 out
1366}
1367
1368#[must_use]
1386pub fn render(baseline: &[u8], params: &Params) -> Vec<u8> {
1387 let mut out = substitute_tokens(baseline, params);
1388 if let Ok(values) = release_gate_replacements(params) {
1394 for ((begin, end), value) in release_gate_spans(params.driver()).iter().zip(values) {
1395 out = replace_span(&out, begin, end, value.as_deref());
1396 }
1397 }
1398 for ((begin, end), value) in SECURITY_SPANS.iter().zip(security_replacements(params)) {
1399 out = replace_span(&out, begin, end, value.as_deref());
1400 }
1401 out
1402}
1403
1404#[must_use]
1409fn substitute_tokens(baseline: &[u8], params: &Params) -> Vec<u8> {
1410 let repo = params.repo();
1411 let owner = repo.split('/').next().unwrap_or(repo);
1412 let mut out = substitute(baseline, OWNER_TOKEN, owner.as_bytes());
1413 if let Some(style) = params.style() {
1414 out = substitute(&out, STYLE_TOKEN, style.as_str().as_bytes());
1415 }
1416 out = substitute(&out, SCOPE_SHAPE_TOKEN, SCOPE_SHAPE.as_bytes());
1417 let (shape, job) = release_driver_shape(params.driver()).unwrap_or_default();
1422 out = substitute(&out, BRANCH_SHAPE_TOKEN, shape.as_bytes());
1423 out = substitute(&out, REQUEST_JOB_TOKEN, job.as_bytes());
1424 out = substitute(&out, TRUNK_BRANCH_TOKEN, params.trunk().as_bytes());
1425 let escaped = params.line_prefix().replace('/', "\\/");
1426 out = substitute(&out, LINE_PREFIX_RE_TOKEN, escaped.as_bytes());
1427 out = substitute(&out, LINE_PREFIX_TOKEN, params.line_prefix().as_bytes());
1428 out = substitute(
1429 &out,
1430 REQUIRED_CHECK_TOKEN,
1431 params.required_check().as_bytes(),
1432 );
1433 out = substitute(
1434 &out,
1435 REQUIRED_WORKFLOW_TOKEN,
1436 params.required_workflow().as_bytes(),
1437 );
1438 let guard: &[u8] = if release_gates(params) {
1441 b" && github.event_name == 'push'"
1442 } else {
1443 b""
1444 };
1445 out = substitute(&out, PUSH_GUARD_TOKEN, guard);
1446 out = substitute(&out, REPO_TOKEN, repo.as_bytes());
1447 out
1448}
1449
1450#[must_use]
1452pub fn substitute(baseline: &[u8], token: &[u8], value: &[u8]) -> Vec<u8> {
1453 let mut out = Vec::with_capacity(baseline.len());
1454 let mut rest = baseline;
1455 while let Some(at) = find(rest, token) {
1456 out.extend_from_slice(&rest[..at]);
1457 out.extend_from_slice(value);
1458 rest = &rest[at + token.len()..];
1459 }
1460 out.extend_from_slice(rest);
1461 out
1462}
1463
1464fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1466 haystack
1467 .windows(needle.len())
1468 .position(|window| window == needle)
1469}
1470
1471pub const AGENTS_DESTINATION: &str = "AGENTS.md";
1473
1474pub const BLOCK_BEGIN: &str = "<!-- BEGIN release-kit -->";
1476
1477pub const BLOCK_END: &str = "<!-- END release-kit -->";
1479
1480pub const GLOSSARY_DESTINATION: &str = "GLOSSARY.md";
1485
1486pub const HOOKS_DESTINATION: &str = ".pre-commit-config.yaml";
1488
1489pub const BLOCK_DESTINATIONS: [&str; 3] =
1495 [AGENTS_DESTINATION, GLOSSARY_DESTINATION, HOOKS_DESTINATION];
1496
1497pub const HOOKS_BEGIN: &str = "# BEGIN release-kit";
1499
1500pub const HOOKS_END: &str = "# END release-kit";
1502
1503pub const HOOK_TYPES_LINE: &str = "default_install_hook_types: [pre-commit, commit-msg, pre-push]";
1507
1508pub const AGENTS_BLOCK: &str = "blocks/agents-block.md.in";
1510
1511pub const GLOSSARY_BLOCK: &str = "blocks/glossary.md.in";
1513
1514pub const AGENTS_LINE_WORKTREE: &str = "blocks/agents-line-worktree.md.in";
1516
1517pub const AGENTS_LINE_BRANCHES: &str = "blocks/agents-line-branches.md.in";
1519
1520pub const AGENTS_LINE_INTEGRATION_FORGE: &str = "blocks/agents-line-integration-forge.md.in";
1522
1523pub const AGENTS_LINE_INTEGRATION_LOCAL: &str = "blocks/agents-line-integration-local.md.in";
1525
1526#[must_use]
1528pub const fn integration_line(integration: Integration) -> &'static str {
1529 match integration {
1530 Integration::Forge => AGENTS_LINE_INTEGRATION_FORGE,
1531 Integration::Local => AGENTS_LINE_INTEGRATION_LOCAL,
1532 }
1533}
1534
1535pub const PRE_COMMIT_BLOCK: &str = "blocks/pre-commit-block.yaml.in";
1537
1538pub const PRE_COMMIT_WORKTREE_GUARD: &str = "blocks/pre-commit-worktree-guard.yaml.in";
1540
1541pub const PRE_COMMIT_TRUNK_COMMIT_GUARD: &str = "blocks/pre-commit-trunk-commit-guard.yaml.in";
1543
1544pub const PRE_COMMIT_TRUNK_PUSH_GUARD: &str = "blocks/pre-commit-trunk-push-guard.yaml.in";
1546
1547pub const PRE_COMMIT_SWEEP_SKIP: &str = "blocks/pre-commit-sweep-skip.yaml.in";
1549
1550pub const PRE_COMMIT_SWEEP_NONE: &str = "blocks/pre-commit-sweep-none.yaml.in";
1552
1553pub const PRE_COMMIT_INTEGRATE_NOTE: &str = "blocks/pre-commit-integrate-note.yaml.in";
1555
1556#[must_use]
1558pub const fn routing_line(mode: CheckoutMode) -> &'static str {
1559 match mode {
1560 CheckoutMode::LinkedWorktree => AGENTS_LINE_WORKTREE,
1561 CheckoutMode::MainWorktree => AGENTS_LINE_BRANCHES,
1562 }
1563}
1564
1565pub fn embedded_block(path: &str) -> Result<&'static str, RkError> {
1572 let name = path.strip_prefix("blocks/").unwrap_or(path);
1573 let file = embedded::BLOCKS
1574 .get_file(name)
1575 .ok_or_else(|| anyhow::anyhow!("{path}: this binary embeds no such block"))?;
1576 std::str::from_utf8(file.contents())
1577 .map_err(|_| anyhow::anyhow!("{path}: a block is UTF-8").into())
1578}
1579
1580#[must_use]
1584pub fn authored(text: &str) -> &str {
1585 text.strip_suffix('\n').unwrap_or(text)
1586}
1587
1588pub 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[-/].+)$";
1596
1597pub const SCOPE_SHAPE: &str = "[a-z0-9._/-]+";
1607
1608#[must_use]
1615pub fn scope_is_shaped(scope: &str) -> bool {
1616 !scope.is_empty()
1617 && scope.chars().all(|c| {
1618 c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '/' | '-')
1619 })
1620}
1621
1622#[must_use]
1629pub fn compose_routing(template: &str, line: &str, integration_line: &str) -> String {
1630 authored(template)
1631 .replacen("RK_WORKFLOW_LINE", authored(line), 1)
1632 .replacen("RK_INTEGRATION_LINE", authored(integration_line), 1)
1633}
1634
1635#[must_use]
1639pub fn compose_glossary(template: &str) -> String {
1640 authored(template).to_owned()
1641}
1642
1643#[must_use]
1662pub fn compose_hooks(template: &str, guard: Option<&str>, parts: &TrunkGuards) -> String {
1663 let guard = guard.map_or_else(String::new, |entry| format!("{}\n", authored(entry)));
1664 let mut skips: Vec<&str> = Vec::new();
1665 if parts.integration == Integration::Forge {
1666 skips.push("no-commit-to-branch");
1667 }
1668 if !guard.is_empty() {
1669 skips.push("rk-worktree-location");
1670 }
1671 let sweep = if skips.is_empty() {
1672 format!("{}\n", authored(parts.sweep_none))
1673 } else {
1674 format!(
1675 "{}\n",
1676 authored(parts.sweep_skip).replacen("RK_SWEEP_SKIP", &skips.join(","), 1)
1677 )
1678 };
1679 let (commit_guard, push_guard, note) = match parts.integration {
1680 Integration::Forge => (
1681 format!("{}\n", authored(parts.trunk_commit)),
1682 format!("{}\n", authored(parts.trunk_push)),
1683 String::new(),
1684 ),
1685 Integration::Local => (
1686 String::new(),
1687 String::new(),
1688 format!("{}\n", authored(parts.integrate_note)),
1689 ),
1690 };
1691 authored(template)
1692 .replacen("RK_BRANCH_GRAMMAR", BRANCH_GRAMMAR, 1)
1693 .replacen("RK_SWEEP_NOTE", &format!("{sweep}{note}"), 1)
1694 .replacen("RK_TRUNK_COMMIT_GUARD", &commit_guard, 1)
1695 .replacen("RK_WORKTREE_GUARD", &guard, 1)
1696 .replacen("RK_TRUNK_PUSH_GUARD", &push_guard, 1)
1697}
1698
1699pub struct TrunkGuards<'a> {
1702 pub integration: Integration,
1704 pub trunk_commit: &'a str,
1706 pub trunk_push: &'a str,
1708 pub sweep_skip: &'a str,
1710 pub sweep_none: &'a str,
1712 pub integrate_note: &'a str,
1714}
1715
1716pub fn routing_block(mode: CheckoutMode, integration: Integration) -> Result<String, RkError> {
1723 Ok(compose_routing(
1724 embedded_block(AGENTS_BLOCK)?,
1725 embedded_block(routing_line(mode))?,
1726 embedded_block(integration_line(integration))?,
1727 ))
1728}
1729
1730pub fn glossary_block() -> Result<String, RkError> {
1736 Ok(compose_glossary(embedded_block(GLOSSARY_BLOCK)?))
1737}
1738
1739pub fn hooks_block(mode: CheckoutMode, integration: Integration) -> Result<String, RkError> {
1746 let guard = match mode {
1747 CheckoutMode::LinkedWorktree => Some(embedded_block(PRE_COMMIT_WORKTREE_GUARD)?),
1748 CheckoutMode::MainWorktree => None,
1749 };
1750 let parts = TrunkGuards {
1751 integration,
1752 trunk_commit: embedded_block(PRE_COMMIT_TRUNK_COMMIT_GUARD)?,
1753 trunk_push: embedded_block(PRE_COMMIT_TRUNK_PUSH_GUARD)?,
1754 sweep_skip: embedded_block(PRE_COMMIT_SWEEP_SKIP)?,
1755 sweep_none: embedded_block(PRE_COMMIT_SWEEP_NONE)?,
1756 integrate_note: embedded_block(PRE_COMMIT_INTEGRATE_NOTE)?,
1757 };
1758 Ok(compose_hooks(
1759 embedded_block(PRE_COMMIT_BLOCK)?,
1760 guard,
1761 &parts,
1762 ))
1763}
1764
1765fn block_template(
1768 destination: &str,
1769 mode: CheckoutMode,
1770 integration: Integration,
1771) -> Result<(String, Vec<String>), RkError> {
1772 match destination {
1773 AGENTS_DESTINATION => Ok((
1774 routing_block(mode, integration)?,
1775 vec![
1776 AGENTS_BLOCK.to_owned(),
1777 routing_line(mode).to_owned(),
1778 integration_line(integration).to_owned(),
1779 ],
1780 )),
1781 GLOSSARY_DESTINATION => Ok((glossary_block()?, vec![GLOSSARY_BLOCK.to_owned()])),
1782 HOOKS_DESTINATION => {
1783 let mut sources = vec![PRE_COMMIT_BLOCK.to_owned()];
1784 if mode == CheckoutMode::LinkedWorktree {
1785 sources.push(PRE_COMMIT_WORKTREE_GUARD.to_owned());
1786 }
1787 match integration {
1788 Integration::Forge => {
1789 sources.push(PRE_COMMIT_TRUNK_COMMIT_GUARD.to_owned());
1790 sources.push(PRE_COMMIT_TRUNK_PUSH_GUARD.to_owned());
1791 sources.push(PRE_COMMIT_SWEEP_SKIP.to_owned());
1792 }
1793 Integration::Local => {
1794 if mode == CheckoutMode::LinkedWorktree {
1795 sources.push(PRE_COMMIT_SWEEP_SKIP.to_owned());
1796 } else {
1797 sources.push(PRE_COMMIT_SWEEP_NONE.to_owned());
1798 }
1799 sources.push(PRE_COMMIT_INTEGRATE_NOTE.to_owned());
1800 }
1801 }
1802 Ok((hooks_block(mode, integration)?, sources))
1803 }
1804 other => Err(anyhow::anyhow!("{other} is not a block destination").into()),
1805 }
1806}
1807
1808#[must_use]
1810pub fn block_markers(destination: &str) -> Option<(&'static str, &'static str)> {
1811 match destination {
1812 AGENTS_DESTINATION | GLOSSARY_DESTINATION => Some((BLOCK_BEGIN, BLOCK_END)),
1813 HOOKS_DESTINATION => Some((HOOKS_BEGIN, HOOKS_END)),
1814 _ => None,
1815 }
1816}
1817
1818#[must_use]
1821pub fn extract_block<'a>(text: &'a str, begin: &str, end: &str) -> Option<&'a str> {
1822 let start = text.find(begin)?;
1823 let stop = text[start..].find(end)? + start + end.len();
1824 Some(&text[start..stop])
1825}
1826
1827#[must_use]
1834pub fn splice_marked_block(existing: Option<&[u8]>, block: &str) -> Vec<u8> {
1835 let block = block.as_bytes();
1836 let Some(text) = existing else {
1837 return [block, b"\n"].concat();
1838 };
1839 if let Some(start) = find(text, BLOCK_BEGIN.as_bytes())
1843 && let Some(offset) = find(&text[start..], BLOCK_END.as_bytes())
1844 {
1845 let stop = start + offset + BLOCK_END.len();
1846 return [&text[..start], block, &text[stop..]].concat();
1847 }
1848 let mut out = Vec::with_capacity(text.len() + block.len() + 3);
1852 out.extend_from_slice(text);
1853 if !text.ends_with(b"\n") {
1854 out.push(b'\n');
1855 }
1856 out.push(b'\n');
1857 out.extend_from_slice(block);
1858 out.push(b'\n');
1859 out
1860}
1861
1862pub fn splice_hooks_block(existing: Option<&str>, block: &str) -> Result<String, String> {
1875 let Some(text) = existing else {
1876 return Ok(format!("{HOOK_TYPES_LINE}\n\nrepos:\n{block}\n"));
1877 };
1878 if let Some(defect) = hooks_marker_defect(text) {
1879 return Err(defect);
1880 }
1881 if let Some(found) = extract_block(text, HOOKS_BEGIN, HOOKS_END) {
1882 return Ok(text.replacen(found, block, 1));
1883 }
1884 let mut out = String::with_capacity(text.len() + block.len() + 1);
1885 let mut placed = false;
1886 for line in text.split_inclusive('\n') {
1887 out.push_str(line);
1888 if !placed && line.trim_end() == "repos:" {
1889 if !out.ends_with('\n') {
1890 out.push('\n');
1891 }
1892 out.push_str(block);
1893 out.push('\n');
1894 placed = true;
1895 }
1896 }
1897 if placed {
1898 Ok(out)
1899 } else {
1900 Err(format!(
1901 "{HOOKS_DESTINATION} exists with no repos: line, so the hook block has nowhere to land"
1902 ))
1903 }
1904}
1905
1906#[must_use]
1916pub fn marker_defect(destination: &str, text: &str) -> Option<String> {
1917 let (begin, end) = block_markers(destination)?;
1918 let begins = text.matches(begin).count();
1919 let ends = text.matches(end).count();
1920 if begins > 1 || ends > 1 {
1921 return Some(format!(
1922 "{destination} carries more than one release-kit marker pair; release-kit owns exactly one block"
1923 ));
1924 }
1925 match (text.find(begin), text.find(end)) {
1926 (Some(begin), Some(end)) if end > begin => None,
1927 (None, None) => None,
1928 _ => Some(format!(
1929 "{destination} carries an unmatched or misordered release-kit marker, so the block's extent is ambiguous"
1930 )),
1931 }
1932}
1933
1934#[must_use]
1937pub fn hooks_marker_defect(text: &str) -> Option<String> {
1938 marker_defect(HOOKS_DESTINATION, text)
1939}
1940
1941fn propose_document(
1945 destination: &str,
1946 existing: Option<&[u8]>,
1947 region: &[u8],
1948) -> Result<Vec<u8>, String> {
1949 let block = String::from_utf8_lossy(region).into_owned();
1954 if let Some(text) = existing
1955 && let Some(defect) = marker_defect(destination, &String::from_utf8_lossy(text))
1956 {
1957 return Err(defect);
1958 }
1959 if destination == HOOKS_DESTINATION {
1960 let text = match existing {
1964 None => None,
1965 Some(bytes) => Some(std::str::from_utf8(bytes).map_err(|_| {
1966 format!(
1967 "{destination} is not UTF-8, so the hook block has nowhere to land without rewriting the target's bytes"
1968 )
1969 })?),
1970 };
1971 return splice_hooks_block(text, &block).map(String::into_bytes);
1972 }
1973 Ok(splice_marked_block(existing, &block))
1974}
1975
1976#[must_use]
1988pub fn nix_unsupported_shape(shape: &CrateShape) -> Option<String> {
1989 let Some(text) = shape.cargo_toml.as_deref() else {
1990 return Some(
1991 "the target has no readable Cargo.toml, which the seeded package expression reads; no Nix file lands".to_owned(),
1992 );
1993 };
1994 let Ok(table) = text.parse::<toml::Table>() else {
1995 return Some(
1996 "the target's Cargo.toml does not parse, and the seeded package expression reads it; no Nix file lands".to_owned(),
1997 );
1998 };
1999 if !table.contains_key("package") {
2000 return Some(
2001 "the target's Cargo.toml has no [package] table; the seed supports a single crate, so no Nix file lands".to_owned(),
2002 );
2003 }
2004 if !shape.cargo_lock {
2005 return Some(
2006 "the target has no Cargo.lock, which the seeded package expression builds from; commit one, then opt in".to_owned(),
2007 );
2008 }
2009 let implicit_bin = shape.main_rs
2010 && table
2011 .get("package")
2012 .and_then(toml::Value::as_table)
2013 .and_then(|package| package.get("autobins"))
2014 .and_then(toml::Value::as_bool)
2015 != Some(false);
2016 let explicit_bins = table.get("bin").and_then(toml::Value::as_array);
2017 if explicit_bins.is_none() && !implicit_bin {
2018 return Some(
2019 "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(),
2020 );
2021 }
2022 if let Some(bins) = explicit_bins {
2028 let required = bins
2029 .first()
2030 .and_then(toml::Value::as_table)
2031 .and_then(|bin| bin.get("required-features"))
2032 .and_then(toml::Value::as_array);
2033 if let Some(required) = required {
2034 let enabled = default_features(&table);
2035 let missing = required
2036 .iter()
2037 .filter_map(toml::Value::as_str)
2038 .any(|feature| !enabled.contains(feature));
2039 if missing {
2040 return Some(
2041 "the target's first [[bin]] entry requires features a default build does not enable; no Nix file lands".to_owned(),
2042 );
2043 }
2044 }
2045 }
2046 None
2047}
2048
2049fn dep_edge_suppresses(features: &toml::Table, name: &str) -> bool {
2052 let edge = format!("dep:{name}");
2053 features.values().any(|list| {
2054 list.as_array().is_some_and(|entries| {
2055 entries
2056 .iter()
2057 .filter_map(toml::Value::as_str)
2058 .any(|entry| entry == edge)
2059 })
2060 })
2061}
2062
2063fn is_optional_dependency(table: &toml::Table, name: &str) -> bool {
2066 ["dependencies", "build-dependencies"]
2067 .iter()
2068 .any(|section| {
2069 table
2070 .get(*section)
2071 .and_then(toml::Value::as_table)
2072 .and_then(|dependencies| dependencies.get(name))
2073 .and_then(toml::Value::as_table)
2074 .and_then(|dependency| dependency.get("optional"))
2075 .and_then(toml::Value::as_bool)
2076 == Some(true)
2077 })
2078}
2079
2080fn default_features(table: &toml::Table) -> std::collections::BTreeSet<String> {
2087 let Some(features) = table.get("features").and_then(toml::Value::as_table) else {
2088 return std::collections::BTreeSet::new();
2089 };
2090 let mut enabled = std::collections::BTreeSet::new();
2091 let mut queue = vec!["default".to_owned()];
2092 while let Some(name) = queue.pop() {
2093 if !enabled.insert(name.clone()) {
2094 continue;
2095 }
2096 if let Some(implies) = features.get(&name).and_then(toml::Value::as_array) {
2097 for implied in implies.iter().filter_map(toml::Value::as_str) {
2098 if implied.starts_with("dep:") || implied.contains("?/") {
2099 continue;
2103 }
2104 if let Some((package, _)) = implied.split_once('/') {
2105 let feature_exists =
2113 features.contains_key(package) || !dep_edge_suppresses(features, package);
2114 if is_optional_dependency(table, package) && feature_exists {
2115 queue.push(package.to_owned());
2116 }
2117 } else {
2118 queue.push(implied.to_owned());
2119 }
2120 }
2121 }
2122 }
2123 enabled
2124}
2125
2126#[must_use]
2134pub fn flake_pair_withheld(
2135 flake_recorded: bool,
2136 flake_nix_present: bool,
2137 flake_lock_present: bool,
2138) -> Option<String> {
2139 if flake_recorded {
2140 return None;
2141 }
2142 let present: Vec<&str> = [
2143 ("flake.nix", flake_nix_present),
2144 ("flake.lock", flake_lock_present),
2145 ]
2146 .into_iter()
2147 .filter_map(|(name, present)| present.then_some(name))
2148 .collect();
2149 if present.is_empty() {
2150 return None;
2151 }
2152 Some(format!(
2153 "the target already carries {}; its flake pair stays its own",
2154 present.join(" and ")
2155 ))
2156}
2157
2158#[must_use]
2168pub fn nix_withholding(
2169 nix: bool,
2170 evidence: &TargetEvidence,
2171) -> Option<(&'static [&'static str], String)> {
2172 if !nix {
2173 return None;
2174 }
2175 if let Some(reason) = nix_unsupported_shape(&evidence.crate_shape) {
2176 return Some((&NIX_DESTINATIONS[..], reason));
2177 }
2178 flake_pair_withheld(
2179 evidence.flake_recorded,
2180 evidence.flake_nix_present,
2181 evidence.flake_lock_present,
2182 )
2183 .map(|reason| (&NIX_WITHHOLDABLE[..], reason))
2184}
2185
2186#[cfg(test)]
2187mod tests {
2188 use super::{
2189 AGENTS_DESTINATION, BLOCK_BEGIN, BLOCK_DESTINATIONS, BLOCK_END, Candidate, Collision,
2190 CrateShape, GLOSSARY_DESTINATION, HOOK_TYPES_LINE, HOOKS_BEGIN, HOOKS_DESTINATION,
2191 HOOKS_END, Placement, Projection, ProjectionInput, TargetEvidence, extract_block,
2192 };
2193 use crate::landing::{Params, Style};
2194
2195 fn supported_shape() -> CrateShape {
2197 CrateShape {
2198 cargo_toml: Some("[package]\nname = \"widget\"\nversion = \"0.1.0\"\n".to_owned()),
2199 cargo_lock: true,
2200 main_rs: true,
2201 }
2202 }
2203
2204 fn input(evidence: TargetEvidence) -> ProjectionInput {
2205 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2206 params.set_nix_for_test(true);
2207 ProjectionInput { params, evidence }
2208 }
2209
2210 fn compute(evidence: TargetEvidence) -> Projection {
2211 Projection::compute(&input(evidence)).expect("the embedded pair projects")
2212 }
2213
2214 fn candidate<'a>(projection: &'a Projection, destination: &str) -> &'a Candidate {
2215 projection
2216 .candidates
2217 .iter()
2218 .find(|candidate| candidate.destination == destination)
2219 .expect("the destination projects")
2220 }
2221
2222 fn outside(bytes: &[u8], begin: &str, end: &str) -> (Vec<u8>, Vec<u8>) {
2224 let text = String::from_utf8_lossy(bytes);
2225 let start = text.find(begin).expect("the begin marker is present");
2226 let stop = text[start..].find(end).expect("the end marker is present") + start + end.len();
2227 (bytes[..start].to_vec(), bytes[stop..].to_vec())
2228 }
2229
2230 #[test]
2231 fn equal_projection_inputs_yield_byte_identical_projections() {
2232 let mut documents = std::collections::BTreeMap::new();
2233 documents.insert(
2234 AGENTS_DESTINATION.to_owned(),
2235 b"# Widget\n\nOwn rules.\n".to_vec(),
2236 );
2237 let evidence = TargetEvidence {
2238 documents,
2239 crate_shape: supported_shape(),
2240 ..TargetEvidence::default()
2241 };
2242 let first = input(evidence.clone());
2243 let second = input(evidence);
2244 assert_eq!(first, second, "the inputs are values and compare equal");
2245 let a = Projection::compute(&first).expect("the pair projects");
2246 let b = Projection::compute(&second).expect("the pair projects");
2247 assert_eq!(a.candidates.len(), b.candidates.len());
2248 for (x, y) in a.candidates.iter().zip(&b.candidates) {
2249 assert_eq!(x.destination, y.destination);
2250 assert_eq!(x.kind, y.kind);
2251 assert_eq!(x.placement, y.placement);
2252 assert_eq!(x.bytes, y.bytes, "{}", x.destination);
2253 assert_eq!(x.region, y.region, "{}", x.destination);
2254 assert_eq!(x.sources, y.sources, "{}", x.destination);
2255 }
2256 assert_eq!(a, b);
2257 let destinations: Vec<&str> = a
2258 .candidates
2259 .iter()
2260 .map(|candidate| candidate.destination.as_str())
2261 .collect();
2262 let mut sorted = destinations.clone();
2263 sorted.sort_unstable();
2264 assert_eq!(destinations, sorted, "candidates sort by destination");
2265 assert!(a.omissions.is_empty(), "{:?}", a.omissions);
2266 assert!(a.collisions.is_empty(), "{:?}", a.collisions);
2267 }
2268
2269 #[test]
2273 fn the_scorecard_destination_projects_only_under_the_opt_in() {
2274 use super::{Kind, SCORECARD_DESTINATIONS, kind_of};
2275 let destination = SCORECARD_DESTINATIONS[0];
2276 assert_eq!(kind_of(destination), Some(Kind::Rendered));
2277
2278 let project = |scorecard: bool| {
2279 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2280 params.set_scorecard_for_test(scorecard);
2281 Projection::compute(&ProjectionInput {
2282 params,
2283 evidence: TargetEvidence::default(),
2284 })
2285 .expect("the embedded pair projects")
2286 };
2287
2288 let off = project(false);
2289 assert!(
2290 !off.candidates
2291 .iter()
2292 .any(|candidate| candidate.destination == destination),
2293 "off by default, and an absent candidate is no omission"
2294 );
2295 assert!(off.omissions.is_empty(), "{:?}", off.omissions);
2296
2297 let on = project(true);
2298 let candidate = candidate(&on, destination);
2299 assert_eq!(candidate.kind, Kind::Rendered);
2300 assert_eq!(candidate.placement, Placement::Whole);
2301 let text = String::from_utf8_lossy(&candidate.bytes);
2302 assert!(!text.contains("RK_"), "a token survived: {text}");
2303 }
2304
2305 #[test]
2310 fn the_licence_judgment_reads_what_every_reader_obtains() {
2311 use super::licence_states_an_open_source_codebase as approved;
2312 for expression in [
2313 "MIT",
2314 "Apache-2.0",
2315 "MIT OR Apache-2.0",
2316 "MIT AND Apache-2.0",
2317 "(MIT OR Apache-2.0) AND ISC",
2318 "Apache-2.0 WITH LLVM-exception OR MIT",
2319 "GPL-3.0+",
2320 ] {
2321 assert!(approved(expression), "{expression} is OSI-approved");
2322 }
2323 for expression in [
2328 "MIT AND CC-BY-4.0",
2329 "CC-BY-4.0 AND MIT",
2330 "MIT AND (CC-BY-4.0 OR CC-BY-SA-4.0)",
2331 "(MIT OR CC-BY-4.0) AND MIT",
2332 "MIT OR Apache-2.0 AND CC-BY-4.0",
2333 "Apache-2.0 WITH LLVM-exception AND CC-BY-SA-3.0",
2334 ] {
2335 assert!(approved(expression), "{expression} states open source");
2336 }
2337 for expression in [
2338 "",
2339 " ",
2340 "LicenseRef-proprietary",
2341 "MIT AND LicenseRef-proprietary",
2342 "SEE LICENSE IN COPYING",
2343 "CC-BY-4.0",
2344 "DocumentRef-spdx:LicenseRef-proprietary",
2345 ] {
2346 assert!(!approved(expression), "{expression} is not recognized");
2347 }
2348 for expression in [
2353 "MIT OR CC-BY-4.0",
2354 "CC-BY-4.0 AND CC-BY-SA-4.0",
2355 "CC-BY-4.0 AND LicenseRef-proprietary",
2356 "CC0-1.0",
2357 "MIT AND CC-BY-4.0 AND LicenseRef-proprietary",
2358 ] {
2359 assert!(!approved(expression), "{expression} grants no code terms");
2360 }
2361 assert!(
2366 !approved("CC-BY-4.0 OR CC-BY-SA-4.0 AND MIT"),
2367 "AND binds tighter than OR"
2368 );
2369 }
2370
2371 #[test]
2377 fn the_licence_judgment_holds_the_expression_to_the_spdx_grammar() {
2378 use super::licence_states_an_open_source_codebase as approved;
2379 for expression in [
2384 "MIT OR",
2385 "OR MIT",
2386 "MIT AND",
2387 "MIT WITH",
2388 "WITH LLVM-exception",
2389 "(MIT",
2390 "MIT)",
2391 "MIT Apache-2.0",
2392 "()",
2393 "(MIT OR Apache-2.0",
2394 "MIT OR (Apache-2.0",
2395 "MIT OR ()",
2396 "AND",
2397 "(",
2398 ")",
2399 "MIT WITH AND ISC",
2400 "MIT OR OR ISC",
2401 "MIT @ Apache-2.0",
2402 ] {
2403 assert!(!approved(expression), "{expression} is malformed");
2404 }
2405 for expression in [
2407 "MIT AND (Apache-2.0 OR ISC)",
2408 "((MIT))",
2409 "Apache-2.0 WITH LLVM-exception AND ISC",
2410 "(Apache-2.0 WITH LLVM-exception)",
2411 ] {
2412 assert!(approved(expression), "{expression} is well formed");
2413 }
2414 for expression in [
2419 "mit",
2420 "MiT",
2421 "apache-2.0 OR mit",
2422 "APACHE-2.0 WITH llvm-exception",
2423 ] {
2424 assert!(
2425 approved(expression),
2426 "{expression} names an approved licence"
2427 );
2428 }
2429 for expression in [
2433 "MIT or Apache-2.0",
2434 "MIT and Apache-2.0",
2435 "MIT with LLVM-exception",
2436 ] {
2437 assert!(!approved(expression), "{expression} carries no operator");
2438 }
2439 for expression in [
2443 "MIT WITH definitely-not-an-spdx-exception",
2444 "MIT WITH MIT",
2445 "MIT WITH Apache-2.0",
2446 ] {
2447 assert!(!approved(expression), "{expression} names no exception");
2448 }
2449 for expression in [
2453 "GPL-2.0-only WITH GCC-exception-2.0",
2454 "GPL-2.0-or-later WITH Classpath-exception-2.0",
2455 "Apache-2.0 WITH Swift-exception",
2456 "GPL-3.0-only WITH Autoconf-exception-generic",
2457 ] {
2458 assert!(approved(expression), "{expression} names a real exception");
2459 }
2460 }
2461
2462 #[test]
2468 fn a_recorded_provider_its_pair_cannot_run_is_named() {
2469 use super::{Provider, code_scanning_incompatibility};
2470
2471 assert!(code_scanning_incompatibility(None, Some("bash"), Some("gitlab")).is_none());
2472 assert!(
2473 code_scanning_incompatibility(Some(Provider::Semgrep), Some("rust"), Some("gitlab"))
2474 .is_none()
2475 );
2476 assert!(
2477 code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("github"))
2478 .is_none()
2479 );
2480
2481 let bash =
2482 code_scanning_incompatibility(Some(Provider::Semgrep), Some("bash"), Some("github"))
2483 .expect("a binding with no scanner is named");
2484 assert!(bash.contains("bash binding"), "{bash}");
2485 let gitlab =
2486 code_scanning_incompatibility(Some(Provider::CodeQl), Some("rust"), Some("gitlab"))
2487 .expect("codeql on gitlab is named");
2488 assert!(gitlab.contains("codeql"), "{gitlab}");
2489 let release_less =
2490 code_scanning_incompatibility(Some(Provider::Semgrep), None, Some("github"))
2491 .expect("no driver is named");
2492 assert!(
2493 release_less.contains("no automatic release driver"),
2494 "{release_less}"
2495 );
2496
2497 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2500 params.set_code_scanning_for_test(Some(Provider::Semgrep));
2501 let clean = Projection::compute(&ProjectionInput {
2502 params: params.clone(),
2503 evidence: TargetEvidence::default(),
2504 })
2505 .expect("the pair projects");
2506 assert!(
2507 clean.record_defects.is_empty(),
2508 "{:?}",
2509 clean.record_defects
2510 );
2511 }
2512
2513 #[test]
2517 fn the_code_scanning_destinations_follow_the_recorded_provider() {
2518 use super::{
2519 CODE_SCANNING_DESTINATIONS, Kind, Provider, code_scanning_licence_refusal, kind_of,
2520 };
2521 for (destination, _) in CODE_SCANNING_DESTINATIONS {
2522 assert_eq!(kind_of(destination), Some(Kind::Rendered), "{destination}");
2523 }
2524
2525 let project = |provider: Option<Provider>| {
2526 let mut params = Params::for_test("acme/widget", Some(Style::Trunk));
2527 params.set_code_scanning_for_test(provider);
2528 Projection::compute(&ProjectionInput {
2529 params,
2530 evidence: TargetEvidence {
2531 crate_shape: CrateShape {
2532 cargo_toml: Some(
2533 "[package]\nname = \"widget\"\nlicense = \"MIT\"\n".to_owned(),
2534 ),
2535 ..CrateShape::default()
2536 },
2537 ..TargetEvidence::default()
2538 },
2539 })
2540 .expect("the embedded pair projects")
2541 };
2542 let landed = |projection: &Projection, destination: &str| {
2543 projection
2544 .candidates
2545 .iter()
2546 .any(|candidate| candidate.destination == destination)
2547 };
2548
2549 let off = project(None);
2550 for (destination, _) in CODE_SCANNING_DESTINATIONS {
2551 assert!(!landed(&off, destination), "{destination}");
2552 }
2553 assert!(off.licence_refusal.is_none());
2554
2555 let codeql = project(Some(Provider::CodeQl));
2556 assert!(landed(
2557 &codeql,
2558 ".github/workflows/code-scanning-codeql.yml"
2559 ));
2560 assert!(!landed(
2561 &codeql,
2562 ".github/workflows/code-scanning-semgrep.yml"
2563 ));
2564 assert!(codeql.licence_refusal.is_none(), "MIT satisfies the terms");
2565
2566 let semgrep = project(Some(Provider::Semgrep));
2567 assert!(landed(
2568 &semgrep,
2569 ".github/workflows/code-scanning-semgrep.yml"
2570 ));
2571 assert!(!landed(
2572 &semgrep,
2573 ".github/workflows/code-scanning-codeql.yml"
2574 ));
2575
2576 let proprietary = CrateShape {
2578 cargo_toml: Some("[package]\nlicense = \"LicenseRef-proprietary\"\n".to_owned()),
2579 ..CrateShape::default()
2580 };
2581 assert!(
2582 code_scanning_licence_refusal(Some(Provider::Semgrep), Some("rust"), &proprietary)
2583 .is_none()
2584 );
2585 let refusal =
2586 code_scanning_licence_refusal(Some(Provider::CodeQl), Some("rust"), &proprietary)
2587 .expect("codeql refuses a licence its terms do not cover");
2588 assert!(refusal.contains("LicenseRef-proprietary"), "{refusal}");
2589 assert!(refusal.contains("semgrep"), "{refusal}");
2590 let bash =
2593 code_scanning_licence_refusal(Some(Provider::CodeQl), Some("bash"), &proprietary)
2594 .expect("an unread binding refuses");
2595 assert!(bash.contains("bash binding"), "{bash}");
2596 }
2597
2598 #[test]
2604 fn the_projection_performs_no_filesystem_git_environment_clock_registry_or_network_read() {
2605 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/projection.rs");
2606 let text = std::fs::read_to_string(&path).expect("the source reads");
2607 let production = text.split("#[cfg(test)]").next().unwrap_or("");
2608 let needles = [
2609 "std::fs",
2610 "std::env",
2611 "std::process",
2612 "std::time",
2613 "SystemTime",
2614 "Instant",
2615 "std::net",
2616 "Command::new",
2617 "registry::",
2618 "curl",
2619 "reqwest",
2620 "blob(",
2621 ];
2622 let mut hits = Vec::new();
2623 for (index, line) in production.lines().enumerate() {
2624 if line.trim_start().starts_with("//") {
2625 continue;
2626 }
2627 for needle in needles {
2628 if line.contains(needle) {
2629 hits.push(format!("src/projection.rs:{}: {needle}", index + 1));
2630 }
2631 }
2632 }
2633 assert!(
2634 hits.is_empty(),
2635 "the projection reads beyond its inputs: {hits:?}"
2636 );
2637 }
2638
2639 #[test]
2640 #[allow(
2641 clippy::too_many_lines,
2642 reason = "one test walks the three marked destinations and the three unmarked shapes"
2643 )]
2644 fn marked_region_projection_preserves_every_target_byte_outside_the_markers() {
2645 let agents_before = "# Widget\n\nOperator prose above.\n\n";
2646 let agents_after = "\n\n## Our rules\n\nOperator prose below. \n";
2647 let glossary_before = "# Glossary\n\n- `spike` is a throwaway branch.\n\n";
2648 let glossary_after = "\n\n## More terms\n\n- `own` is ours.";
2649 let hooks_before = "default_install_hook_types: [pre-commit]\n\nrepos:\n";
2650 let hooks_after =
2651 "\n - repo: https://example.com/own\n rev: v1\n hooks:\n - id: own\n";
2652 let stale = |begin: &str, end: &str| format!("{begin}\nstale block\n{end}");
2653 let mut documents = std::collections::BTreeMap::new();
2654 documents.insert(
2655 AGENTS_DESTINATION.to_owned(),
2656 format!(
2657 "{agents_before}{}{agents_after}",
2658 stale(BLOCK_BEGIN, BLOCK_END)
2659 )
2660 .into_bytes(),
2661 );
2662 documents.insert(
2663 GLOSSARY_DESTINATION.to_owned(),
2664 format!(
2665 "{glossary_before}{}{glossary_after}",
2666 stale(BLOCK_BEGIN, BLOCK_END)
2667 )
2668 .into_bytes(),
2669 );
2670 documents.insert(
2671 HOOKS_DESTINATION.to_owned(),
2672 format!(
2673 "{hooks_before}{}{hooks_after}",
2674 stale(HOOKS_BEGIN, HOOKS_END)
2675 )
2676 .into_bytes(),
2677 );
2678 let projection = compute(TargetEvidence {
2679 documents: documents.clone(),
2680 crate_shape: supported_shape(),
2681 ..TargetEvidence::default()
2682 });
2683 assert!(
2684 projection.collisions.is_empty(),
2685 "{:?}",
2686 projection.collisions
2687 );
2688 for (destination, before, after) in [
2689 (AGENTS_DESTINATION, agents_before, agents_after),
2690 (GLOSSARY_DESTINATION, glossary_before, glossary_after),
2691 (HOOKS_DESTINATION, hooks_before, hooks_after),
2692 ] {
2693 let candidate = candidate(&projection, destination);
2694 let Placement::Region { begin, end } = candidate.placement else {
2695 panic!("{destination} is a region");
2696 };
2697 let region = candidate
2698 .region
2699 .as_deref()
2700 .expect("a region carries its block");
2701 let (head, tail) = outside(&candidate.bytes, begin, end);
2702 assert_eq!(
2703 head,
2704 before.as_bytes(),
2705 "{destination}: bytes before the markers"
2706 );
2707 assert_eq!(
2708 tail,
2709 after.as_bytes(),
2710 "{destination}: bytes after the markers"
2711 );
2712 let inside = &candidate.bytes[head.len()..candidate.bytes.len() - tail.len()];
2713 assert_eq!(
2714 inside, region,
2715 "{destination}: the region is the rendered block"
2716 );
2717 let (existing_head, existing_tail) = outside(&documents[destination], begin, end);
2718 assert_eq!(head, existing_head);
2719 assert_eq!(tail, existing_tail);
2720 }
2721
2722 let own_hooks =
2726 "repos:\n - repo: https://example.com/own\n rev: v1\n hooks:\n - id: own\n";
2727 let own_agents = "# Widget\n\nOwn rules.";
2728 let mut documents = std::collections::BTreeMap::new();
2729 documents.insert(HOOKS_DESTINATION.to_owned(), own_hooks.as_bytes().to_vec());
2730 documents.insert(
2731 AGENTS_DESTINATION.to_owned(),
2732 own_agents.as_bytes().to_vec(),
2733 );
2734 let projection = compute(TargetEvidence {
2735 documents,
2736 crate_shape: supported_shape(),
2737 ..TargetEvidence::default()
2738 });
2739 assert!(
2740 projection.collisions.is_empty(),
2741 "{:?}",
2742 projection.collisions
2743 );
2744 let hooks = candidate(&projection, HOOKS_DESTINATION);
2745 let hooks_text = String::from_utf8_lossy(&hooks.bytes);
2746 let region = String::from_utf8_lossy(hooks.region.as_deref().expect("a region"));
2747 assert!(
2748 hooks_text.starts_with(&format!(
2749 "repos:\n{region}\n - repo: https://example.com/own"
2750 )),
2751 "{hooks_text}"
2752 );
2753 assert!(!hooks_text.contains(HOOK_TYPES_LINE));
2754 let agents = candidate(&projection, AGENTS_DESTINATION);
2755 assert!(agents.bytes.starts_with(own_agents.as_bytes()));
2756 assert_eq!(
2757 extract_block(
2758 &String::from_utf8_lossy(&agents.bytes),
2759 BLOCK_BEGIN,
2760 BLOCK_END
2761 )
2762 .map(str::as_bytes),
2763 agents.region.as_deref()
2764 );
2765 let glossary = candidate(&projection, GLOSSARY_DESTINATION);
2766 let region = glossary.region.as_deref().expect("a region");
2767 assert_eq!(
2768 glossary.bytes,
2769 [region, b"\n"].concat(),
2770 "an absent file is fresh"
2771 );
2772 }
2773
2774 #[test]
2780 fn a_hook_document_that_is_not_utf8_collides_instead_of_being_rewritten() {
2781 let mut documents = std::collections::BTreeMap::new();
2782 let mut invalid = b"repos:\n# own \xff above\n".to_vec();
2783 invalid.extend_from_slice(format!("{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n").as_bytes());
2784 invalid.extend_from_slice(b" - repo: local \xff below\n");
2785 documents.insert(HOOKS_DESTINATION.to_owned(), invalid);
2786 let mut agents = b"# Widget r\xe9sum\xe9\n\n".to_vec();
2787 agents.extend_from_slice(format!("{BLOCK_BEGIN}\nstale\n{BLOCK_END}\n\n").as_bytes());
2788 agents.extend_from_slice(b"r\xe9sum\xe9\n");
2789 documents.insert(AGENTS_DESTINATION.to_owned(), agents.clone());
2790 let projection = compute(TargetEvidence {
2791 documents,
2792 crate_shape: supported_shape(),
2793 ..TargetEvidence::default()
2794 });
2795 let collided: Vec<&str> = projection
2796 .collisions
2797 .iter()
2798 .map(|c| c.destination.as_str())
2799 .collect();
2800 assert_eq!(collided, [HOOKS_DESTINATION]);
2801 assert!(
2802 projection.collisions[0].reason.contains("not UTF-8"),
2803 "{}",
2804 projection.collisions[0].reason
2805 );
2806 assert!(
2807 !projection
2808 .candidates
2809 .iter()
2810 .any(|c| c.destination == HOOKS_DESTINATION),
2811 "a colliding destination projects no candidate"
2812 );
2813 let agents = candidate(&projection, AGENTS_DESTINATION);
2814 assert!(
2815 agents.bytes.starts_with(b"# Widget r\xe9sum\xe9\n\n"),
2816 "{:?}",
2817 agents.bytes
2818 );
2819 assert!(
2820 agents.bytes.ends_with(b"\n\nr\xe9sum\xe9\n"),
2821 "{:?}",
2822 agents.bytes
2823 );
2824 assert!(
2825 !agents.bytes.contains(&0xEF),
2826 "a replacement character landed"
2827 );
2828
2829 let mut documents = std::collections::BTreeMap::new();
2830 let valid =
2831 format!("repos:\n# own above\n{HOOKS_BEGIN}\nstale\n{HOOKS_END}\n - repo: local\n");
2832 documents.insert(HOOKS_DESTINATION.to_owned(), valid.into_bytes());
2833 let projection = compute(TargetEvidence {
2834 documents,
2835 crate_shape: supported_shape(),
2836 ..TargetEvidence::default()
2837 });
2838 assert!(
2839 projection.collisions.is_empty(),
2840 "{:?}",
2841 projection.collisions
2842 );
2843 let hooks = candidate(&projection, HOOKS_DESTINATION);
2844 let text = String::from_utf8(hooks.bytes.clone()).expect("a valid document stays text");
2845 assert!(text.starts_with("repos:\n# own above\n"), "{text}");
2846 assert!(text.ends_with("\n - repo: local\n"), "{text}");
2847 assert!(!text.contains("stale"), "the region is replaced: {text}");
2848 }
2849
2850 #[test]
2854 fn a_whole_file_colliding_with_a_marked_region_names_both_source_paths() {
2855 let files: Vec<(String, &[u8])> = vec![
2856 ("snippets/_shared/github/SECURITY.md".to_owned(), b"policy"),
2857 ("snippets/rust/github/AGENTS.md".to_owned(), b"whole"),
2858 ];
2859 let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
2860 .expect_err("a whole file at a block destination refuses");
2861 let text = err.to_string();
2862 assert!(text.contains("snippets/rust/github/AGENTS.md"), "{text}");
2863 assert!(text.contains(super::AGENTS_BLOCK), "{text}");
2864 assert!(text.contains(super::AGENTS_LINE_WORKTREE), "{text}");
2865 assert!(text.contains("embedded sources are defective"), "{text}");
2866 }
2867
2868 #[test]
2869 fn duplicate_whole_file_destinations_and_overlapping_marked_regions_refuse_with_the_conflicting_source_names()
2870 {
2871 let files: Vec<(String, &[u8])> = vec![
2874 ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
2875 ("snippets/rust/github/SECURITY.md".to_owned(), b"pair"),
2876 ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
2877 ];
2878 let err = Projection::compute_over(&files, &input(TargetEvidence::default()))
2879 .expect_err("a doubled destination refuses");
2880 let text = err.to_string();
2881 assert!(
2882 text.contains("snippets/_shared/github/SECURITY.md"),
2883 "{text}"
2884 );
2885 assert!(text.contains("snippets/rust/github/SECURITY.md"), "{text}");
2886 assert!(text.contains("embedded sources are defective"), "{text}");
2887
2888 let clean: Vec<(String, &[u8])> = vec![
2889 ("snippets/_shared/github/SECURITY.md".to_owned(), b"shared"),
2890 ("snippets/rust/github/release-plz.toml".to_owned(), b"seed"),
2891 ];
2892 let projection = Projection::compute_over(&clean, &input(TargetEvidence::default()))
2893 .expect("a clean list projects");
2894 let whole: Vec<&str> = projection
2895 .candidates
2896 .iter()
2897 .filter(|c| c.placement == Placement::Whole)
2898 .map(|c| c.destination.as_str())
2899 .collect();
2900 assert_eq!(whole, ["SECURITY.md", "release-plz.toml"]);
2901 assert_eq!(
2902 projection
2903 .candidates
2904 .iter()
2905 .find(|c| c.destination == "SECURITY.md")
2906 .map(|c| c.sources.clone()),
2907 Some(vec!["snippets/_shared/github/SECURITY.md".to_owned()])
2908 );
2909
2910 let doubled = format!("{BLOCK_BEGIN}\na\n{BLOCK_END}\n{BLOCK_BEGIN}\nb\n{BLOCK_END}\n");
2911 let unmatched = format!("repos:\n{HOOKS_BEGIN}\n - repo: local\n");
2912 let misordered = format!("# G\n{BLOCK_END}\n{BLOCK_BEGIN}\n");
2913 let mut documents = std::collections::BTreeMap::new();
2914 documents.insert(AGENTS_DESTINATION.to_owned(), doubled.into_bytes());
2915 documents.insert(HOOKS_DESTINATION.to_owned(), unmatched.into_bytes());
2916 documents.insert(GLOSSARY_DESTINATION.to_owned(), misordered.into_bytes());
2917 let projection = compute(TargetEvidence {
2918 documents,
2919 crate_shape: supported_shape(),
2920 ..TargetEvidence::default()
2921 });
2922 let mut collided: Vec<&str> = projection
2923 .collisions
2924 .iter()
2925 .map(|Collision { destination, .. }| destination.as_str())
2926 .collect();
2927 collided.sort_unstable();
2928 let mut expected = BLOCK_DESTINATIONS.to_vec();
2929 expected.sort_unstable();
2930 assert_eq!(collided, expected);
2931 for collision in &projection.collisions {
2932 assert!(
2933 collision.reason.contains(&collision.destination),
2934 "{collision:?}"
2935 );
2936 assert!(
2937 !projection
2938 .candidates
2939 .iter()
2940 .any(|candidate| candidate.destination == collision.destination),
2941 "{} collided and still projects",
2942 collision.destination
2943 );
2944 }
2945 let agents = projection
2946 .collisions
2947 .iter()
2948 .find(|c| c.destination == AGENTS_DESTINATION)
2949 .expect("the doubled document collides");
2950 assert!(agents.reason.contains("more than one"), "{}", agents.reason);
2951 let hooks = projection
2952 .collisions
2953 .iter()
2954 .find(|c| c.destination == HOOKS_DESTINATION)
2955 .expect("the unmatched document collides");
2956 assert!(hooks.reason.contains("unmatched"), "{}", hooks.reason);
2957 }
2958}