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