1use core::fmt;
32use std::num::NonZeroUsize;
33use std::path::PathBuf;
34
35use crate::types::{
36 Ceiling, Declaration, DeclarationOrder, DenialReason, Diagnostic, Directory, EnvName, EnvValue,
37 FieldName, IgnoredPath, Ignoring, InputKind, Label, Node, Origin, OutputPath, PluginName,
38 PluginViolation, Program, Provenance, RemoteUrl, SettingName, SourcePath, TargetRole,
39 TokenSource, TreePath, Want, WantedSet, Written,
40};
41
42pub type Result<T> = core::result::Result<T, Error>;
44
45#[derive(Debug, thiserror::Error)]
49#[non_exhaustive]
50pub enum Error {
51 #[error("invalid {kind}: {value:?} — {reason}")]
53 InvalidName {
54 kind: NameKind,
56 value: String,
58 reason: &'static str,
60 },
61 #[error("a token would be sent in clear text to {url}; use a grpcs:// URL")]
63 InsecureToken {
64 url: RemoteUrl,
66 },
67 #[error("{reason}")]
69 NotAccepted {
70 reason: &'static str,
72 },
73 #[error(
75 "target {target} declares {outputs} outputs; a target whose output is its stdout declares exactly one"
76 )]
77 StdoutOutputs {
78 target: Label,
80 outputs: usize,
82 },
83 #[error("value could not be serialized as canonical JSON")]
85 CanonicalJson {
86 #[source]
88 source: serde_json::Error,
89 },
90 #[error("floating-point value at {path} cannot appear in canonical JSON")]
92 FloatRejected {
93 path: String,
95 },
96 #[error("canonical JSON could not be read: {source}")]
99 UnreadableJson {
100 #[source]
102 source: serde_json::Error,
103 },
104 #[error("JSON is not in canonical form: it differs from it at byte {offset}")]
107 NonCanonicalJson {
108 offset: usize,
110 },
111 #[error("{} is not a file buildl wrote: {source}", .file.display())]
118 CorruptState {
119 file: PathBuf,
121 #[source]
123 source: Box<Self>,
124 },
125 #[error("{provenance}: {failure}: {diagnostic}")]
127 Evaluation {
128 provenance: Provenance,
130 failure: EvaluationFailure,
132 diagnostic: Diagnostic,
134 },
135 #[error(
137 "no build file in //{directory}{}",
138 requested_by_suffix(.requested_by.as_ref())
139 )]
140 MissingBuildFile {
141 directory: Directory,
143 requested_by: Option<Provenance>,
145 },
146 #[error(
148 "{provenance}{}: declaration {order}: invalid {field}: {source}",
149 plugin_suffix(.origin)
150 )]
151 InvalidDeclaration {
152 provenance: Provenance,
154 origin: Origin,
156 order: DeclarationOrder,
158 field: DeclarationField,
160 #[source]
162 source: Box<Self>,
163 },
164 #[error(
166 "{provenance}{}: {}: {path} is ignored by {} ({})",
167 plugin_suffix(.origin),
168 ignored_field(.path),
169 .ignoring.file(),
170 .ignoring.pattern()
171 )]
172 Ignored {
173 provenance: Provenance,
175 origin: Origin,
177 order: DeclarationOrder,
179 path: Box<IgnoredPath>,
181 ignoring: Box<Ignoring>,
183 },
184 #[error("{file}{}: {reason}", line_suffix(*.line))]
186 IgnoreFile {
187 file: String,
189 line: Option<u32>,
191 reason: String,
193 },
194 #[error(
196 "{provenance}{}: declaration {order}: a target names {found}",
197 plugin_suffix(.origin)
198 )]
199 ActionConflict {
200 provenance: Provenance,
202 origin: Origin,
204 order: DeclarationOrder,
206 found: ActionFound,
208 },
209 #[error("{provenance}: declarations differ between two evaluations")]
211 Nondeterministic {
212 provenance: Provenance,
214 first_run: Option<Box<Declaration>>,
216 second_run: Option<Box<Declaration>>,
218 },
219 #[error(
222 "{provenance}: discovery target {label} differs once discovery results are read; a \
223 discovery target may not depend on a discovery result"
224 )]
225 DiscoveryChanged {
226 label: Label,
229 provenance: Provenance,
231 },
232 #[error("{label} is declared more than once: {}", declaring_sites(.sites))]
234 DuplicateLabel {
235 label: Label,
237 sites: Vec<DeclarationSite>,
240 },
241 #[error("setting {name} is declared more than once: {}", sites_list(.sites))]
243 DuplicateSetting {
244 name: SettingName,
246 sites: Vec<Provenance>,
248 },
249 #[error(
251 "{}: {field} {reference} is not declared{}",
252 .site,
253 suggestion_suffix(.suggestion.as_ref())
254 )]
255 UnknownReference {
256 site: Box<DeclarationSite>,
258 field: DeclarationField,
260 reference: Label,
262 suggestion: Option<Label>,
264 },
265 #[error(
267 "{}: {field} {reference} names {}, declared in {declared_in}",
268 .site,
269 .found.with_article()
270 )]
271 WrongReferenceKind {
272 site: Box<DeclarationSite>,
274 field: DeclarationField,
276 reference: Label,
278 found: DeclaredKind,
280 declared_in: Provenance,
282 },
283 #[error(
285 "{}: setting {name} is not declared{}",
286 .site,
287 suggestion_suffix(.suggestion.as_ref())
288 )]
289 UnknownSetting {
290 site: Box<DeclarationSite>,
293 name: String,
295 suggestion: Option<SettingName>,
297 },
298 #[error("dependency cycle: {}", cycle_path(.path))]
300 DependencyCycle {
301 path: Vec<DeclarationSite>,
304 },
305 #[error("{count} targets are more than a graph can number")]
307 TooManyTargets {
308 count: usize,
310 },
311 #[error("{}", refusal(.want, .site.as_deref(), .ceiling))]
313 Refused {
314 want: Want,
316 site: Option<Box<DeclarationSite>>,
319 ceiling: Box<Ceiling>,
321 },
322 #[error("{}: {}", .violation.site, .violation)]
324 PluginRefused {
325 violation: Box<PluginViolation>,
327 },
328 #[error("{}", denial(.reason, .unapproved))]
330 NotApproved {
331 unapproved: Box<WantedSet>,
333 reason: DenialReason,
335 },
336 #[error(
338 "{}: program {program} was not found",
339 .site
340 )]
341 MissingTool {
342 site: Box<DeclarationSite>,
344 program: Program,
346 },
347 #[error(
349 "{}: env must mark each variable \"key\" or \"unkeyed\", such as env = {{ HOME = \"unkeyed\" }}",
350 .site
351 )]
352 EnvNotMarked {
353 site: Box<DeclarationSite>,
355 },
356 #[error(
358 "{}: env {name} is marked {found}; mark it \"key\" or \"unkeyed\"",
359 .site
360 )]
361 EnvBadMark {
362 site: Box<DeclarationSite>,
364 name: EnvName,
366 found: String,
368 },
369 #[error(
372 "{}: the command holds this machine's path {folder}; it would give the target another \
373 key on every machine",
374 .site
375 )]
376 MachinePathInCommand {
377 site: Box<DeclarationSite>,
379 folder: String,
381 },
382 #[error(
384 "{}: the variable {name} holds this machine's path {folder}; mark it \"unkeyed\" if it \
385 only finds files",
386 .site
387 )]
388 MachinePathInVariable {
389 site: Box<DeclarationSite>,
391 name: EnvName,
393 folder: String,
395 },
396 #[error(
398 "{}: the setting {name} holds this machine's path {folder}; it would give the target \
399 another key on every machine",
400 .site
401 )]
402 MachinePathInSetting {
403 site: Box<DeclarationSite>,
405 name: SettingName,
407 folder: String,
409 },
410 #[error("{}: its output holds this machine's path {folder}", .site)]
412 MachinePathInDiscovery {
413 site: Box<DeclarationSite>,
415 folder: String,
417 },
418 #[error("{file}: {table} env.unkeyed lists {name}, which env.read does not")]
420 UnkeyedNotRead {
421 file: String,
423 table: String,
425 name: EnvName,
427 },
428 #[error(
430 "{}: env {name} is set to {value} by the sandbox and cannot be declared",
431 .site
432 )]
433 PinnedEnv {
434 name: EnvName,
436 value: EnvValue,
438 site: Box<DeclarationSite>,
440 },
441 #[error(
443 "{}: input {path} does not exist",
444 .site
445 )]
446 MissingInput {
447 site: Box<DeclarationSite>,
449 path: SourcePath,
451 },
452 #[error(
454 "{}: input {path} is {found}; an input must be a regular file",
455 .site
456 )]
457 InputNotAFile {
458 site: Box<DeclarationSite>,
460 path: SourcePath,
462 found: InputKind,
464 },
465 #[error("setting {name} is overridden but not declared")]
467 UnknownOverride {
468 name: SettingName,
470 },
471 #[error(
473 "target {label} was asked for but is not declared{}",
474 suggestion_suffix(.suggestion.as_ref())
475 )]
476 UnknownTarget {
477 label: Label,
479 suggestion: Option<Label>,
481 },
482 #[error(
484 "target {asked} was asked for as a test, but {} is declared with {} in {}",
485 .site.label,
486 .declared_with.declaring_function(),
487 .site.located()
488 )]
489 NotATest {
490 asked: Label,
492 declared_with: TargetRole,
494 site: Box<DeclarationSite>,
497 },
498 #[error("query `{expression}` is not deps(<target>) or rdeps(<target>)")]
500 InvalidQuery {
501 expression: String,
503 },
504 #[error(
506 "target {label} has no run in the log{}{}",
507 suggestion_suffix(.suggestion.as_ref()),
508 damaged_suffix(.damaged)
509 )]
510 NoRun {
511 label: Label,
513 suggestion: Option<Label>,
515 damaged: Vec<NonZeroUsize>,
518 },
519 #[error("target {label}: the output of its last logged run is no longer in the store")]
521 MissingOutput {
522 label: Label,
524 },
525 #[error("the plan was not made from this graph")]
527 ForeignPlan,
528 #[error("{}", which.diagnostic())]
534 UploadUnsandboxed {
535 which: UnsandboxedRemote,
537 },
538 #[error(
543 "the remote cache token from {} cannot be used: it is missing or unreadable, \
544 or it holds a character a header cannot carry",
545 token_source(.from)
546 )]
547 RemoteToken {
548 from: TokenSource,
550 },
551 #[error("{name} is {value:?}, and must be 1 or 0")]
553 RemoteSwitch {
554 name: RemoteVariable,
556 value: String,
558 },
559 #[error("{conflict}")]
561 RemoteFlags {
562 conflict: RemoteFlagConflict,
564 },
565 #[error(
568 "{path}: {} ({}) and {} ({}) cannot both write here",
569 .first.label,
570 .first.located(),
571 .second.label,
572 .second.located()
573 )]
574 OutputConflict {
575 path: OutputPath,
577 first: Box<DeclarationSite>,
579 second: Box<DeclarationSite>,
581 },
582 #[error(
585 "{}: the command names no program once expanded",
586 .site
587 )]
588 NoProgram {
589 site: Box<DeclarationSite>,
591 },
592 #[error("{}", lost_by_the_dispatcher(.targets))]
598 DispatcherFault {
599 targets: Vec<Label>,
601 },
602 #[error("{}", lost_build_files(.directories))]
607 LostBuildFiles {
608 directories: Vec<Directory>,
610 },
611 #[error("{port}: {diagnostic}")]
613 Adapter {
614 port: PortName,
616 diagnostic: Diagnostic,
618 },
619 #[error("not a tree: {fault}")]
621 InvalidTree {
622 fault: TreeFault,
624 },
625 #[error(
627 "plugin {plugin}: {} is not a regular file with a Unicode name; a plugin holds regular files only",
628 .path.display()
629 )]
630 PluginTree {
631 plugin: PluginName,
633 path: PathBuf,
635 },
636 #[error("plugin {plugin} is not fetched: {reason}")]
640 PluginNotFetched {
641 plugin: PluginName,
643 reason: String,
645 },
646 #[error("plugin {plugin} was changed after it was fetched: {reason}")]
649 PluginChanged {
650 plugin: PluginName,
652 reason: String,
654 },
655 #[error("plugin {plugin} could not be fetched: {diagnostic}")]
658 PluginFetch {
659 plugin: PluginName,
661 diagnostic: Diagnostic,
663 },
664}
665
666fn lost_build_files(directories: &[Directory]) -> String {
669 let shown: Vec<String> = directories.iter().map(|d| format!("//{d}")).collect();
670 format!(
671 "{}: returned without evaluating the build files of {}",
672 PortName::Dispatcher,
673 shown.join(", ")
674 )
675}
676
677fn lost_by_the_dispatcher(targets: &[Label]) -> String {
680 let labels: Vec<String> = targets.iter().map(ToString::to_string).collect();
681 format!(
682 "{}: returned without an outcome for {}",
683 PortName::Dispatcher,
684 labels.join(", ")
685 )
686}
687
688fn token_source(from: &TokenSource) -> String {
690 match from {
691 TokenSource::Env(name) => format!("environment variable {name}"),
692 TokenSource::File(path) => format!("file {path}"),
693 }
694}
695
696fn requested_by_suffix(requested_by: Option<&Provenance>) -> String {
698 requested_by.map_or_else(
699 || " (the workspace root)".to_owned(),
700 |provenance| format!(" (requested by {provenance})"),
701 )
702}
703
704fn sites_list(sites: &[Provenance]) -> String {
706 let rendered: Vec<String> = sites.iter().map(ToString::to_string).collect();
707 rendered.join(", ")
708}
709
710fn declaring_sites(sites: &[DeclarationSite]) -> String {
713 let rendered: Vec<String> = sites
714 .iter()
715 .map(|site| format!("{}{}", site.provenance, plugin_suffix(&site.origin)))
716 .collect();
717 rendered.join(", ")
718}
719
720fn plugin_suffix(origin: &Origin) -> String {
722 match origin {
723 Origin::BuildFile => String::new(),
724 chain @ Origin::Plugins(_) => format!(" (plugin {chain})"),
725 }
726}
727
728const fn ignored_field(path: &IgnoredPath) -> &'static str {
731 match path {
732 IgnoredPath::Input(_) => "inputs",
733 IgnoredPath::Subdir(_) => "subdir",
734 }
735}
736
737fn line_suffix(line: Option<u32>) -> String {
739 line.map_or_else(String::new, |line| format!(":{line}"))
740}
741
742fn suggestion_suffix<T: fmt::Display>(suggestion: Option<&T>) -> String {
744 suggestion.map_or_else(String::new, |nearest| format!(" (did you mean {nearest}?)"))
745}
746
747fn damaged_suffix(damaged: &[NonZeroUsize]) -> String {
749 let numbers: Vec<String> = damaged.iter().map(ToString::to_string).collect();
750 match numbers.as_slice() {
751 [] => String::new(),
752 [only] => format!("; 1 damaged line was skipped (line {only})"),
753 many => format!(
754 "; {} damaged lines were skipped (lines {})",
755 many.len(),
756 many.join(", ")
757 ),
758 }
759}
760
761fn cycle_path(path: &[DeclarationSite]) -> String {
763 let mut rendered: Vec<String> = path
764 .iter()
765 .map(|site| format!("{} ({})", site.label, site.located()))
766 .collect();
767 if let Some(first) = path.first() {
768 rendered.push(first.label.to_string());
769 }
770 rendered.join(" -> ")
771}
772
773fn denial(reason: &DenialReason, unapproved: &WantedSet) -> String {
776 if unapproved.is_empty() {
777 reason.to_string()
778 } else {
779 format!("{reason}\n{unapproved}")
780 }
781}
782
783fn refusal(want: &Want, site: Option<&DeclarationSite>, ceiling: &Ceiling) -> String {
785 let (wanted, list, allowed) = match want {
786 Want::Program(program) => (
787 format!("program {program}"),
788 "proc.run",
789 allowed_list(&ceiling.run),
790 ),
791 Want::Env(name) => (
792 format!("environment variable {name}"),
793 "env.read",
794 allowed_list(&ceiling.env),
795 ),
796 Want::Unkeyed(name) => (
797 format!("unkeyed variable {name}"),
798 "env.unkeyed",
799 allowed_list(&ceiling.unkeyed),
800 ),
801 Want::Read(path) => (
802 format!("input {path}"),
803 "fs.read",
804 allowed_list(ceiling.read.iter().map(directory_text)),
805 ),
806 Want::Write(directory) => (
807 format!("directory {}", directory_text(directory)),
808 "fs.write",
809 allowed_list(ceiling.write.iter().map(directory_text)),
810 ),
811 Want::Network(label) => (
812 format!("network of {label}"),
813 "network",
814 "nothing".to_owned(),
815 ),
816 };
817 let holder = site.map_or_else(String::new, |site| format!("{site}: "));
818 format!("{holder}{wanted} is outside the ceiling ({list} allows: {allowed})")
819}
820
821pub(crate) fn allowed_list<T: fmt::Display>(entries: impl IntoIterator<Item = T>) -> String {
823 let rendered: Vec<String> = entries.into_iter().map(|entry| entry.to_string()).collect();
824 if rendered.is_empty() {
825 "nothing".to_owned()
826 } else {
827 rendered.join(", ")
828 }
829}
830
831pub(crate) fn directory_text(directory: &Directory) -> &str {
833 if directory.is_root() {
834 "."
835 } else {
836 directory.as_str()
837 }
838}
839
840#[derive(Debug, Clone, Copy, PartialEq, Eq)]
842#[non_exhaustive]
843pub enum DeclaredKind {
844 Target,
846 Rule,
848 Alias,
850}
851
852impl DeclaredKind {
853 const fn with_article(self) -> &'static str {
855 match self {
856 Self::Target => "a target",
857 Self::Rule => "a rule",
858 Self::Alias => "an alias",
859 }
860 }
861}
862
863impl fmt::Display for DeclaredKind {
864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
865 f.write_str(match self {
866 Self::Target => "target",
867 Self::Rule => "rule",
868 Self::Alias => "alias",
869 })
870 }
871}
872
873#[derive(Debug, Clone, PartialEq, Eq)]
880pub struct DeclarationSite {
881 pub label: Label,
883 pub provenance: Provenance,
885 pub origin: Origin,
887}
888
889impl DeclarationSite {
890 fn located(&self) -> String {
893 match &self.origin {
894 Origin::BuildFile => self.provenance.to_string(),
895 chain @ Origin::Plugins(_) => format!("{}, plugin {chain}", self.provenance),
896 }
897 }
898}
899
900impl fmt::Display for DeclarationSite {
901 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902 write!(
903 f,
904 "{}: {}{}",
905 self.provenance,
906 self.label,
907 plugin_suffix(&self.origin)
908 )
909 }
910}
911
912impl From<&Node> for DeclarationSite {
913 fn from(node: &Node) -> Self {
915 Self {
916 label: node.label.clone(),
917 provenance: node.provenance.clone(),
918 origin: node.origin.clone(),
919 }
920 }
921}
922
923#[derive(Debug, Clone, Copy, PartialEq, Eq)]
927#[non_exhaustive]
928pub enum PortName {
929 Manifest,
931 Host,
933 Digester,
935 StatCache,
937 ToolResolver,
939 ActionCache,
941 ContentStore,
943 EventLog,
945 RunHistory,
947 ExecStrategy,
949 Dispatcher,
951 GraphRecord,
953 Sweep,
955 Approver,
957 PluginStore,
959 RemoteCache,
961 Changes,
963}
964
965impl fmt::Display for PortName {
966 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
967 f.write_str(match self {
968 Self::Manifest => "manifest",
969 Self::Host => "host",
970 Self::Digester => "digester",
971 Self::StatCache => "stat cache",
972 Self::ToolResolver => "tool resolver",
973 Self::ActionCache => "action cache",
974 Self::ContentStore => "content store",
975 Self::EventLog => "event log",
976 Self::RunHistory => "run history",
977 Self::ExecStrategy => "exec strategy",
978 Self::Dispatcher => "dispatcher",
979 Self::GraphRecord => "graph record",
980 Self::Sweep => "sweep",
981 Self::Approver => "approver",
982 Self::PluginStore => "plugin store",
983 Self::RemoteCache => "remote cache",
984 Self::Changes => "file watcher",
985 })
986 }
987}
988
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
991#[non_exhaustive]
992pub enum EvaluationLimit {
993 Instructions,
995 Memory,
997 Staging,
1000 Walk,
1002}
1003
1004impl fmt::Display for EvaluationLimit {
1005 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1006 f.write_str(match self {
1007 Self::Instructions => "instruction ceiling",
1008 Self::Memory => "memory ceiling",
1009 Self::Staging => "staging cap",
1010 Self::Walk => "walk cap",
1011 })
1012 }
1013}
1014
1015#[derive(Debug, Clone, PartialEq, Eq)]
1020#[non_exhaustive]
1021pub enum EvaluationFailure {
1022 Syntax,
1024 Runtime,
1026 Refused,
1028 LimitReached {
1030 limit: EvaluationLimit,
1032 },
1033 UnknownField {
1035 field: Written<FieldName>,
1037 },
1038 WrongFieldType {
1040 field: Written<FieldName>,
1042 },
1043}
1044
1045impl fmt::Display for EvaluationFailure {
1046 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1047 match self {
1048 Self::Syntax => f.write_str("syntax error"),
1049 Self::Runtime => f.write_str("runtime error"),
1050 Self::Refused => f.write_str("operation refused"),
1051 Self::LimitReached { limit } => write!(f, "{limit} reached"),
1052 Self::UnknownField { field } => write!(f, "unknown field {:?}", field.as_written()),
1053 Self::WrongFieldType { field } => {
1054 write!(f, "field {:?} has the wrong type", field.as_written())
1055 }
1056 }
1057 }
1058}
1059
1060#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1062#[non_exhaustive]
1063pub enum DeclarationField {
1064 Name,
1066 Dep,
1068 Input,
1070 Output,
1072 Env,
1074 Run,
1076 Rule,
1078 Description,
1080 Target,
1082 SettingName,
1084 SettingValue,
1086 Freshness,
1088 Stdout,
1090 Subdir,
1092}
1093
1094impl fmt::Display for DeclarationField {
1095 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 f.write_str(match self {
1097 Self::Name => "name",
1098 Self::Dep => "dep",
1099 Self::Input => "input",
1100 Self::Output => "output",
1101 Self::Env => "env",
1102 Self::Run => "run",
1103 Self::Rule => "rule",
1104 Self::Description => "description",
1105 Self::Target => "target",
1106 Self::SettingName => "setting name",
1107 Self::SettingValue => "setting value",
1108 Self::Freshness => "freshness",
1109 Self::Stdout => "stdout",
1110 Self::Subdir => "subdir",
1111 })
1112 }
1113}
1114
1115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1117pub enum ActionFound {
1118 Both,
1120 Neither,
1122}
1123
1124impl fmt::Display for ActionFound {
1125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 f.write_str(match self {
1127 Self::Both => "both 'rule' and 'run'",
1128 Self::Neither => "neither 'rule' nor 'run'",
1129 })
1130 }
1131}
1132
1133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1137#[non_exhaustive]
1138pub enum UnsandboxedRemote {
1139 Upload,
1141 Execute,
1144}
1145
1146impl UnsandboxedRemote {
1147 const fn diagnostic(self) -> &'static str {
1149 match self {
1150 Self::Upload => {
1151 "uploading to the remote cache needs actions to run in the input sandbox, \
1152 but strategy is \"bare\"; set strategy to \"sandbox\", or stop uploading by \
1153 unsetting BUILDL_REMOTE_UPLOAD or dropping --remote-upload"
1154 }
1155 Self::Execute => {
1156 "executing on the remote needs actions to run in the input sandbox, \
1157 but strategy is \"bare\"; set strategy to \"sandbox\", or stop executing by \
1158 setting execute to false in [remote], unsetting BUILDL_REMOTE_EXECUTE or \
1159 dropping --remote-execute"
1160 }
1161 }
1162 }
1163}
1164
1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1169#[non_exhaustive]
1170pub enum RemoteVariable {
1171 Upload,
1173 Strict,
1175 Execute,
1177}
1178
1179impl fmt::Display for RemoteVariable {
1180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181 f.write_str(match self {
1182 Self::Upload => "BUILDL_REMOTE_UPLOAD",
1183 Self::Strict => "BUILDL_REMOTE_STRICT",
1184 Self::Execute => "BUILDL_REMOTE_EXECUTE",
1185 })
1186 }
1187}
1188
1189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1193#[non_exhaustive]
1194pub enum RemoteFlagConflict {
1195 NoRemoteWithSwitch,
1197 SwitchWithoutRemote,
1200 NoRemoteWithExecute,
1202 ExecuteBothWays,
1204 ExecutionWithoutRemote,
1207 JobsWithoutExecution,
1209}
1210
1211impl fmt::Display for RemoteFlagConflict {
1212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1213 f.write_str(match self {
1214 Self::NoRemoteWithSwitch => {
1215 "--no-remote cannot be combined with --remote-upload or --remote-strict"
1216 }
1217 Self::SwitchWithoutRemote => {
1218 "--remote-upload and --remote-strict need a [remote] table in buildl.toml, \
1219 and this workspace has none"
1220 }
1221 Self::NoRemoteWithExecute => "--no-remote cannot be combined with --remote-execute",
1222 Self::ExecuteBothWays => "--remote-execute cannot be combined with --no-remote-execute",
1223 Self::ExecutionWithoutRemote => {
1224 "--remote-execute, --no-remote-execute and --remote-jobs need a [remote] table \
1225 in buildl.toml, and this workspace has none"
1226 }
1227 Self::JobsWithoutExecution => {
1228 "--remote-jobs needs remote execution, and it is off in this run"
1229 }
1230 })
1231 }
1232}
1233
1234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1239#[non_exhaustive]
1240pub enum NameKind {
1241 Directory,
1243 TargetName,
1245 Label,
1247 Digest,
1249 SourcePath,
1251 OutputName,
1253 EnvName,
1255 Argument,
1257 Command,
1259 Description,
1261 SettingName,
1263 SettingValue,
1265 EntryName,
1267 FieldName,
1269 Program,
1271 EnvValue,
1273 Platform,
1275 Workers,
1277 Timeout,
1279 Isolation,
1281 Approver,
1283 TreePath,
1285 EnvMark,
1287 PluginName,
1289 PluginVersion,
1291 PluginChain,
1293 CommitId,
1295 TagName,
1297 GitUrl,
1299 RemoteUrl,
1301 InstanceName,
1303 HostPath,
1305 HeaderName,
1307 ChangedPath,
1309 RemoteJobs,
1311 RetryCount,
1313 PlatformProperty,
1315}
1316
1317impl fmt::Display for NameKind {
1318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1319 f.write_str(match self {
1320 Self::Directory => "directory",
1321 Self::TargetName => "target name",
1322 Self::Label => "label",
1323 Self::Digest => "digest",
1324 Self::SourcePath => "source path",
1325 Self::OutputName => "output name",
1326 Self::EnvName => "environment variable name",
1327 Self::Argument => "argument",
1328 Self::Command => "command",
1329 Self::Description => "description",
1330 Self::SettingName => "setting name",
1331 Self::SettingValue => "setting value",
1332 Self::EntryName => "entry file name",
1333 Self::FieldName => "field name",
1334 Self::Program => "program",
1335 Self::EnvValue => "environment variable value",
1336 Self::Platform => "platform",
1337 Self::Workers => "worker count",
1338 Self::Timeout => "timeout",
1339 Self::Isolation => "execution strategy",
1340 Self::Approver => "approver mode",
1341 Self::TreePath => "tree path",
1342 Self::EnvMark => "environment variable mark",
1343 Self::PluginName => "plugin name",
1344 Self::PluginVersion => "plugin version",
1345 Self::PluginChain => "plugin chain",
1346 Self::CommitId => "commit id",
1347 Self::TagName => "tag name",
1348 Self::GitUrl => "git URL",
1349 Self::RemoteUrl => "remote cache URL",
1350 Self::InstanceName => "instance name",
1351 Self::HostPath => "host path",
1352 Self::HeaderName => "header name",
1353 Self::ChangedPath => "changed path",
1354 Self::RemoteJobs => "remote job count",
1355 Self::RetryCount => "retry count",
1356 Self::PlatformProperty => "platform property name",
1357 })
1358 }
1359}
1360
1361#[derive(Debug, Clone, PartialEq, Eq)]
1365#[non_exhaustive]
1366pub enum TreeFault {
1367 Empty,
1369 Repeated(TreePath),
1371 Clash(TreePath),
1373}
1374
1375impl fmt::Display for TreeFault {
1376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1377 match self {
1378 Self::Empty => f.write_str("it holds no file"),
1379 Self::Repeated(path) => write!(f, "{path} is listed twice"),
1380 Self::Clash(path) => write!(f, "{path} is both a file and a directory"),
1381 }
1382 }
1383}
1384
1385#[cfg(test)]
1386mod tests {
1387 #![expect(
1388 clippy::unwrap_used,
1389 reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
1390 )]
1391
1392 use std::collections::{BTreeMap, BTreeSet};
1393 use std::num::NonZeroUsize;
1394 use std::path::PathBuf;
1395
1396 use super::{
1397 ActionFound, DeclarationField, DeclarationSite, DeclaredKind, Error, EvaluationFailure,
1398 EvaluationLimit, NameKind, PortName, RemoteFlagConflict, RemoteVariable, TreeFault,
1399 UnsandboxedRemote,
1400 };
1401 use crate::types::{
1402 Argument, Ceiling, Command, DeclarationOrder, DenialReason, Diagnostic, Directory, EnvName,
1403 EnvValue, FieldName, Freshness, HostPath, IgnoredPath, Ignoring, InputKind, Label,
1404 NetworkAccess, Node, Origin, OutputName, OutputPath, OutputSource, PluginName, PluginRef,
1405 PluginVersion, PluginViolation, Program, Provenance, RemoteUrl, SettingName, SourcePath,
1406 TargetName, TargetRole, TokenSource, TreePath, Want, WantedSet, Written,
1407 };
1408
1409 fn lib_file() -> Provenance {
1410 Provenance::new(
1411 PathBuf::from("lib/build.lua"),
1412 Directory::parse("lib").unwrap(),
1413 )
1414 }
1415
1416 fn root_file() -> Provenance {
1417 Provenance::new(PathBuf::from("build.lua"), Directory::root())
1418 }
1419
1420 fn tools_file() -> Provenance {
1421 Provenance::new(
1422 PathBuf::from("tools/build.lua"),
1423 Directory::parse("tools").unwrap(),
1424 )
1425 }
1426
1427 fn label(raw: &str) -> Label {
1428 Label::parse(raw).unwrap()
1429 }
1430
1431 fn root_site(raw: &str) -> DeclarationSite {
1433 DeclarationSite {
1434 label: label(raw),
1435 provenance: root_file(),
1436 origin: Origin::BuildFile,
1437 }
1438 }
1439
1440 #[test]
1441 fn duplicate_label_names_every_site() {
1442 let err = Error::DuplicateLabel {
1443 label: label("//:a"),
1444 sites: vec![root_site("//:a"), root_site("//:a")],
1445 };
1446 assert_eq!(
1447 err.to_string(),
1448 "//:a is declared more than once: build.lua, build.lua"
1449 );
1450 }
1451
1452 #[test]
1453 fn duplicate_label_names_the_plugin_chain_of_the_declaration_a_plugin_made() {
1454 let err = Error::DuplicateLabel {
1455 label: label("//:a"),
1456 sites: vec![
1457 root_site("//:a"),
1458 DeclarationSite {
1459 origin: ourgo_chain(),
1460 ..root_site("//:a")
1461 },
1462 ],
1463 };
1464 assert_eq!(
1465 err.to_string(),
1466 "//:a is declared more than once: build.lua, build.lua (plugin ourgo@0.1.0 > go@1.2.0)"
1467 );
1468 }
1469
1470 #[test]
1471 fn duplicate_setting_names_every_site() {
1472 let err = Error::DuplicateSetting {
1473 name: SettingName::parse("test_filter").unwrap(),
1474 sites: vec![root_file(), lib_file()],
1475 };
1476 assert_eq!(
1477 err.to_string(),
1478 "setting test_filter is declared more than once: build.lua, lib/build.lua"
1479 );
1480 }
1481
1482 #[test]
1483 fn unknown_reference_names_the_site_the_field_and_the_nearest_label() {
1484 let err = Error::UnknownReference {
1485 site: Box::new(root_site("//:app")),
1486 field: DeclarationField::Dep,
1487 reference: label("//:mian.o"),
1488 suggestion: Some(label("//:main.o")),
1489 };
1490 assert_eq!(
1491 err.to_string(),
1492 "build.lua: //:app: dep //:mian.o is not declared (did you mean //:main.o?)"
1493 );
1494 }
1495
1496 #[test]
1497 fn unknown_reference_without_a_near_label_offers_nothing() {
1498 let err = Error::UnknownReference {
1499 site: Box::new(root_site("//:default")),
1500 field: DeclarationField::Target,
1501 reference: label("//:nope"),
1502 suggestion: None,
1503 };
1504 assert_eq!(
1505 err.to_string(),
1506 "build.lua: //:default: target //:nope is not declared"
1507 );
1508 }
1509
1510 #[test]
1511 fn wrong_reference_kind_names_what_was_found_and_where() {
1512 let err = Error::WrongReferenceKind {
1513 site: Box::new(root_site("//:app")),
1514 field: DeclarationField::Dep,
1515 reference: label("//:cc"),
1516 found: DeclaredKind::Rule,
1517 declared_in: tools_file(),
1518 };
1519 assert_eq!(
1520 err.to_string(),
1521 "build.lua: //:app: dep //:cc names a rule, declared in tools/build.lua"
1522 );
1523 }
1524
1525 #[test]
1526 fn every_declared_kind_renders_alone_and_in_a_sentence() {
1527 let cases = [
1528 (DeclaredKind::Target, "target", "names a target,"),
1529 (DeclaredKind::Rule, "rule", "names a rule,"),
1530 (DeclaredKind::Alias, "alias", "names an alias,"),
1531 ];
1532 for (found, alone, in_a_sentence) in cases {
1533 assert_eq!(found.to_string(), alone);
1534 let err = Error::WrongReferenceKind {
1535 site: Box::new(root_site("//:app")),
1536 field: DeclarationField::Rule,
1537 reference: label("//:x"),
1538 found,
1539 declared_in: root_file(),
1540 };
1541 assert!(err.to_string().contains(in_a_sentence), "{err}");
1542 }
1543 }
1544
1545 #[test]
1546 fn unknown_setting_names_the_site_and_the_nearest_setting() {
1547 let err = Error::UnknownSetting {
1548 site: Box::new(root_site("//:go_test")),
1549 name: "test_fliter".to_owned(),
1550 suggestion: Some(SettingName::parse("test_filter").unwrap()),
1551 };
1552 assert_eq!(
1553 err.to_string(),
1554 "build.lua: //:go_test: setting test_fliter is not declared \
1555 (did you mean test_filter?)"
1556 );
1557 }
1558
1559 #[test]
1560 fn dependency_cycle_lists_every_target_and_closes_on_the_first() {
1561 let err = Error::DependencyCycle {
1562 path: vec![
1563 DeclarationSite {
1564 label: label("//:a"),
1565 provenance: root_file(),
1566 origin: Origin::BuildFile,
1567 },
1568 DeclarationSite {
1569 label: label("//lib:b"),
1570 provenance: lib_file(),
1571 origin: Origin::BuildFile,
1572 },
1573 ],
1574 };
1575 assert_eq!(
1576 err.to_string(),
1577 "dependency cycle: //:a (build.lua) -> //lib:b (lib/build.lua) -> //:a"
1578 );
1579 }
1580
1581 #[test]
1582 fn a_cycle_of_one_names_its_target_twice() {
1583 let err = Error::DependencyCycle {
1584 path: vec![DeclarationSite {
1585 label: label("//:a"),
1586 provenance: root_file(),
1587 origin: Origin::BuildFile,
1588 }],
1589 };
1590 assert_eq!(
1591 err.to_string(),
1592 "dependency cycle: //:a (build.lua) -> //:a"
1593 );
1594 }
1595
1596 #[test]
1597 fn too_many_targets_states_the_count() {
1598 let err = Error::TooManyTargets { count: 7 };
1599 assert_eq!(
1600 err.to_string(),
1601 "7 targets are more than a graph can number"
1602 );
1603 }
1604
1605 #[test]
1606 fn a_site_is_a_nodes_label_and_its_build_file() {
1607 let node = Node {
1608 label: label("//lib:text"),
1609 provenance: lib_file(),
1610 origin: Origin::BuildFile,
1611 narrowing: Vec::new(),
1612 role: TargetRole::Build,
1613 run: Command::new(vec![Argument::parse("cc").unwrap()]).unwrap(),
1614 description: None,
1615 inputs: Vec::new(),
1616 outputs: vec![OutputName::parse("text").unwrap()],
1617 env: BTreeMap::new(),
1618 network: NetworkAccess::Sealed,
1619 output_source: OutputSource::Command,
1620 freshness: Freshness::Cached,
1621 };
1622 assert_eq!(
1623 DeclarationSite::from(&node),
1624 DeclarationSite {
1625 label: label("//lib:text"),
1626 provenance: lib_file(),
1627 origin: Origin::BuildFile,
1628 }
1629 );
1630 }
1631
1632 fn ourgo_chain() -> Origin {
1634 let plugin = |name: &str, version: &str| PluginRef {
1635 unkeyed: BTreeSet::new(),
1636 name: PluginName::parse(name).unwrap(),
1637 version: PluginVersion::parse(version).unwrap(),
1638 run: BTreeSet::new(),
1639 env: BTreeSet::new(),
1640 };
1641 Origin::plugins(vec![plugin("ourgo", "0.1.0"), plugin("go", "1.2.0")]).unwrap()
1642 }
1643
1644 #[test]
1645 fn a_site_with_a_plugin_origin_names_the_chain() {
1646 let site = DeclarationSite {
1647 origin: ourgo_chain(),
1648 ..root_site("//:app")
1649 };
1650 assert_eq!(
1651 site.to_string(),
1652 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.2.0)"
1653 );
1654 let missing = Error::MissingTool {
1655 site: Box::new(site.clone()),
1656 program: Program::parse("cc").unwrap(),
1657 };
1658 assert_eq!(
1659 missing.to_string(),
1660 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.2.0): program cc was not found"
1661 );
1662 let cycle = Error::DependencyCycle { path: vec![site] };
1663 assert_eq!(
1664 cycle.to_string(),
1665 "dependency cycle: //:app (build.lua, plugin ourgo@0.1.0 > go@1.2.0) -> //:app"
1666 );
1667 }
1668
1669 #[test]
1670 fn a_build_file_site_reads_as_today() {
1671 assert_eq!(root_site("//:app").to_string(), "build.lua: //:app");
1672 let err = Error::MissingTool {
1673 site: Box::new(root_site("//:app")),
1674 program: Program::parse("cc").unwrap(),
1675 };
1676 assert_eq!(
1677 err.to_string(),
1678 "build.lua: //:app: program cc was not found"
1679 );
1680 }
1681
1682 #[test]
1683 fn missing_tool_names_the_site_and_the_program() {
1684 let err = Error::MissingTool {
1685 site: Box::new(root_site("//:app")),
1686 program: Program::parse("cc").unwrap(),
1687 };
1688 assert_eq!(
1689 err.to_string(),
1690 "build.lua: //:app: program cc was not found"
1691 );
1692 }
1693
1694 #[test]
1695 fn pinned_env_renders_its_site_name_and_value() {
1696 let err = Error::PinnedEnv {
1697 name: EnvName::parse("TZ").unwrap(),
1698 value: EnvValue::parse("UTC").unwrap(),
1699 site: Box::new(root_site("//a:y")),
1700 };
1701 assert_eq!(
1702 err.to_string(),
1703 "build.lua: //a:y: env TZ is set to UTC by the sandbox and cannot be declared"
1704 );
1705 }
1706
1707 #[test]
1708 fn missing_input_names_the_site_and_the_path() {
1709 let err = Error::MissingInput {
1710 site: Box::new(root_site("//:app")),
1711 path: SourcePath::parse("src/main.c").unwrap(),
1712 };
1713 assert_eq!(
1714 err.to_string(),
1715 "build.lua: //:app: input src/main.c does not exist"
1716 );
1717 }
1718
1719 #[test]
1720 fn an_input_that_is_not_a_file_names_the_site_the_path_and_what_was_found() {
1721 for (found, text) in [
1722 (
1723 InputKind::Directory,
1724 "build.lua: //:app: input src is a directory; an input must be a regular file",
1725 ),
1726 (
1727 InputKind::Symlink,
1728 "build.lua: //:app: input src is a symbolic link; an input must be a regular file",
1729 ),
1730 (
1731 InputKind::Special,
1732 "build.lua: //:app: input src is a pipe, a socket or a device; an input must be a regular file",
1733 ),
1734 ] {
1735 let err = Error::InputNotAFile {
1736 site: Box::new(root_site("//:app")),
1737 path: SourcePath::parse("src").unwrap(),
1738 found,
1739 };
1740 assert_eq!(err.to_string(), text);
1741 }
1742 }
1743
1744 fn ceiling() -> Ceiling {
1746 Ceiling {
1747 unkeyed: BTreeSet::new(),
1748 run: ["cc", "ld"]
1749 .into_iter()
1750 .map(|raw| Program::parse(raw).unwrap())
1751 .collect(),
1752 env: ["PATH", "HOME"]
1753 .into_iter()
1754 .map(|raw| EnvName::parse(raw).unwrap())
1755 .collect(),
1756 read: BTreeSet::from([Directory::parse("src").unwrap()]),
1757 write: BTreeSet::new(),
1758 }
1759 }
1760
1761 #[test]
1762 fn not_approved_shows_its_reason_then_the_wants() {
1763 let err = Error::NotApproved {
1764 unapproved: Box::new(WantedSet {
1765 programs: BTreeSet::from([Program::parse("protoc").unwrap()]),
1766 env: BTreeSet::new(),
1767 unkeyed: BTreeSet::new(),
1768 write: BTreeSet::from([Directory::parse("out").unwrap()]),
1769 network: BTreeSet::new(),
1770 }),
1771 reason: DenialReason::new("not approved"),
1772 };
1773 assert_eq!(
1774 err.to_string(),
1775 "not approved\n run programs: protoc\n write into: out"
1776 );
1777 }
1778
1779 #[test]
1780 fn not_approved_with_nothing_unapproved_shows_only_its_reason() {
1781 let err = Error::NotApproved {
1782 unapproved: Box::new(WantedSet {
1783 programs: BTreeSet::new(),
1784 env: BTreeSet::new(),
1785 unkeyed: BTreeSet::new(),
1786 write: BTreeSet::new(),
1787 network: BTreeSet::new(),
1788 }),
1789 reason: DenialReason::new("not approved"),
1790 };
1791 assert_eq!(err.to_string(), "not approved");
1792 }
1793
1794 #[test]
1795 fn a_refused_program_names_the_site_and_what_may_run() {
1796 let err = Error::Refused {
1797 want: Want::Program(Program::parse("docker").unwrap()),
1798 site: Some(Box::new(root_site("//:image"))),
1799 ceiling: Box::new(ceiling()),
1800 };
1801 assert_eq!(
1802 err.to_string(),
1803 "build.lua: //:image: program docker is outside the ceiling (proc.run allows: cc, ld)"
1804 );
1805 }
1806
1807 fn violation(want: Want, allowed: &[&str]) -> Error {
1810 let plugin = |name: &str, version: &str| PluginRef {
1811 unkeyed: BTreeSet::new(),
1812 name: PluginName::parse(name).unwrap(),
1813 version: PluginVersion::parse(version).unwrap(),
1814 run: BTreeSet::new(),
1815 env: BTreeSet::new(),
1816 };
1817 let chain = vec![plugin("ourgo", "0.1.0"), plugin("go", "1.3.0")];
1818 Error::PluginRefused {
1819 violation: Box::new(PluginViolation {
1820 want,
1821 site: DeclarationSite {
1822 label: label("//:app"),
1823 provenance: root_file(),
1824 origin: Origin::plugins(chain.clone()).unwrap(),
1825 },
1826 plugin: chain[1].clone(),
1827 allowed: allowed.iter().map(|text| (*text).to_owned()).collect(),
1828 }),
1829 }
1830 }
1831
1832 #[test]
1833 fn a_plugin_tree_names_the_plugin_and_the_path() {
1834 let err = Error::PluginTree {
1835 plugin: PluginName::parse("go").unwrap(),
1836 path: PathBuf::from(".buildl/plugins/go/c0ffee/bin/link"),
1837 };
1838 assert_eq!(
1839 err.to_string(),
1840 "plugin go: .buildl/plugins/go/c0ffee/bin/link is not a regular file with a Unicode \
1841 name; a plugin holds regular files only"
1842 );
1843 }
1844
1845 #[test]
1846 fn a_plugin_not_fetched_names_the_plugin_and_the_reason() {
1847 let err = Error::PluginNotFetched {
1848 plugin: PluginName::parse("go").unwrap(),
1849 reason: "run `buildl plugins fetch`".to_owned(),
1850 };
1851 assert_eq!(
1852 err.to_string(),
1853 "plugin go is not fetched: run `buildl plugins fetch`"
1854 );
1855 }
1856
1857 #[test]
1858 fn a_plugin_changed_names_the_plugin_and_the_reason() {
1859 let err = Error::PluginChanged {
1860 plugin: PluginName::parse("go").unwrap(),
1861 reason: "its files differ from buildl.lock".to_owned(),
1862 };
1863 assert_eq!(
1864 err.to_string(),
1865 "plugin go was changed after it was fetched: its files differ from buildl.lock"
1866 );
1867 }
1868
1869 #[test]
1870 fn a_plugin_fetch_names_the_plugin_and_what_git_said() {
1871 let err = Error::PluginFetch {
1872 plugin: PluginName::parse("go").unwrap(),
1873 diagnostic: Diagnostic::new("fatal: couldn't find remote ref refs/tags/v9"),
1874 };
1875 assert_eq!(
1876 err.to_string(),
1877 "plugin go could not be fetched: fatal: couldn't find remote ref refs/tags/v9"
1878 );
1879 }
1880
1881 #[test]
1882 fn a_plugin_refused_program_names_the_site_the_plugin_and_what_it_allows() {
1883 let err = violation(Want::Program(Program::parse("curl").unwrap()), &["go"]);
1884 assert_eq!(
1885 err.to_string(),
1886 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): program curl is outside plugin \
1887 go@1.3.0 (proc.run allows: go)"
1888 );
1889 }
1890
1891 #[test]
1892 fn a_plugin_refused_variable_reads_like_a_refused_program() {
1893 let err = violation(Want::Env(EnvName::parse("HOME").unwrap()), &[]);
1894 assert_eq!(
1895 err.to_string(),
1896 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): environment variable HOME is \
1897 outside plugin go@1.3.0 (env.read allows: nothing)"
1898 );
1899 }
1900
1901 #[test]
1902 fn a_plugin_refused_unkeyed_variable_names_env_unkeyed() {
1903 let err = violation(Want::Unkeyed(EnvName::parse("HOME").unwrap()), &["PATH"]);
1904 assert_eq!(
1905 err.to_string(),
1906 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): unkeyed variable HOME is outside \
1907 plugin go@1.3.0 (env.unkeyed allows: PATH)"
1908 );
1909 }
1910
1911 #[test]
1912 fn a_plugin_refused_network_says_the_network_is_not_allowed() {
1913 let err = violation(Want::Network(label("//:app")), &[]);
1914 assert_eq!(
1915 err.to_string(),
1916 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): network is outside plugin \
1917 go@1.3.0 (network not allowed)"
1918 );
1919 }
1920
1921 #[test]
1922 fn an_unmarked_env_names_the_target_and_shows_the_form() {
1923 let err = Error::EnvNotMarked {
1924 site: Box::new(root_site("//:app")),
1925 };
1926 assert_eq!(
1927 err.to_string(),
1928 "build.lua: //:app: env must mark each variable \"key\" or \"unkeyed\", such as \
1929 env = { HOME = \"unkeyed\" }"
1930 );
1931 }
1932
1933 #[test]
1934 fn a_machine_path_in_a_command_names_the_target_and_the_folder() {
1935 let err = Error::MachinePathInCommand {
1936 site: Box::new(root_site("//:note")),
1937 folder: "/home/alice".to_owned(),
1938 };
1939 assert_eq!(
1940 err.to_string(),
1941 "build.lua: //:note: the command holds this machine's path /home/alice; it would \
1942 give the target another key on every machine"
1943 );
1944 }
1945
1946 #[test]
1947 fn a_machine_path_in_a_variable_names_the_variable_and_offers_unkeyed() {
1948 let err = Error::MachinePathInVariable {
1949 site: Box::new(root_site("//:app")),
1950 name: EnvName::parse("RUSTFLAGS").unwrap(),
1951 folder: "/home/alice".to_owned(),
1952 };
1953 assert_eq!(
1954 err.to_string(),
1955 "build.lua: //:app: the variable RUSTFLAGS holds this machine's path /home/alice; \
1956 mark it \"unkeyed\" if it only finds files"
1957 );
1958 }
1959
1960 #[test]
1961 fn a_machine_path_in_a_setting_names_the_setting_and_the_folder() {
1962 let err = Error::MachinePathInSetting {
1963 site: Box::new(root_site("//:setting")),
1964 name: SettingName::parse("prefix").unwrap(),
1965 folder: "/home/alice".to_owned(),
1966 };
1967 assert_eq!(
1968 err.to_string(),
1969 "build.lua: //:setting: the setting prefix holds this machine's path /home/alice; it \
1970 would give the target another key on every machine"
1971 );
1972 }
1973
1974 #[test]
1975 fn a_machine_path_in_a_discovery_output_names_the_target_and_the_folder() {
1976 let err = Error::MachinePathInDiscovery {
1977 site: Box::new(root_site("//:cargo.metadata")),
1978 folder: "/home/alice/shop".to_owned(),
1979 };
1980 assert_eq!(
1981 err.to_string(),
1982 "build.lua: //:cargo.metadata: its output holds this machine's path /home/alice/shop"
1983 );
1984 }
1985
1986 #[test]
1987 fn a_bad_mark_names_the_target_the_variable_and_the_mark() {
1988 let err = Error::EnvBadMark {
1989 site: Box::new(root_site("//:app")),
1990 name: EnvName::parse("HOME").unwrap(),
1991 found: "\"pass\"".to_owned(),
1992 };
1993 assert_eq!(
1994 err.to_string(),
1995 "build.lua: //:app: env HOME is marked \"pass\"; mark it \"key\" or \"unkeyed\""
1996 );
1997 }
1998
1999 #[test]
2000 fn a_refused_variable_names_the_site_and_what_may_be_read() {
2001 let err = Error::Refused {
2002 want: Want::Env(EnvName::parse("AWS_SECRET").unwrap()),
2003 site: Some(Box::new(root_site("//:app"))),
2004 ceiling: Box::new(ceiling()),
2005 };
2006 assert_eq!(
2007 err.to_string(),
2008 "build.lua: //:app: environment variable AWS_SECRET is outside the ceiling \
2009 (env.read allows: HOME, PATH)"
2010 );
2011 }
2012
2013 #[test]
2014 fn a_refused_input_names_the_site_and_where_inputs_may_lie() {
2015 let err = Error::Refused {
2016 want: Want::Read(SourcePath::parse("lib/key.pem").unwrap()),
2017 site: Some(Box::new(DeclarationSite {
2018 label: label("//lib:text"),
2019 provenance: lib_file(),
2020 origin: Origin::BuildFile,
2021 })),
2022 ceiling: Box::new(ceiling()),
2023 };
2024 assert_eq!(
2025 err.to_string(),
2026 "lib/build.lua: //lib:text: input lib/key.pem is outside the ceiling \
2027 (fs.read allows: src)"
2028 );
2029 }
2030
2031 #[test]
2032 fn a_refused_directory_has_no_site_and_an_empty_list_allows_nothing() {
2033 let err = Error::Refused {
2034 want: Want::Write(Directory::parse("out").unwrap()),
2035 site: None,
2036 ceiling: Box::new(ceiling()),
2037 };
2038 assert_eq!(
2039 err.to_string(),
2040 "directory out is outside the ceiling (fs.write allows: nothing)"
2041 );
2042 }
2043
2044 #[test]
2045 fn a_refused_network_reads_as_network() {
2046 let err = Error::Refused {
2047 want: Want::Network(Label::parse("//:fetch").unwrap()),
2048 site: None,
2049 ceiling: Box::new(ceiling()),
2050 };
2051 assert_eq!(
2052 err.to_string(),
2053 "network of //:fetch is outside the ceiling (network allows: nothing)"
2054 );
2055 }
2056
2057 #[test]
2058 fn the_workspace_root_renders_as_a_dot_in_a_refusal() {
2059 let mut allows_root = ceiling();
2060 allows_root.read = BTreeSet::from([Directory::root(), Directory::parse("src").unwrap()]);
2061 allows_root.write = BTreeSet::from([Directory::parse("out").unwrap()]);
2062 let read = Error::Refused {
2063 want: Want::Read(SourcePath::parse("lib/key.pem").unwrap()),
2064 site: Some(Box::new(root_site("//:app"))),
2065 ceiling: Box::new(allows_root.clone()),
2066 };
2067 assert_eq!(
2068 read.to_string(),
2069 "build.lua: //:app: input lib/key.pem is outside the ceiling (fs.read allows: ., src)"
2070 );
2071 let write = Error::Refused {
2072 want: Want::Write(Directory::root()),
2073 site: None,
2074 ceiling: Box::new(allows_root),
2075 };
2076 assert_eq!(
2077 write.to_string(),
2078 "directory . is outside the ceiling (fs.write allows: out)"
2079 );
2080 }
2081
2082 #[test]
2083 fn unknown_override_names_the_setting() {
2084 let err = Error::UnknownOverride {
2085 name: SettingName::parse("test_fliter").unwrap(),
2086 };
2087 assert_eq!(
2088 err.to_string(),
2089 "setting test_fliter is overridden but not declared"
2090 );
2091 }
2092
2093 #[test]
2094 fn unknown_target_names_the_label_and_the_nearest_one() {
2095 let err = Error::UnknownTarget {
2096 label: label("//:libs"),
2097 suggestion: Some(label("//:lib")),
2098 };
2099 assert_eq!(
2100 err.to_string(),
2101 "target //:libs was asked for but is not declared (did you mean //:lib?)"
2102 );
2103 }
2104
2105 #[test]
2106 fn unknown_target_without_a_near_label_offers_nothing() {
2107 let err = Error::UnknownTarget {
2108 label: label("//:nope"),
2109 suggestion: None,
2110 };
2111 assert_eq!(
2112 err.to_string(),
2113 "target //:nope was asked for but is not declared"
2114 );
2115 }
2116
2117 #[test]
2118 fn an_unreadable_token_names_where_it_was_to_come_from() {
2119 let env = Error::RemoteToken {
2120 from: TokenSource::Env(EnvName::parse("CACHE_TOKEN").unwrap()),
2121 };
2122 assert_eq!(
2123 env.to_string(),
2124 "the remote cache token from environment variable CACHE_TOKEN cannot be used: \
2125 it is missing or unreadable, or it holds a character a header cannot carry"
2126 );
2127 let file = Error::RemoteToken {
2128 from: TokenSource::File(HostPath::parse("secrets/token").unwrap()),
2129 };
2130 assert_eq!(
2131 file.to_string(),
2132 "the remote cache token from file secrets/token cannot be used: \
2133 it is missing or unreadable, or it holds a character a header cannot carry"
2134 );
2135 }
2136
2137 #[test]
2138 fn a_bad_switch_names_the_variable_and_what_it_holds() {
2139 let err = Error::RemoteSwitch {
2140 name: RemoteVariable::Upload,
2141 value: "yes".to_owned(),
2142 };
2143 assert_eq!(
2144 err.to_string(),
2145 "BUILDL_REMOTE_UPLOAD is \"yes\", and must be 1 or 0"
2146 );
2147 assert_eq!(RemoteVariable::Strict.to_string(), "BUILDL_REMOTE_STRICT");
2148 assert_eq!(RemoteVariable::Execute.to_string(), "BUILDL_REMOTE_EXECUTE");
2149 }
2150
2151 #[test]
2152 fn refused_flags_say_why() {
2153 let combined = Error::RemoteFlags {
2154 conflict: RemoteFlagConflict::NoRemoteWithSwitch,
2155 };
2156 let unnamed = Error::RemoteFlags {
2157 conflict: RemoteFlagConflict::SwitchWithoutRemote,
2158 };
2159 assert_eq!(
2160 combined.to_string(),
2161 "--no-remote cannot be combined with --remote-upload or --remote-strict"
2162 );
2163 assert_eq!(
2164 unnamed.to_string(),
2165 "--remote-upload and --remote-strict need a [remote] table in buildl.toml, \
2166 and this workspace has none"
2167 );
2168 }
2169
2170 #[test]
2171 fn refused_execution_flags_name_the_flags() {
2172 let text = |conflict| Error::RemoteFlags { conflict }.to_string();
2173 assert_eq!(
2174 text(RemoteFlagConflict::NoRemoteWithExecute),
2175 "--no-remote cannot be combined with --remote-execute"
2176 );
2177 assert_eq!(
2178 text(RemoteFlagConflict::ExecuteBothWays),
2179 "--remote-execute cannot be combined with --no-remote-execute"
2180 );
2181 assert_eq!(
2182 text(RemoteFlagConflict::ExecutionWithoutRemote),
2183 "--remote-execute, --no-remote-execute and --remote-jobs need a [remote] table \
2184 in buildl.toml, and this workspace has none"
2185 );
2186 assert_eq!(
2187 text(RemoteFlagConflict::JobsWithoutExecution),
2188 "--remote-jobs needs remote execution, and it is off in this run"
2189 );
2190 }
2191
2192 #[test]
2193 fn an_unsandboxed_upload_says_how_to_sandbox_or_stop_uploading() {
2194 assert_eq!(
2195 Error::UploadUnsandboxed {
2196 which: UnsandboxedRemote::Upload
2197 }
2198 .to_string(),
2199 "uploading to the remote cache needs actions to run in the input sandbox, \
2200 but strategy is \"bare\"; set strategy to \"sandbox\", or stop uploading by \
2201 unsetting BUILDL_REMOTE_UPLOAD or dropping --remote-upload"
2202 );
2203 }
2204
2205 #[test]
2206 fn an_unsandboxed_execution_says_how_to_sandbox_or_stop_executing() {
2207 assert_eq!(
2208 Error::UploadUnsandboxed {
2209 which: UnsandboxedRemote::Execute
2210 }
2211 .to_string(),
2212 "executing on the remote needs actions to run in the input sandbox, \
2213 but strategy is \"bare\"; set strategy to \"sandbox\", or stop executing by \
2214 setting execute to false in [remote], unsetting BUILDL_REMOTE_EXECUTE or \
2215 dropping --remote-execute"
2216 );
2217 }
2218
2219 #[test]
2220 fn not_a_test_names_the_target_and_its_file() {
2221 let err = Error::NotATest {
2222 asked: label("//:default"),
2223 declared_with: TargetRole::Build,
2224 site: Box::new(root_site("//:app")),
2225 };
2226 assert_eq!(
2227 err.to_string(),
2228 "target //:default was asked for as a test, but //:app is declared with b.target in build.lua"
2229 );
2230 }
2231
2232 #[test]
2233 fn not_a_test_names_the_function_that_declared_a_discovery_target() {
2234 let err = Error::NotATest {
2235 asked: label("//:pkgs"),
2236 declared_with: TargetRole::Discovery,
2237 site: Box::new(root_site("//:pkgs")),
2238 };
2239 assert_eq!(
2240 err.to_string(),
2241 "target //:pkgs was asked for as a test, but //:pkgs is declared with b.discover in build.lua"
2242 );
2243 }
2244
2245 #[test]
2246 fn not_a_test_names_the_plugin_chain_of_a_target_a_plugin_declared() {
2247 let err = Error::NotATest {
2248 asked: label("//:default"),
2249 declared_with: TargetRole::Build,
2250 site: Box::new(DeclarationSite {
2251 origin: ourgo_chain(),
2252 ..root_site("//:app")
2253 }),
2254 };
2255 assert_eq!(
2256 err.to_string(),
2257 "target //:default was asked for as a test, but //:app is declared with b.target in \
2258 build.lua, plugin ourgo@0.1.0 > go@1.2.0"
2259 );
2260 }
2261
2262 #[test]
2263 fn invalid_query_names_the_query_and_the_two_forms() {
2264 let err = Error::InvalidQuery {
2265 expression: "dep(//:a)".to_owned(),
2266 };
2267 assert_eq!(
2268 err.to_string(),
2269 "query `dep(//:a)` is not deps(<target>) or rdeps(<target>)"
2270 );
2271 }
2272
2273 fn line(number: usize) -> NonZeroUsize {
2274 NonZeroUsize::new(number).unwrap()
2275 }
2276
2277 #[test]
2278 fn no_run_names_the_target_and_a_suggestion() {
2279 let err = Error::NoRun {
2280 label: label("//:ap"),
2281 suggestion: Some(label("//:app")),
2282 damaged: Vec::new(),
2283 };
2284 assert_eq!(
2285 err.to_string(),
2286 "target //:ap has no run in the log (did you mean //:app?)"
2287 );
2288 let without = Error::NoRun {
2289 label: label("//:ap"),
2290 suggestion: None,
2291 damaged: Vec::new(),
2292 };
2293 assert_eq!(without.to_string(), "target //:ap has no run in the log");
2294 }
2295
2296 #[test]
2297 fn no_run_names_the_damaged_lines() {
2298 let two = Error::NoRun {
2299 label: label("//:app"),
2300 suggestion: None,
2301 damaged: vec![line(14), line(90)],
2302 };
2303 assert_eq!(
2304 two.to_string(),
2305 "target //:app has no run in the log; 2 damaged lines were skipped (lines 14, 90)"
2306 );
2307 let one = Error::NoRun {
2308 label: label("//:app"),
2309 suggestion: None,
2310 damaged: vec![line(14)],
2311 };
2312 assert_eq!(
2313 one.to_string(),
2314 "target //:app has no run in the log; 1 damaged line was skipped (line 14)"
2315 );
2316 }
2317
2318 #[test]
2319 fn missing_output_names_the_target() {
2320 let err = Error::MissingOutput {
2321 label: label("//:app"),
2322 };
2323 assert_eq!(
2324 err.to_string(),
2325 "target //:app: the output of its last logged run is no longer in the store"
2326 );
2327 }
2328
2329 #[test]
2330 fn a_foreign_plan_says_the_plan_does_not_belong_to_the_graph() {
2331 assert_eq!(
2332 Error::ForeignPlan.to_string(),
2333 "the plan was not made from this graph"
2334 );
2335 }
2336
2337 #[test]
2338 fn an_output_conflict_names_the_path_and_both_targets_with_their_files() {
2339 let err = Error::OutputConflict {
2340 path: OutputPath::of(
2341 &Directory::parse("out").unwrap(),
2342 &label("//:lib"),
2343 &OutputName::parse("lib").unwrap(),
2344 ),
2345 first: Box::new(root_site("//:lib")),
2346 second: Box::new(DeclarationSite {
2347 label: label("//lib:text"),
2348 provenance: lib_file(),
2349 origin: Origin::BuildFile,
2350 }),
2351 };
2352 assert_eq!(
2353 err.to_string(),
2354 "out/lib: //:lib (build.lua) and //lib:text (lib/build.lua) cannot both write here"
2355 );
2356 }
2357
2358 #[test]
2359 fn an_output_conflict_names_the_plugin_chain_of_a_target_a_plugin_declared() {
2360 let err = Error::OutputConflict {
2361 path: OutputPath::of(
2362 &Directory::parse("out").unwrap(),
2363 &label("//:lib"),
2364 &OutputName::parse("lib").unwrap(),
2365 ),
2366 first: Box::new(DeclarationSite {
2367 origin: ourgo_chain(),
2368 ..root_site("//:lib")
2369 }),
2370 second: Box::new(root_site("//:other")),
2371 };
2372 assert_eq!(
2373 err.to_string(),
2374 "out/lib: //:lib (build.lua, plugin ourgo@0.1.0 > go@1.2.0) and //:other (build.lua) \
2375 cannot both write here"
2376 );
2377 }
2378
2379 #[test]
2380 fn an_output_conflict_inside_one_target_names_that_target_twice() {
2381 let err = Error::OutputConflict {
2382 path: OutputPath::of(
2383 &Directory::parse("out").unwrap(),
2384 &label("//:app"),
2385 &OutputName::parse("app").unwrap(),
2386 ),
2387 first: Box::new(root_site("//:app")),
2388 second: Box::new(root_site("//:app")),
2389 };
2390 assert_eq!(
2391 err.to_string(),
2392 "out/app: //:app (build.lua) and //:app (build.lua) cannot both write here"
2393 );
2394 }
2395
2396 #[test]
2397 fn no_program_names_the_site_of_the_command() {
2398 let err = Error::NoProgram {
2399 site: Box::new(root_site("//:app")),
2400 };
2401 assert_eq!(
2402 err.to_string(),
2403 "build.lua: //:app: the command names no program once expanded"
2404 );
2405 }
2406
2407 #[test]
2408 fn a_program_a_command_names_only_once_expanded_is_refused_like_any_other() {
2409 let err = Error::Refused {
2410 want: Want::Program(Program::parse("out/app").unwrap()),
2411 site: Some(Box::new(root_site("//:app_test"))),
2412 ceiling: Box::new(Ceiling {
2413 unkeyed: BTreeSet::new(),
2414 run: BTreeSet::from([Program::parse("cc").unwrap()]),
2415 env: BTreeSet::new(),
2416 read: BTreeSet::new(),
2417 write: BTreeSet::new(),
2418 }),
2419 };
2420 assert_eq!(
2421 err.to_string(),
2422 "build.lua: //:app_test: program out/app is outside the ceiling (proc.run allows: cc)"
2423 );
2424 }
2425
2426 #[test]
2427 fn adapter_names_the_port_before_the_adapters_own_message() {
2428 let err = Error::Adapter {
2429 port: PortName::StatCache,
2430 diagnostic: Diagnostic::new("statcache.json: permission denied"),
2431 };
2432 assert_eq!(
2433 err.to_string(),
2434 "stat cache: statcache.json: permission denied"
2435 );
2436 }
2437
2438 #[test]
2439 fn a_dispatcher_fault_names_the_dispatcher_and_the_targets_left_without_an_outcome() {
2440 let lost = Error::DispatcherFault {
2441 targets: vec![label("//:a"), label("//lib:b")],
2442 };
2443 assert_eq!(
2444 lost.to_string(),
2445 "dispatcher: returned without an outcome for //:a, //lib:b"
2446 );
2447 }
2448
2449 #[test]
2450 fn lost_build_files_names_each_directory() {
2451 let lost = Error::LostBuildFiles {
2452 directories: vec![Directory::root(), Directory::parse("lib").unwrap()],
2453 };
2454 assert_eq!(
2455 lost.to_string(),
2456 "dispatcher: returned without evaluating the build files of //, //lib"
2457 );
2458 }
2459
2460 #[test]
2461 fn every_port_name_renders_a_human_phrase() {
2462 let cases = [
2463 (PortName::Manifest, "manifest"),
2464 (PortName::Host, "host"),
2465 (PortName::Digester, "digester"),
2466 (PortName::StatCache, "stat cache"),
2467 (PortName::ToolResolver, "tool resolver"),
2468 (PortName::ActionCache, "action cache"),
2469 (PortName::ContentStore, "content store"),
2470 (PortName::EventLog, "event log"),
2471 (PortName::RunHistory, "run history"),
2472 (PortName::ExecStrategy, "exec strategy"),
2473 (PortName::Dispatcher, "dispatcher"),
2474 (PortName::GraphRecord, "graph record"),
2475 (PortName::Sweep, "sweep"),
2476 (PortName::Approver, "approver"),
2477 (PortName::PluginStore, "plugin store"),
2478 (PortName::RemoteCache, "remote cache"),
2479 (PortName::Changes, "file watcher"),
2480 ];
2481 for (port, rendered) in cases {
2482 assert_eq!(port.to_string(), rendered);
2483 }
2484 }
2485
2486 #[test]
2487 fn the_remote_cache_port_is_named_in_errors() {
2488 let err = Error::Adapter {
2489 port: PortName::RemoteCache,
2490 diagnostic: Diagnostic::new("connection refused"),
2491 };
2492 assert_eq!(PortName::RemoteCache.to_string(), "remote cache");
2493 assert_eq!(err.to_string(), "remote cache: connection refused");
2494 }
2495
2496 #[test]
2497 fn name_kind_renders_a_human_phrase() {
2498 assert_eq!(NameKind::Directory.to_string(), "directory");
2499 assert_eq!(NameKind::TargetName.to_string(), "target name");
2500 assert_eq!(NameKind::Label.to_string(), "label");
2501 assert_eq!(NameKind::Digest.to_string(), "digest");
2502 assert_eq!(NameKind::SourcePath.to_string(), "source path");
2503 assert_eq!(NameKind::OutputName.to_string(), "output name");
2504 assert_eq!(NameKind::EnvName.to_string(), "environment variable name");
2505 assert_eq!(NameKind::Argument.to_string(), "argument");
2506 assert_eq!(NameKind::Command.to_string(), "command");
2507 assert_eq!(NameKind::Description.to_string(), "description");
2508 assert_eq!(NameKind::SettingName.to_string(), "setting name");
2509 assert_eq!(NameKind::SettingValue.to_string(), "setting value");
2510 assert_eq!(NameKind::EntryName.to_string(), "entry file name");
2511 assert_eq!(NameKind::FieldName.to_string(), "field name");
2512 assert_eq!(NameKind::Program.to_string(), "program");
2513 assert_eq!(NameKind::EnvValue.to_string(), "environment variable value");
2514 assert_eq!(NameKind::Platform.to_string(), "platform");
2515 assert_eq!(NameKind::Workers.to_string(), "worker count");
2516 assert_eq!(NameKind::Timeout.to_string(), "timeout");
2517 assert_eq!(NameKind::Isolation.to_string(), "execution strategy");
2518 assert_eq!(NameKind::Approver.to_string(), "approver mode");
2519 assert_eq!(NameKind::TreePath.to_string(), "tree path");
2520 assert_eq!(NameKind::EnvMark.to_string(), "environment variable mark");
2521 assert_eq!(NameKind::PluginName.to_string(), "plugin name");
2522 assert_eq!(NameKind::PluginVersion.to_string(), "plugin version");
2523 assert_eq!(NameKind::PluginChain.to_string(), "plugin chain");
2524 assert_eq!(NameKind::RemoteUrl.to_string(), "remote cache URL");
2525 assert_eq!(NameKind::InstanceName.to_string(), "instance name");
2526 assert_eq!(NameKind::HostPath.to_string(), "host path");
2527 assert_eq!(NameKind::HeaderName.to_string(), "header name");
2528 assert_eq!(NameKind::ChangedPath.to_string(), "changed path");
2529 assert_eq!(NameKind::RemoteJobs.to_string(), "remote job count");
2530 assert_eq!(NameKind::RetryCount.to_string(), "retry count");
2531 assert_eq!(
2532 NameKind::PlatformProperty.to_string(),
2533 "platform property name"
2534 );
2535 }
2536
2537 #[test]
2538 fn an_insecure_token_names_the_url_and_the_fix() {
2539 let url = RemoteUrl::parse("grpc://cache:50051").unwrap();
2540 assert_eq!(
2541 Error::InsecureToken { url }.to_string(),
2542 "a token would be sent in clear text to grpc://cache:50051; use a grpcs:// URL"
2543 );
2544 }
2545
2546 #[test]
2547 fn invalid_name_states_what_was_found() {
2548 let err = Error::InvalidName {
2549 kind: NameKind::Label,
2550 value: "//lib".to_owned(),
2551 reason: "must hold ':' and a target name",
2552 };
2553 assert_eq!(
2554 err.to_string(),
2555 r#"invalid label: "//lib" — must hold ':' and a target name"#
2556 );
2557 }
2558
2559 #[test]
2560 fn canonical_json_states_the_value_could_not_be_serialized() {
2561 let Err(source) = serde_json::to_value(u128::MAX) else {
2562 unreachable!("u128::MAX has no JSON number representation")
2563 };
2564 let err = Error::CanonicalJson { source };
2565 assert_eq!(
2566 err.to_string(),
2567 "value could not be serialized as canonical JSON"
2568 );
2569 }
2570
2571 #[test]
2572 fn float_rejected_states_where_the_float_was_found() {
2573 let err = Error::FloatRejected {
2574 path: "$.timings.elapsed".to_owned(),
2575 };
2576 assert_eq!(
2577 err.to_string(),
2578 "floating-point value at $.timings.elapsed cannot appear in canonical JSON"
2579 );
2580 }
2581
2582 #[test]
2583 fn unreadable_json_states_what_could_not_be_read() {
2584 let Err(source) = serde_json::from_slice::<u32>(b"[]") else {
2585 unreachable!("an array is not a number")
2586 };
2587 let err = Error::UnreadableJson { source };
2588 assert_eq!(
2589 err.to_string(),
2590 "canonical JSON could not be read: invalid type: sequence, expected u32 at line 1 \
2591 column 0"
2592 );
2593 }
2594
2595 #[test]
2596 fn non_canonical_json_states_where_the_bytes_differ() {
2597 let err = Error::NonCanonicalJson { offset: 36 };
2598 assert_eq!(
2599 err.to_string(),
2600 "JSON is not in canonical form: it differs from it at byte 36"
2601 );
2602 }
2603
2604 #[test]
2605 fn corrupt_state_names_the_file_and_keeps_the_reading_failure() {
2606 let err = Error::CorruptState {
2607 file: PathBuf::from("/ws/.buildl/cache.json"),
2608 source: Box::new(Error::NonCanonicalJson { offset: 36 }),
2609 };
2610 assert_eq!(
2611 err.to_string(),
2612 "/ws/.buildl/cache.json is not a file buildl wrote: JSON is not in canonical form: \
2613 it differs from it at byte 36"
2614 );
2615 assert_eq!(
2616 std::error::Error::source(&err).unwrap().to_string(),
2617 "JSON is not in canonical form: it differs from it at byte 36"
2618 );
2619 let Error::CorruptState { source, .. } = err else {
2620 unreachable!("built as CorruptState above")
2621 };
2622 assert!(matches!(*source, Error::NonCanonicalJson { offset: 36 }));
2623 }
2624
2625 #[test]
2626 fn evaluation_names_the_file_the_failure_and_the_message() {
2627 let err = Error::Evaluation {
2628 provenance: lib_file(),
2629 failure: EvaluationFailure::Syntax,
2630 diagnostic: Diagnostic::new("unexpected symbol near '}'"),
2631 };
2632 assert_eq!(
2633 err.to_string(),
2634 "lib/build.lua: syntax error: unexpected symbol near '}'"
2635 );
2636 }
2637
2638 #[test]
2639 fn every_evaluation_failure_renders_a_human_phrase() {
2640 let field = || Written::<FieldName>::new("dep");
2641 let cases = [
2642 (EvaluationFailure::Syntax, "syntax error"),
2643 (EvaluationFailure::Runtime, "runtime error"),
2644 (EvaluationFailure::Refused, "operation refused"),
2645 (
2646 EvaluationFailure::LimitReached {
2647 limit: EvaluationLimit::Instructions,
2648 },
2649 "instruction ceiling reached",
2650 ),
2651 (
2652 EvaluationFailure::LimitReached {
2653 limit: EvaluationLimit::Memory,
2654 },
2655 "memory ceiling reached",
2656 ),
2657 (
2658 EvaluationFailure::LimitReached {
2659 limit: EvaluationLimit::Staging,
2660 },
2661 "staging cap reached",
2662 ),
2663 (
2664 EvaluationFailure::LimitReached {
2665 limit: EvaluationLimit::Walk,
2666 },
2667 "walk cap reached",
2668 ),
2669 (
2670 EvaluationFailure::UnknownField { field: field() },
2671 r#"unknown field "dep""#,
2672 ),
2673 (
2674 EvaluationFailure::WrongFieldType { field: field() },
2675 r#"field "dep" has the wrong type"#,
2676 ),
2677 ];
2678 for (failure, rendered) in cases {
2679 assert_eq!(failure.to_string(), rendered);
2680 }
2681 }
2682
2683 #[test]
2684 fn missing_build_file_names_the_root_or_the_requester() {
2685 let root = Error::MissingBuildFile {
2686 directory: Directory::root(),
2687 requested_by: None,
2688 };
2689 assert_eq!(root.to_string(), "no build file in // (the workspace root)");
2690 let requested = Error::MissingBuildFile {
2691 directory: Directory::parse("lib/text").unwrap(),
2692 requested_by: Some(lib_file()),
2693 };
2694 assert_eq!(
2695 requested.to_string(),
2696 "no build file in //lib/text (requested by lib/build.lua)"
2697 );
2698 }
2699
2700 #[test]
2701 fn invalid_declaration_names_the_site_the_field_and_the_grammar() {
2702 let source = TargetName::parse("a/b").unwrap_err();
2703 let source_text = source.to_string();
2704 let err = Error::InvalidDeclaration {
2705 provenance: lib_file(),
2706 origin: Origin::BuildFile,
2707 order: DeclarationOrder::new(2),
2708 field: DeclarationField::Dep,
2709 source: Box::new(source),
2710 };
2711 assert_eq!(
2712 err.to_string(),
2713 r#"lib/build.lua: declaration #2: invalid dep: invalid target name: "a/b" — may hold only ASCII letters, digits, '.', '-' and '_'"#
2714 );
2715 assert_eq!(
2716 std::error::Error::source(&err).unwrap().to_string(),
2717 source_text
2718 );
2719 }
2720
2721 fn ignored(path: IgnoredPath, file: &str, pattern: &str) -> Error {
2722 Error::Ignored {
2723 provenance: lib_file(),
2724 origin: Origin::BuildFile,
2725 order: DeclarationOrder::new(2),
2726 path: Box::new(path),
2727 ignoring: Box::new(Ignoring::new(file, pattern)),
2728 }
2729 }
2730
2731 #[test]
2732 fn an_ignored_input_names_the_path_the_file_and_the_pattern() {
2733 let err = ignored(
2734 IgnoredPath::Input(SourcePath::parse("notes/a.md").unwrap()),
2735 ".buildlignore",
2736 "notes/",
2737 );
2738 assert_eq!(
2739 err.to_string(),
2740 "lib/build.lua: inputs: notes/a.md is ignored by .buildlignore (notes/)"
2741 );
2742 }
2743
2744 #[test]
2745 fn an_ignored_subdir_says_subdir() {
2746 let err = ignored(
2747 IgnoredPath::Subdir(Directory::parse("examples").unwrap()),
2748 ".buildlignore",
2749 "examples/",
2750 );
2751 assert_eq!(
2752 err.to_string(),
2753 "lib/build.lua: subdir: examples is ignored by .buildlignore (examples/)"
2754 );
2755 }
2756
2757 #[test]
2758 fn an_ignore_file_error_with_a_line() {
2759 let err = Error::IgnoreFile {
2760 file: "lib/.buildlignore".to_owned(),
2761 line: Some(1),
2762 reason: "error parsing glob '[z-a]': invalid range; 'z' > 'a'".to_owned(),
2763 };
2764 assert_eq!(
2765 err.to_string(),
2766 "lib/.buildlignore:1: error parsing glob '[z-a]': invalid range; 'z' > 'a'"
2767 );
2768 }
2769
2770 #[test]
2771 fn an_ignore_file_error_without_a_line() {
2772 let err = Error::IgnoreFile {
2773 file: "lib/.buildlignore".to_owned(),
2774 line: None,
2775 reason: "a symlink, not a file".to_owned(),
2776 };
2777 assert_eq!(err.to_string(), "lib/.buildlignore: a symlink, not a file");
2778 }
2779
2780 #[test]
2781 fn stdout_outputs_names_the_target_and_the_count() {
2782 let err = Error::StdoutOutputs {
2783 target: "//svc:gen".parse().unwrap(),
2784 outputs: 2,
2785 };
2786 assert_eq!(
2787 err.to_string(),
2788 "target //svc:gen declares 2 outputs; a target whose output is its stdout declares exactly one"
2789 );
2790 }
2791
2792 #[test]
2793 fn not_accepted_states_why_the_declaration_cannot_hold_the_value() {
2794 let err = Error::NotAccepted {
2795 reason: "a discovery target is always cached",
2796 };
2797 assert_eq!(err.to_string(), "a discovery target is always cached");
2798 }
2799
2800 #[test]
2801 fn invalid_declaration_names_the_plugin_chain_of_a_declaration_a_plugin_made() {
2802 let err = Error::InvalidDeclaration {
2803 provenance: lib_file(),
2804 origin: ourgo_chain(),
2805 order: DeclarationOrder::new(2),
2806 field: DeclarationField::Dep,
2807 source: Box::new(TargetName::parse("a/b").unwrap_err()),
2808 };
2809 assert!(
2810 err.to_string().starts_with(
2811 "lib/build.lua (plugin ourgo@0.1.0 > go@1.2.0): declaration #2: invalid dep: "
2812 ),
2813 "{err}"
2814 );
2815 }
2816
2817 #[test]
2818 fn every_declaration_field_renders_a_human_phrase() {
2819 let cases = [
2820 (DeclarationField::Name, "name"),
2821 (DeclarationField::Dep, "dep"),
2822 (DeclarationField::Input, "input"),
2823 (DeclarationField::Output, "output"),
2824 (DeclarationField::Env, "env"),
2825 (DeclarationField::Run, "run"),
2826 (DeclarationField::Rule, "rule"),
2827 (DeclarationField::Description, "description"),
2828 (DeclarationField::Target, "target"),
2829 (DeclarationField::SettingName, "setting name"),
2830 (DeclarationField::SettingValue, "setting value"),
2831 (DeclarationField::Freshness, "freshness"),
2832 (DeclarationField::Stdout, "stdout"),
2833 (DeclarationField::Subdir, "subdir"),
2834 ];
2835 for (field, rendered) in cases {
2836 assert_eq!(field.to_string(), rendered);
2837 }
2838 }
2839
2840 #[test]
2841 fn action_conflict_states_what_was_found() {
2842 let both = Error::ActionConflict {
2843 provenance: lib_file(),
2844 origin: Origin::BuildFile,
2845 order: DeclarationOrder::new(0),
2846 found: ActionFound::Both,
2847 };
2848 assert_eq!(
2849 both.to_string(),
2850 "lib/build.lua: declaration #0: a target names both 'rule' and 'run'"
2851 );
2852 let neither = Error::ActionConflict {
2853 provenance: lib_file(),
2854 origin: Origin::BuildFile,
2855 order: DeclarationOrder::new(1),
2856 found: ActionFound::Neither,
2857 };
2858 assert_eq!(
2859 neither.to_string(),
2860 "lib/build.lua: declaration #1: a target names neither 'rule' nor 'run'"
2861 );
2862 }
2863
2864 #[test]
2865 fn action_conflict_names_the_plugin_chain_of_a_declaration_a_plugin_made() {
2866 let err = Error::ActionConflict {
2867 provenance: lib_file(),
2868 origin: ourgo_chain(),
2869 order: DeclarationOrder::new(0),
2870 found: ActionFound::Both,
2871 };
2872 assert_eq!(
2873 err.to_string(),
2874 "lib/build.lua (plugin ourgo@0.1.0 > go@1.2.0): declaration #0: a target names both \
2875 'rule' and 'run'"
2876 );
2877 }
2878
2879 #[test]
2880 fn nondeterministic_names_the_file_to_fix() {
2881 let err = Error::Nondeterministic {
2882 provenance: lib_file(),
2883 first_run: None,
2884 second_run: None,
2885 };
2886 assert_eq!(
2887 err.to_string(),
2888 "lib/build.lua: declarations differ between two evaluations"
2889 );
2890 }
2891
2892 #[test]
2893 fn discovery_changed_names_the_target_and_its_file() {
2894 let err = Error::DiscoveryChanged {
2895 label: Label::parse("//lib:pkgs").unwrap(),
2896 provenance: lib_file(),
2897 };
2898 assert_eq!(
2899 err.to_string(),
2900 "lib/build.lua: discovery target //lib:pkgs differs once discovery results are \
2901 read; a discovery target may not depend on a discovery result"
2902 );
2903 }
2904
2905 #[test]
2906 fn an_invalid_tree_says_what_is_wrong_with_the_list() {
2907 let path = TreePath::parse("assets/app.js").unwrap();
2908 for (fault, rendered) in [
2909 (TreeFault::Empty, "not a tree: it holds no file"),
2910 (
2911 TreeFault::Repeated(path.clone()),
2912 "not a tree: assets/app.js is listed twice",
2913 ),
2914 (
2915 TreeFault::Clash(path),
2916 "not a tree: assets/app.js is both a file and a directory",
2917 ),
2918 ] {
2919 assert_eq!(Error::InvalidTree { fault }.to_string(), rendered);
2920 }
2921 }
2922}