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 {name} is set to {value} by the sandbox and cannot be declared",
320 .site
321 )]
322 PinnedEnv {
323 name: EnvName,
325 value: EnvValue,
327 site: Box<DeclarationSite>,
329 },
330 #[error(
332 "{}: input {path} does not exist",
333 .site
334 )]
335 MissingInput {
336 site: Box<DeclarationSite>,
338 path: SourcePath,
340 },
341 #[error(
343 "{}: input {path} is {found}; an input must be a regular file",
344 .site
345 )]
346 InputNotAFile {
347 site: Box<DeclarationSite>,
349 path: SourcePath,
351 found: InputKind,
353 },
354 #[error("setting {name} is overridden but not declared")]
356 UnknownOverride {
357 name: SettingName,
359 },
360 #[error(
362 "target {label} was asked for but is not declared{}",
363 suggestion_suffix(.suggestion.as_ref())
364 )]
365 UnknownTarget {
366 label: Label,
368 suggestion: Option<Label>,
370 },
371 #[error(
373 "target {asked} was asked for as a test, but {} is declared with {} in {}",
374 .site.label,
375 .declared_with.declaring_function(),
376 .site.located()
377 )]
378 NotATest {
379 asked: Label,
381 declared_with: TargetRole,
383 site: Box<DeclarationSite>,
386 },
387 #[error("query `{expression}` is not deps(<target>) or rdeps(<target>)")]
389 InvalidQuery {
390 expression: String,
392 },
393 #[error(
395 "target {label} has no run in the log{}{}",
396 suggestion_suffix(.suggestion.as_ref()),
397 damaged_suffix(.damaged)
398 )]
399 NoRun {
400 label: Label,
402 suggestion: Option<Label>,
404 damaged: Vec<NonZeroUsize>,
407 },
408 #[error("target {label}: the output of its last logged run is no longer in the store")]
410 MissingOutput {
411 label: Label,
413 },
414 #[error("the plan was not made from this graph")]
416 ForeignPlan,
417 #[error("{}", which.diagnostic())]
423 UploadUnsandboxed {
424 which: UnsandboxedRemote,
426 },
427 #[error(
432 "the remote cache token from {} cannot be used: it is missing or unreadable, \
433 or it holds a character a header cannot carry",
434 token_source(.from)
435 )]
436 RemoteToken {
437 from: TokenSource,
439 },
440 #[error("{name} is {value:?}, and must be 1 or 0")]
442 RemoteSwitch {
443 name: RemoteVariable,
445 value: String,
447 },
448 #[error("{conflict}")]
450 RemoteFlags {
451 conflict: RemoteFlagConflict,
453 },
454 #[error(
457 "{path}: {} ({}) and {} ({}) cannot both write here",
458 .first.label,
459 .first.located(),
460 .second.label,
461 .second.located()
462 )]
463 OutputConflict {
464 path: OutputPath,
466 first: Box<DeclarationSite>,
468 second: Box<DeclarationSite>,
470 },
471 #[error(
474 "{}: the command names no program once expanded",
475 .site
476 )]
477 NoProgram {
478 site: Box<DeclarationSite>,
480 },
481 #[error("{}", lost_by_the_dispatcher(.targets))]
487 DispatcherFault {
488 targets: Vec<Label>,
490 },
491 #[error("{}", lost_build_files(.directories))]
496 LostBuildFiles {
497 directories: Vec<Directory>,
499 },
500 #[error("{port}: {diagnostic}")]
502 Adapter {
503 port: PortName,
505 diagnostic: Diagnostic,
507 },
508 #[error("not a tree: {fault}")]
510 InvalidTree {
511 fault: TreeFault,
513 },
514 #[error(
516 "plugin {plugin}: {} is not a regular file with a Unicode name; a plugin holds regular files only",
517 .path.display()
518 )]
519 PluginTree {
520 plugin: PluginName,
522 path: PathBuf,
524 },
525 #[error("plugin {plugin} is not fetched: {reason}")]
529 PluginNotFetched {
530 plugin: PluginName,
532 reason: String,
534 },
535 #[error("plugin {plugin} was changed after it was fetched: {reason}")]
538 PluginChanged {
539 plugin: PluginName,
541 reason: String,
543 },
544 #[error("plugin {plugin} could not be fetched: {diagnostic}")]
547 PluginFetch {
548 plugin: PluginName,
550 diagnostic: Diagnostic,
552 },
553}
554
555fn lost_build_files(directories: &[Directory]) -> String {
558 let shown: Vec<String> = directories.iter().map(|d| format!("//{d}")).collect();
559 format!(
560 "{}: returned without evaluating the build files of {}",
561 PortName::Dispatcher,
562 shown.join(", ")
563 )
564}
565
566fn lost_by_the_dispatcher(targets: &[Label]) -> String {
569 let labels: Vec<String> = targets.iter().map(ToString::to_string).collect();
570 format!(
571 "{}: returned without an outcome for {}",
572 PortName::Dispatcher,
573 labels.join(", ")
574 )
575}
576
577fn token_source(from: &TokenSource) -> String {
579 match from {
580 TokenSource::Env(name) => format!("environment variable {name}"),
581 TokenSource::File(path) => format!("file {path}"),
582 }
583}
584
585fn requested_by_suffix(requested_by: Option<&Provenance>) -> String {
587 requested_by.map_or_else(
588 || " (the workspace root)".to_owned(),
589 |provenance| format!(" (requested by {provenance})"),
590 )
591}
592
593fn sites_list(sites: &[Provenance]) -> String {
595 let rendered: Vec<String> = sites.iter().map(ToString::to_string).collect();
596 rendered.join(", ")
597}
598
599fn declaring_sites(sites: &[DeclarationSite]) -> String {
602 let rendered: Vec<String> = sites
603 .iter()
604 .map(|site| format!("{}{}", site.provenance, plugin_suffix(&site.origin)))
605 .collect();
606 rendered.join(", ")
607}
608
609fn plugin_suffix(origin: &Origin) -> String {
611 match origin {
612 Origin::BuildFile => String::new(),
613 chain @ Origin::Plugins(_) => format!(" (plugin {chain})"),
614 }
615}
616
617fn suggestion_suffix<T: fmt::Display>(suggestion: Option<&T>) -> String {
619 suggestion.map_or_else(String::new, |nearest| format!(" (did you mean {nearest}?)"))
620}
621
622fn damaged_suffix(damaged: &[NonZeroUsize]) -> String {
624 let numbers: Vec<String> = damaged.iter().map(ToString::to_string).collect();
625 match numbers.as_slice() {
626 [] => String::new(),
627 [only] => format!("; 1 damaged line was skipped (line {only})"),
628 many => format!(
629 "; {} damaged lines were skipped (lines {})",
630 many.len(),
631 many.join(", ")
632 ),
633 }
634}
635
636fn cycle_path(path: &[DeclarationSite]) -> String {
638 let mut rendered: Vec<String> = path
639 .iter()
640 .map(|site| format!("{} ({})", site.label, site.located()))
641 .collect();
642 if let Some(first) = path.first() {
643 rendered.push(first.label.to_string());
644 }
645 rendered.join(" -> ")
646}
647
648fn denial(reason: &DenialReason, unapproved: &WantedSet) -> String {
651 if unapproved.is_empty() {
652 reason.to_string()
653 } else {
654 format!("{reason}\n{unapproved}")
655 }
656}
657
658fn refusal(want: &Want, site: Option<&DeclarationSite>, ceiling: &Ceiling) -> String {
660 let (wanted, list, allowed) = match want {
661 Want::Program(program) => (
662 format!("program {program}"),
663 "proc.run",
664 allowed_list(&ceiling.run),
665 ),
666 Want::Env(name) => (
667 format!("environment variable {name}"),
668 "env.read",
669 allowed_list(&ceiling.env),
670 ),
671 Want::Read(path) => (
672 format!("input {path}"),
673 "fs.read",
674 allowed_list(ceiling.read.iter().map(directory_text)),
675 ),
676 Want::Write(directory) => (
677 format!("directory {}", directory_text(directory)),
678 "fs.write",
679 allowed_list(ceiling.write.iter().map(directory_text)),
680 ),
681 Want::Network(label) => (
682 format!("network of {label}"),
683 "network",
684 "nothing".to_owned(),
685 ),
686 };
687 let holder = site.map_or_else(String::new, |site| format!("{site}: "));
688 format!("{holder}{wanted} is outside the ceiling ({list} allows: {allowed})")
689}
690
691pub(crate) fn allowed_list<T: fmt::Display>(entries: impl IntoIterator<Item = T>) -> String {
693 let rendered: Vec<String> = entries.into_iter().map(|entry| entry.to_string()).collect();
694 if rendered.is_empty() {
695 "nothing".to_owned()
696 } else {
697 rendered.join(", ")
698 }
699}
700
701pub(crate) fn directory_text(directory: &Directory) -> &str {
703 if directory.is_root() {
704 "."
705 } else {
706 directory.as_str()
707 }
708}
709
710#[derive(Debug, Clone, Copy, PartialEq, Eq)]
712#[non_exhaustive]
713pub enum DeclaredKind {
714 Target,
716 Rule,
718 Alias,
720}
721
722impl DeclaredKind {
723 const fn with_article(self) -> &'static str {
725 match self {
726 Self::Target => "a target",
727 Self::Rule => "a rule",
728 Self::Alias => "an alias",
729 }
730 }
731}
732
733impl fmt::Display for DeclaredKind {
734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735 f.write_str(match self {
736 Self::Target => "target",
737 Self::Rule => "rule",
738 Self::Alias => "alias",
739 })
740 }
741}
742
743#[derive(Debug, Clone, PartialEq, Eq)]
750pub struct DeclarationSite {
751 pub label: Label,
753 pub provenance: Provenance,
755 pub origin: Origin,
757}
758
759impl DeclarationSite {
760 fn located(&self) -> String {
763 match &self.origin {
764 Origin::BuildFile => self.provenance.to_string(),
765 chain @ Origin::Plugins(_) => format!("{}, plugin {chain}", self.provenance),
766 }
767 }
768}
769
770impl fmt::Display for DeclarationSite {
771 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772 write!(
773 f,
774 "{}: {}{}",
775 self.provenance,
776 self.label,
777 plugin_suffix(&self.origin)
778 )
779 }
780}
781
782impl From<&Node> for DeclarationSite {
783 fn from(node: &Node) -> Self {
785 Self {
786 label: node.label.clone(),
787 provenance: node.provenance.clone(),
788 origin: node.origin.clone(),
789 }
790 }
791}
792
793#[derive(Debug, Clone, Copy, PartialEq, Eq)]
797#[non_exhaustive]
798pub enum PortName {
799 Manifest,
801 Host,
803 Digester,
805 StatCache,
807 ToolResolver,
809 ActionCache,
811 ContentStore,
813 EventLog,
815 RunHistory,
817 ExecStrategy,
819 Dispatcher,
821 GraphRecord,
823 Sweep,
825 Approver,
827 PluginStore,
829 RemoteCache,
831 Changes,
833}
834
835impl fmt::Display for PortName {
836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837 f.write_str(match self {
838 Self::Manifest => "manifest",
839 Self::Host => "host",
840 Self::Digester => "digester",
841 Self::StatCache => "stat cache",
842 Self::ToolResolver => "tool resolver",
843 Self::ActionCache => "action cache",
844 Self::ContentStore => "content store",
845 Self::EventLog => "event log",
846 Self::RunHistory => "run history",
847 Self::ExecStrategy => "exec strategy",
848 Self::Dispatcher => "dispatcher",
849 Self::GraphRecord => "graph record",
850 Self::Sweep => "sweep",
851 Self::Approver => "approver",
852 Self::PluginStore => "plugin store",
853 Self::RemoteCache => "remote cache",
854 Self::Changes => "file watcher",
855 })
856 }
857}
858
859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861#[non_exhaustive]
862pub enum EvaluationLimit {
863 Instructions,
865 Memory,
867 Staging,
870 Walk,
872}
873
874impl fmt::Display for EvaluationLimit {
875 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876 f.write_str(match self {
877 Self::Instructions => "instruction ceiling",
878 Self::Memory => "memory ceiling",
879 Self::Staging => "staging cap",
880 Self::Walk => "walk cap",
881 })
882 }
883}
884
885#[derive(Debug, Clone, PartialEq, Eq)]
890#[non_exhaustive]
891pub enum EvaluationFailure {
892 Syntax,
894 Runtime,
896 Refused,
898 LimitReached {
900 limit: EvaluationLimit,
902 },
903 UnknownField {
905 field: Written<FieldName>,
907 },
908 WrongFieldType {
910 field: Written<FieldName>,
912 },
913}
914
915impl fmt::Display for EvaluationFailure {
916 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
917 match self {
918 Self::Syntax => f.write_str("syntax error"),
919 Self::Runtime => f.write_str("runtime error"),
920 Self::Refused => f.write_str("operation refused"),
921 Self::LimitReached { limit } => write!(f, "{limit} reached"),
922 Self::UnknownField { field } => write!(f, "unknown field {:?}", field.as_written()),
923 Self::WrongFieldType { field } => {
924 write!(f, "field {:?} has the wrong type", field.as_written())
925 }
926 }
927 }
928}
929
930#[derive(Debug, Clone, Copy, PartialEq, Eq)]
932#[non_exhaustive]
933pub enum DeclarationField {
934 Name,
936 Dep,
938 Input,
940 Output,
942 Env,
944 Run,
946 Rule,
948 Description,
950 Target,
952 SettingName,
954 SettingValue,
956 Freshness,
958 Stdout,
960 Subdir,
962}
963
964impl fmt::Display for DeclarationField {
965 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
966 f.write_str(match self {
967 Self::Name => "name",
968 Self::Dep => "dep",
969 Self::Input => "input",
970 Self::Output => "output",
971 Self::Env => "env",
972 Self::Run => "run",
973 Self::Rule => "rule",
974 Self::Description => "description",
975 Self::Target => "target",
976 Self::SettingName => "setting name",
977 Self::SettingValue => "setting value",
978 Self::Freshness => "freshness",
979 Self::Stdout => "stdout",
980 Self::Subdir => "subdir",
981 })
982 }
983}
984
985#[derive(Debug, Clone, Copy, PartialEq, Eq)]
987pub enum ActionFound {
988 Both,
990 Neither,
992}
993
994impl fmt::Display for ActionFound {
995 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
996 f.write_str(match self {
997 Self::Both => "both 'rule' and 'run'",
998 Self::Neither => "neither 'rule' nor 'run'",
999 })
1000 }
1001}
1002
1003#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1007#[non_exhaustive]
1008pub enum UnsandboxedRemote {
1009 Upload,
1011 Execute,
1014}
1015
1016impl UnsandboxedRemote {
1017 const fn diagnostic(self) -> &'static str {
1019 match self {
1020 Self::Upload => {
1021 "uploading to the remote cache needs actions to run in the input sandbox, \
1022 but strategy is \"bare\"; set strategy to \"sandbox\", or stop uploading by \
1023 unsetting BUILDL_REMOTE_UPLOAD or dropping --remote-upload"
1024 }
1025 Self::Execute => {
1026 "executing on the remote needs actions to run in the input sandbox, \
1027 but strategy is \"bare\"; set strategy to \"sandbox\", or stop executing by \
1028 setting execute to false in [remote], unsetting BUILDL_REMOTE_EXECUTE or \
1029 dropping --remote-execute"
1030 }
1031 }
1032 }
1033}
1034
1035#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1039#[non_exhaustive]
1040pub enum RemoteVariable {
1041 Upload,
1043 Strict,
1045 Execute,
1047}
1048
1049impl fmt::Display for RemoteVariable {
1050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1051 f.write_str(match self {
1052 Self::Upload => "BUILDL_REMOTE_UPLOAD",
1053 Self::Strict => "BUILDL_REMOTE_STRICT",
1054 Self::Execute => "BUILDL_REMOTE_EXECUTE",
1055 })
1056 }
1057}
1058
1059#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1063#[non_exhaustive]
1064pub enum RemoteFlagConflict {
1065 NoRemoteWithSwitch,
1067 SwitchWithoutRemote,
1070 NoRemoteWithExecute,
1072 ExecuteBothWays,
1074 ExecutionWithoutRemote,
1077 JobsWithoutExecution,
1079}
1080
1081impl fmt::Display for RemoteFlagConflict {
1082 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1083 f.write_str(match self {
1084 Self::NoRemoteWithSwitch => {
1085 "--no-remote cannot be combined with --remote-upload or --remote-strict"
1086 }
1087 Self::SwitchWithoutRemote => {
1088 "--remote-upload and --remote-strict need a [remote] table in buildl.toml, \
1089 and this workspace has none"
1090 }
1091 Self::NoRemoteWithExecute => "--no-remote cannot be combined with --remote-execute",
1092 Self::ExecuteBothWays => "--remote-execute cannot be combined with --no-remote-execute",
1093 Self::ExecutionWithoutRemote => {
1094 "--remote-execute, --no-remote-execute and --remote-jobs need a [remote] table \
1095 in buildl.toml, and this workspace has none"
1096 }
1097 Self::JobsWithoutExecution => {
1098 "--remote-jobs needs remote execution, and it is off in this run"
1099 }
1100 })
1101 }
1102}
1103
1104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1109#[non_exhaustive]
1110pub enum NameKind {
1111 Directory,
1113 TargetName,
1115 Label,
1117 Digest,
1119 SourcePath,
1121 OutputName,
1123 EnvName,
1125 Argument,
1127 Command,
1129 Description,
1131 SettingName,
1133 SettingValue,
1135 EntryName,
1137 FieldName,
1139 Program,
1141 EnvValue,
1143 Platform,
1145 Workers,
1147 Timeout,
1149 Isolation,
1151 Approver,
1153 TreePath,
1155 PluginName,
1157 PluginVersion,
1159 PluginChain,
1161 CommitId,
1163 TagName,
1165 GitUrl,
1167 RemoteUrl,
1169 InstanceName,
1171 HostPath,
1173 HeaderName,
1175 ChangedPath,
1177 RemoteJobs,
1179 RetryCount,
1181 PlatformProperty,
1183}
1184
1185impl fmt::Display for NameKind {
1186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1187 f.write_str(match self {
1188 Self::Directory => "directory",
1189 Self::TargetName => "target name",
1190 Self::Label => "label",
1191 Self::Digest => "digest",
1192 Self::SourcePath => "source path",
1193 Self::OutputName => "output name",
1194 Self::EnvName => "environment variable name",
1195 Self::Argument => "argument",
1196 Self::Command => "command",
1197 Self::Description => "description",
1198 Self::SettingName => "setting name",
1199 Self::SettingValue => "setting value",
1200 Self::EntryName => "entry file name",
1201 Self::FieldName => "field name",
1202 Self::Program => "program",
1203 Self::EnvValue => "environment variable value",
1204 Self::Platform => "platform",
1205 Self::Workers => "worker count",
1206 Self::Timeout => "timeout",
1207 Self::Isolation => "execution strategy",
1208 Self::Approver => "approver mode",
1209 Self::TreePath => "tree path",
1210 Self::PluginName => "plugin name",
1211 Self::PluginVersion => "plugin version",
1212 Self::PluginChain => "plugin chain",
1213 Self::CommitId => "commit id",
1214 Self::TagName => "tag name",
1215 Self::GitUrl => "git URL",
1216 Self::RemoteUrl => "remote cache URL",
1217 Self::InstanceName => "instance name",
1218 Self::HostPath => "host path",
1219 Self::HeaderName => "header name",
1220 Self::ChangedPath => "changed path",
1221 Self::RemoteJobs => "remote job count",
1222 Self::RetryCount => "retry count",
1223 Self::PlatformProperty => "platform property name",
1224 })
1225 }
1226}
1227
1228#[derive(Debug, Clone, PartialEq, Eq)]
1232#[non_exhaustive]
1233pub enum TreeFault {
1234 Empty,
1236 Repeated(TreePath),
1238 Clash(TreePath),
1240}
1241
1242impl fmt::Display for TreeFault {
1243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1244 match self {
1245 Self::Empty => f.write_str("it holds no file"),
1246 Self::Repeated(path) => write!(f, "{path} is listed twice"),
1247 Self::Clash(path) => write!(f, "{path} is both a file and a directory"),
1248 }
1249 }
1250}
1251
1252#[cfg(test)]
1253mod tests {
1254 #![expect(
1255 clippy::unwrap_used,
1256 reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
1257 )]
1258
1259 use std::collections::BTreeSet;
1260 use std::num::NonZeroUsize;
1261 use std::path::PathBuf;
1262
1263 use super::{
1264 ActionFound, DeclarationField, DeclarationSite, DeclaredKind, Error, EvaluationFailure,
1265 EvaluationLimit, NameKind, PortName, RemoteFlagConflict, RemoteVariable, TreeFault,
1266 UnsandboxedRemote,
1267 };
1268 use crate::types::{
1269 Argument, Ceiling, Command, DeclarationOrder, DenialReason, Diagnostic, Directory, EnvName,
1270 EnvValue, FieldName, Freshness, HostPath, InputKind, Label, NetworkAccess, Node, Origin,
1271 OutputName, OutputPath, OutputSource, PluginName, PluginRef, PluginVersion,
1272 PluginViolation, Program, Provenance, RemoteUrl, SettingName, SourcePath, TargetName,
1273 TargetRole, TokenSource, TreePath, Want, WantedSet, Written,
1274 };
1275
1276 fn lib_file() -> Provenance {
1277 Provenance::new(
1278 PathBuf::from("lib/build.lua"),
1279 Directory::parse("lib").unwrap(),
1280 )
1281 }
1282
1283 fn root_file() -> Provenance {
1284 Provenance::new(PathBuf::from("build.lua"), Directory::root())
1285 }
1286
1287 fn tools_file() -> Provenance {
1288 Provenance::new(
1289 PathBuf::from("tools/build.lua"),
1290 Directory::parse("tools").unwrap(),
1291 )
1292 }
1293
1294 fn label(raw: &str) -> Label {
1295 Label::parse(raw).unwrap()
1296 }
1297
1298 fn root_site(raw: &str) -> DeclarationSite {
1300 DeclarationSite {
1301 label: label(raw),
1302 provenance: root_file(),
1303 origin: Origin::BuildFile,
1304 }
1305 }
1306
1307 #[test]
1308 fn duplicate_label_names_every_site() {
1309 let err = Error::DuplicateLabel {
1310 label: label("//:a"),
1311 sites: vec![root_site("//:a"), root_site("//:a")],
1312 };
1313 assert_eq!(
1314 err.to_string(),
1315 "//:a is declared more than once: build.lua, build.lua"
1316 );
1317 }
1318
1319 #[test]
1320 fn duplicate_label_names_the_plugin_chain_of_the_declaration_a_plugin_made() {
1321 let err = Error::DuplicateLabel {
1322 label: label("//:a"),
1323 sites: vec![
1324 root_site("//:a"),
1325 DeclarationSite {
1326 origin: ourgo_chain(),
1327 ..root_site("//:a")
1328 },
1329 ],
1330 };
1331 assert_eq!(
1332 err.to_string(),
1333 "//:a is declared more than once: build.lua, build.lua (plugin ourgo@0.1.0 > go@1.2.0)"
1334 );
1335 }
1336
1337 #[test]
1338 fn duplicate_setting_names_every_site() {
1339 let err = Error::DuplicateSetting {
1340 name: SettingName::parse("test_filter").unwrap(),
1341 sites: vec![root_file(), lib_file()],
1342 };
1343 assert_eq!(
1344 err.to_string(),
1345 "setting test_filter is declared more than once: build.lua, lib/build.lua"
1346 );
1347 }
1348
1349 #[test]
1350 fn unknown_reference_names_the_site_the_field_and_the_nearest_label() {
1351 let err = Error::UnknownReference {
1352 site: Box::new(root_site("//:app")),
1353 field: DeclarationField::Dep,
1354 reference: label("//:mian.o"),
1355 suggestion: Some(label("//:main.o")),
1356 };
1357 assert_eq!(
1358 err.to_string(),
1359 "build.lua: //:app: dep //:mian.o is not declared (did you mean //:main.o?)"
1360 );
1361 }
1362
1363 #[test]
1364 fn unknown_reference_without_a_near_label_offers_nothing() {
1365 let err = Error::UnknownReference {
1366 site: Box::new(root_site("//:default")),
1367 field: DeclarationField::Target,
1368 reference: label("//:nope"),
1369 suggestion: None,
1370 };
1371 assert_eq!(
1372 err.to_string(),
1373 "build.lua: //:default: target //:nope is not declared"
1374 );
1375 }
1376
1377 #[test]
1378 fn wrong_reference_kind_names_what_was_found_and_where() {
1379 let err = Error::WrongReferenceKind {
1380 site: Box::new(root_site("//:app")),
1381 field: DeclarationField::Dep,
1382 reference: label("//:cc"),
1383 found: DeclaredKind::Rule,
1384 declared_in: tools_file(),
1385 };
1386 assert_eq!(
1387 err.to_string(),
1388 "build.lua: //:app: dep //:cc names a rule, declared in tools/build.lua"
1389 );
1390 }
1391
1392 #[test]
1393 fn every_declared_kind_renders_alone_and_in_a_sentence() {
1394 let cases = [
1395 (DeclaredKind::Target, "target", "names a target,"),
1396 (DeclaredKind::Rule, "rule", "names a rule,"),
1397 (DeclaredKind::Alias, "alias", "names an alias,"),
1398 ];
1399 for (found, alone, in_a_sentence) in cases {
1400 assert_eq!(found.to_string(), alone);
1401 let err = Error::WrongReferenceKind {
1402 site: Box::new(root_site("//:app")),
1403 field: DeclarationField::Rule,
1404 reference: label("//:x"),
1405 found,
1406 declared_in: root_file(),
1407 };
1408 assert!(err.to_string().contains(in_a_sentence), "{err}");
1409 }
1410 }
1411
1412 #[test]
1413 fn unknown_setting_names_the_site_and_the_nearest_setting() {
1414 let err = Error::UnknownSetting {
1415 site: Box::new(root_site("//:go_test")),
1416 name: "test_fliter".to_owned(),
1417 suggestion: Some(SettingName::parse("test_filter").unwrap()),
1418 };
1419 assert_eq!(
1420 err.to_string(),
1421 "build.lua: //:go_test: setting test_fliter is not declared \
1422 (did you mean test_filter?)"
1423 );
1424 }
1425
1426 #[test]
1427 fn dependency_cycle_lists_every_target_and_closes_on_the_first() {
1428 let err = Error::DependencyCycle {
1429 path: vec![
1430 DeclarationSite {
1431 label: label("//:a"),
1432 provenance: root_file(),
1433 origin: Origin::BuildFile,
1434 },
1435 DeclarationSite {
1436 label: label("//lib:b"),
1437 provenance: lib_file(),
1438 origin: Origin::BuildFile,
1439 },
1440 ],
1441 };
1442 assert_eq!(
1443 err.to_string(),
1444 "dependency cycle: //:a (build.lua) -> //lib:b (lib/build.lua) -> //:a"
1445 );
1446 }
1447
1448 #[test]
1449 fn a_cycle_of_one_names_its_target_twice() {
1450 let err = Error::DependencyCycle {
1451 path: vec![DeclarationSite {
1452 label: label("//:a"),
1453 provenance: root_file(),
1454 origin: Origin::BuildFile,
1455 }],
1456 };
1457 assert_eq!(
1458 err.to_string(),
1459 "dependency cycle: //:a (build.lua) -> //:a"
1460 );
1461 }
1462
1463 #[test]
1464 fn too_many_targets_states_the_count() {
1465 let err = Error::TooManyTargets { count: 7 };
1466 assert_eq!(
1467 err.to_string(),
1468 "7 targets are more than a graph can number"
1469 );
1470 }
1471
1472 #[test]
1473 fn a_site_is_a_nodes_label_and_its_build_file() {
1474 let node = Node {
1475 label: label("//lib:text"),
1476 provenance: lib_file(),
1477 origin: Origin::BuildFile,
1478 narrowing: Vec::new(),
1479 role: TargetRole::Build,
1480 run: Command::new(vec![Argument::parse("cc").unwrap()]).unwrap(),
1481 description: None,
1482 inputs: Vec::new(),
1483 outputs: vec![OutputName::parse("text").unwrap()],
1484 env: Vec::new(),
1485 network: NetworkAccess::Sealed,
1486 output_source: OutputSource::Command,
1487 freshness: Freshness::Cached,
1488 };
1489 assert_eq!(
1490 DeclarationSite::from(&node),
1491 DeclarationSite {
1492 label: label("//lib:text"),
1493 provenance: lib_file(),
1494 origin: Origin::BuildFile,
1495 }
1496 );
1497 }
1498
1499 fn ourgo_chain() -> Origin {
1501 let plugin = |name: &str, version: &str| PluginRef {
1502 name: PluginName::parse(name).unwrap(),
1503 version: PluginVersion::parse(version).unwrap(),
1504 run: BTreeSet::new(),
1505 env: BTreeSet::new(),
1506 };
1507 Origin::plugins(vec![plugin("ourgo", "0.1.0"), plugin("go", "1.2.0")]).unwrap()
1508 }
1509
1510 #[test]
1511 fn a_site_with_a_plugin_origin_names_the_chain() {
1512 let site = DeclarationSite {
1513 origin: ourgo_chain(),
1514 ..root_site("//:app")
1515 };
1516 assert_eq!(
1517 site.to_string(),
1518 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.2.0)"
1519 );
1520 let missing = Error::MissingTool {
1521 site: Box::new(site.clone()),
1522 program: Program::parse("cc").unwrap(),
1523 };
1524 assert_eq!(
1525 missing.to_string(),
1526 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.2.0): program cc was not found"
1527 );
1528 let cycle = Error::DependencyCycle { path: vec![site] };
1529 assert_eq!(
1530 cycle.to_string(),
1531 "dependency cycle: //:app (build.lua, plugin ourgo@0.1.0 > go@1.2.0) -> //:app"
1532 );
1533 }
1534
1535 #[test]
1536 fn a_build_file_site_reads_as_today() {
1537 assert_eq!(root_site("//:app").to_string(), "build.lua: //:app");
1538 let err = Error::MissingTool {
1539 site: Box::new(root_site("//:app")),
1540 program: Program::parse("cc").unwrap(),
1541 };
1542 assert_eq!(
1543 err.to_string(),
1544 "build.lua: //:app: program cc was not found"
1545 );
1546 }
1547
1548 #[test]
1549 fn missing_tool_names_the_site_and_the_program() {
1550 let err = Error::MissingTool {
1551 site: Box::new(root_site("//:app")),
1552 program: Program::parse("cc").unwrap(),
1553 };
1554 assert_eq!(
1555 err.to_string(),
1556 "build.lua: //:app: program cc was not found"
1557 );
1558 }
1559
1560 #[test]
1561 fn pinned_env_renders_its_site_name_and_value() {
1562 let err = Error::PinnedEnv {
1563 name: EnvName::parse("TZ").unwrap(),
1564 value: EnvValue::parse("UTC").unwrap(),
1565 site: Box::new(root_site("//a:y")),
1566 };
1567 assert_eq!(
1568 err.to_string(),
1569 "build.lua: //a:y: env TZ is set to UTC by the sandbox and cannot be declared"
1570 );
1571 }
1572
1573 #[test]
1574 fn missing_input_names_the_site_and_the_path() {
1575 let err = Error::MissingInput {
1576 site: Box::new(root_site("//:app")),
1577 path: SourcePath::parse("src/main.c").unwrap(),
1578 };
1579 assert_eq!(
1580 err.to_string(),
1581 "build.lua: //:app: input src/main.c does not exist"
1582 );
1583 }
1584
1585 #[test]
1586 fn an_input_that_is_not_a_file_names_the_site_the_path_and_what_was_found() {
1587 for (found, text) in [
1588 (
1589 InputKind::Directory,
1590 "build.lua: //:app: input src is a directory; an input must be a regular file",
1591 ),
1592 (
1593 InputKind::Symlink,
1594 "build.lua: //:app: input src is a symbolic link; an input must be a regular file",
1595 ),
1596 (
1597 InputKind::Special,
1598 "build.lua: //:app: input src is a pipe, a socket or a device; an input must be a regular file",
1599 ),
1600 ] {
1601 let err = Error::InputNotAFile {
1602 site: Box::new(root_site("//:app")),
1603 path: SourcePath::parse("src").unwrap(),
1604 found,
1605 };
1606 assert_eq!(err.to_string(), text);
1607 }
1608 }
1609
1610 fn ceiling() -> Ceiling {
1612 Ceiling {
1613 run: ["cc", "ld"]
1614 .into_iter()
1615 .map(|raw| Program::parse(raw).unwrap())
1616 .collect(),
1617 env: ["PATH", "HOME"]
1618 .into_iter()
1619 .map(|raw| EnvName::parse(raw).unwrap())
1620 .collect(),
1621 read: BTreeSet::from([Directory::parse("src").unwrap()]),
1622 write: BTreeSet::new(),
1623 }
1624 }
1625
1626 #[test]
1627 fn not_approved_shows_its_reason_then_the_wants() {
1628 let err = Error::NotApproved {
1629 unapproved: Box::new(WantedSet {
1630 programs: BTreeSet::from([Program::parse("protoc").unwrap()]),
1631 env: BTreeSet::new(),
1632 write: BTreeSet::from([Directory::parse("out").unwrap()]),
1633 network: BTreeSet::new(),
1634 }),
1635 reason: DenialReason::new("not approved"),
1636 };
1637 assert_eq!(
1638 err.to_string(),
1639 "not approved\n run programs: protoc\n write into: out"
1640 );
1641 }
1642
1643 #[test]
1644 fn not_approved_with_nothing_unapproved_shows_only_its_reason() {
1645 let err = Error::NotApproved {
1646 unapproved: Box::new(WantedSet {
1647 programs: BTreeSet::new(),
1648 env: BTreeSet::new(),
1649 write: BTreeSet::new(),
1650 network: BTreeSet::new(),
1651 }),
1652 reason: DenialReason::new("not approved"),
1653 };
1654 assert_eq!(err.to_string(), "not approved");
1655 }
1656
1657 #[test]
1658 fn a_refused_program_names_the_site_and_what_may_run() {
1659 let err = Error::Refused {
1660 want: Want::Program(Program::parse("docker").unwrap()),
1661 site: Some(Box::new(root_site("//:image"))),
1662 ceiling: Box::new(ceiling()),
1663 };
1664 assert_eq!(
1665 err.to_string(),
1666 "build.lua: //:image: program docker is outside the ceiling (proc.run allows: cc, ld)"
1667 );
1668 }
1669
1670 fn violation(want: Want, allowed: &[&str]) -> Error {
1673 let plugin = |name: &str, version: &str| PluginRef {
1674 name: PluginName::parse(name).unwrap(),
1675 version: PluginVersion::parse(version).unwrap(),
1676 run: BTreeSet::new(),
1677 env: BTreeSet::new(),
1678 };
1679 let chain = vec![plugin("ourgo", "0.1.0"), plugin("go", "1.3.0")];
1680 Error::PluginRefused {
1681 violation: Box::new(PluginViolation {
1682 want,
1683 site: DeclarationSite {
1684 label: label("//:app"),
1685 provenance: root_file(),
1686 origin: Origin::plugins(chain.clone()).unwrap(),
1687 },
1688 plugin: chain[1].clone(),
1689 allowed: allowed.iter().map(|text| (*text).to_owned()).collect(),
1690 }),
1691 }
1692 }
1693
1694 #[test]
1695 fn a_plugin_tree_names_the_plugin_and_the_path() {
1696 let err = Error::PluginTree {
1697 plugin: PluginName::parse("go").unwrap(),
1698 path: PathBuf::from(".buildl/plugins/go/c0ffee/bin/link"),
1699 };
1700 assert_eq!(
1701 err.to_string(),
1702 "plugin go: .buildl/plugins/go/c0ffee/bin/link is not a regular file with a Unicode \
1703 name; a plugin holds regular files only"
1704 );
1705 }
1706
1707 #[test]
1708 fn a_plugin_not_fetched_names_the_plugin_and_the_reason() {
1709 let err = Error::PluginNotFetched {
1710 plugin: PluginName::parse("go").unwrap(),
1711 reason: "run `buildl plugins fetch`".to_owned(),
1712 };
1713 assert_eq!(
1714 err.to_string(),
1715 "plugin go is not fetched: run `buildl plugins fetch`"
1716 );
1717 }
1718
1719 #[test]
1720 fn a_plugin_changed_names_the_plugin_and_the_reason() {
1721 let err = Error::PluginChanged {
1722 plugin: PluginName::parse("go").unwrap(),
1723 reason: "its files differ from buildl.lock".to_owned(),
1724 };
1725 assert_eq!(
1726 err.to_string(),
1727 "plugin go was changed after it was fetched: its files differ from buildl.lock"
1728 );
1729 }
1730
1731 #[test]
1732 fn a_plugin_fetch_names_the_plugin_and_what_git_said() {
1733 let err = Error::PluginFetch {
1734 plugin: PluginName::parse("go").unwrap(),
1735 diagnostic: Diagnostic::new("fatal: couldn't find remote ref refs/tags/v9"),
1736 };
1737 assert_eq!(
1738 err.to_string(),
1739 "plugin go could not be fetched: fatal: couldn't find remote ref refs/tags/v9"
1740 );
1741 }
1742
1743 #[test]
1744 fn a_plugin_refused_program_names_the_site_the_plugin_and_what_it_allows() {
1745 let err = violation(Want::Program(Program::parse("curl").unwrap()), &["go"]);
1746 assert_eq!(
1747 err.to_string(),
1748 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): program curl is outside plugin \
1749 go@1.3.0 (proc.run allows: go)"
1750 );
1751 }
1752
1753 #[test]
1754 fn a_plugin_refused_variable_reads_like_a_refused_program() {
1755 let err = violation(Want::Env(EnvName::parse("HOME").unwrap()), &[]);
1756 assert_eq!(
1757 err.to_string(),
1758 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): environment variable HOME is \
1759 outside plugin go@1.3.0 (env.read allows: nothing)"
1760 );
1761 }
1762
1763 #[test]
1764 fn a_plugin_refused_network_says_the_network_is_not_allowed() {
1765 let err = violation(Want::Network(label("//:app")), &[]);
1766 assert_eq!(
1767 err.to_string(),
1768 "build.lua: //:app (plugin ourgo@0.1.0 > go@1.3.0): network is outside plugin \
1769 go@1.3.0 (network not allowed)"
1770 );
1771 }
1772
1773 #[test]
1774 fn a_refused_variable_names_the_site_and_what_may_be_read() {
1775 let err = Error::Refused {
1776 want: Want::Env(EnvName::parse("AWS_SECRET").unwrap()),
1777 site: Some(Box::new(root_site("//:app"))),
1778 ceiling: Box::new(ceiling()),
1779 };
1780 assert_eq!(
1781 err.to_string(),
1782 "build.lua: //:app: environment variable AWS_SECRET is outside the ceiling \
1783 (env.read allows: HOME, PATH)"
1784 );
1785 }
1786
1787 #[test]
1788 fn a_refused_input_names_the_site_and_where_inputs_may_lie() {
1789 let err = Error::Refused {
1790 want: Want::Read(SourcePath::parse("lib/key.pem").unwrap()),
1791 site: Some(Box::new(DeclarationSite {
1792 label: label("//lib:text"),
1793 provenance: lib_file(),
1794 origin: Origin::BuildFile,
1795 })),
1796 ceiling: Box::new(ceiling()),
1797 };
1798 assert_eq!(
1799 err.to_string(),
1800 "lib/build.lua: //lib:text: input lib/key.pem is outside the ceiling \
1801 (fs.read allows: src)"
1802 );
1803 }
1804
1805 #[test]
1806 fn a_refused_directory_has_no_site_and_an_empty_list_allows_nothing() {
1807 let err = Error::Refused {
1808 want: Want::Write(Directory::parse("out").unwrap()),
1809 site: None,
1810 ceiling: Box::new(ceiling()),
1811 };
1812 assert_eq!(
1813 err.to_string(),
1814 "directory out is outside the ceiling (fs.write allows: nothing)"
1815 );
1816 }
1817
1818 #[test]
1819 fn a_refused_network_reads_as_network() {
1820 let err = Error::Refused {
1821 want: Want::Network(Label::parse("//:fetch").unwrap()),
1822 site: None,
1823 ceiling: Box::new(ceiling()),
1824 };
1825 assert_eq!(
1826 err.to_string(),
1827 "network of //:fetch is outside the ceiling (network allows: nothing)"
1828 );
1829 }
1830
1831 #[test]
1832 fn the_workspace_root_renders_as_a_dot_in_a_refusal() {
1833 let mut allows_root = ceiling();
1834 allows_root.read = BTreeSet::from([Directory::root(), Directory::parse("src").unwrap()]);
1835 allows_root.write = BTreeSet::from([Directory::parse("out").unwrap()]);
1836 let read = Error::Refused {
1837 want: Want::Read(SourcePath::parse("lib/key.pem").unwrap()),
1838 site: Some(Box::new(root_site("//:app"))),
1839 ceiling: Box::new(allows_root.clone()),
1840 };
1841 assert_eq!(
1842 read.to_string(),
1843 "build.lua: //:app: input lib/key.pem is outside the ceiling (fs.read allows: ., src)"
1844 );
1845 let write = Error::Refused {
1846 want: Want::Write(Directory::root()),
1847 site: None,
1848 ceiling: Box::new(allows_root),
1849 };
1850 assert_eq!(
1851 write.to_string(),
1852 "directory . is outside the ceiling (fs.write allows: out)"
1853 );
1854 }
1855
1856 #[test]
1857 fn unknown_override_names_the_setting() {
1858 let err = Error::UnknownOverride {
1859 name: SettingName::parse("test_fliter").unwrap(),
1860 };
1861 assert_eq!(
1862 err.to_string(),
1863 "setting test_fliter is overridden but not declared"
1864 );
1865 }
1866
1867 #[test]
1868 fn unknown_target_names_the_label_and_the_nearest_one() {
1869 let err = Error::UnknownTarget {
1870 label: label("//:libs"),
1871 suggestion: Some(label("//:lib")),
1872 };
1873 assert_eq!(
1874 err.to_string(),
1875 "target //:libs was asked for but is not declared (did you mean //:lib?)"
1876 );
1877 }
1878
1879 #[test]
1880 fn unknown_target_without_a_near_label_offers_nothing() {
1881 let err = Error::UnknownTarget {
1882 label: label("//:nope"),
1883 suggestion: None,
1884 };
1885 assert_eq!(
1886 err.to_string(),
1887 "target //:nope was asked for but is not declared"
1888 );
1889 }
1890
1891 #[test]
1892 fn an_unreadable_token_names_where_it_was_to_come_from() {
1893 let env = Error::RemoteToken {
1894 from: TokenSource::Env(EnvName::parse("CACHE_TOKEN").unwrap()),
1895 };
1896 assert_eq!(
1897 env.to_string(),
1898 "the remote cache token from environment variable CACHE_TOKEN cannot be used: \
1899 it is missing or unreadable, or it holds a character a header cannot carry"
1900 );
1901 let file = Error::RemoteToken {
1902 from: TokenSource::File(HostPath::parse("secrets/token").unwrap()),
1903 };
1904 assert_eq!(
1905 file.to_string(),
1906 "the remote cache token from file secrets/token cannot be used: \
1907 it is missing or unreadable, or it holds a character a header cannot carry"
1908 );
1909 }
1910
1911 #[test]
1912 fn a_bad_switch_names_the_variable_and_what_it_holds() {
1913 let err = Error::RemoteSwitch {
1914 name: RemoteVariable::Upload,
1915 value: "yes".to_owned(),
1916 };
1917 assert_eq!(
1918 err.to_string(),
1919 "BUILDL_REMOTE_UPLOAD is \"yes\", and must be 1 or 0"
1920 );
1921 assert_eq!(RemoteVariable::Strict.to_string(), "BUILDL_REMOTE_STRICT");
1922 assert_eq!(RemoteVariable::Execute.to_string(), "BUILDL_REMOTE_EXECUTE");
1923 }
1924
1925 #[test]
1926 fn refused_flags_say_why() {
1927 let combined = Error::RemoteFlags {
1928 conflict: RemoteFlagConflict::NoRemoteWithSwitch,
1929 };
1930 let unnamed = Error::RemoteFlags {
1931 conflict: RemoteFlagConflict::SwitchWithoutRemote,
1932 };
1933 assert_eq!(
1934 combined.to_string(),
1935 "--no-remote cannot be combined with --remote-upload or --remote-strict"
1936 );
1937 assert_eq!(
1938 unnamed.to_string(),
1939 "--remote-upload and --remote-strict need a [remote] table in buildl.toml, \
1940 and this workspace has none"
1941 );
1942 }
1943
1944 #[test]
1945 fn refused_execution_flags_name_the_flags() {
1946 let text = |conflict| Error::RemoteFlags { conflict }.to_string();
1947 assert_eq!(
1948 text(RemoteFlagConflict::NoRemoteWithExecute),
1949 "--no-remote cannot be combined with --remote-execute"
1950 );
1951 assert_eq!(
1952 text(RemoteFlagConflict::ExecuteBothWays),
1953 "--remote-execute cannot be combined with --no-remote-execute"
1954 );
1955 assert_eq!(
1956 text(RemoteFlagConflict::ExecutionWithoutRemote),
1957 "--remote-execute, --no-remote-execute and --remote-jobs need a [remote] table \
1958 in buildl.toml, and this workspace has none"
1959 );
1960 assert_eq!(
1961 text(RemoteFlagConflict::JobsWithoutExecution),
1962 "--remote-jobs needs remote execution, and it is off in this run"
1963 );
1964 }
1965
1966 #[test]
1967 fn an_unsandboxed_upload_says_how_to_sandbox_or_stop_uploading() {
1968 assert_eq!(
1969 Error::UploadUnsandboxed {
1970 which: UnsandboxedRemote::Upload
1971 }
1972 .to_string(),
1973 "uploading to the remote cache needs actions to run in the input sandbox, \
1974 but strategy is \"bare\"; set strategy to \"sandbox\", or stop uploading by \
1975 unsetting BUILDL_REMOTE_UPLOAD or dropping --remote-upload"
1976 );
1977 }
1978
1979 #[test]
1980 fn an_unsandboxed_execution_says_how_to_sandbox_or_stop_executing() {
1981 assert_eq!(
1982 Error::UploadUnsandboxed {
1983 which: UnsandboxedRemote::Execute
1984 }
1985 .to_string(),
1986 "executing on the remote needs actions to run in the input sandbox, \
1987 but strategy is \"bare\"; set strategy to \"sandbox\", or stop executing by \
1988 setting execute to false in [remote], unsetting BUILDL_REMOTE_EXECUTE or \
1989 dropping --remote-execute"
1990 );
1991 }
1992
1993 #[test]
1994 fn not_a_test_names_the_target_and_its_file() {
1995 let err = Error::NotATest {
1996 asked: label("//:default"),
1997 declared_with: TargetRole::Build,
1998 site: Box::new(root_site("//:app")),
1999 };
2000 assert_eq!(
2001 err.to_string(),
2002 "target //:default was asked for as a test, but //:app is declared with b.target in build.lua"
2003 );
2004 }
2005
2006 #[test]
2007 fn not_a_test_names_the_function_that_declared_a_discovery_target() {
2008 let err = Error::NotATest {
2009 asked: label("//:pkgs"),
2010 declared_with: TargetRole::Discovery,
2011 site: Box::new(root_site("//:pkgs")),
2012 };
2013 assert_eq!(
2014 err.to_string(),
2015 "target //:pkgs was asked for as a test, but //:pkgs is declared with b.discover in build.lua"
2016 );
2017 }
2018
2019 #[test]
2020 fn not_a_test_names_the_plugin_chain_of_a_target_a_plugin_declared() {
2021 let err = Error::NotATest {
2022 asked: label("//:default"),
2023 declared_with: TargetRole::Build,
2024 site: Box::new(DeclarationSite {
2025 origin: ourgo_chain(),
2026 ..root_site("//:app")
2027 }),
2028 };
2029 assert_eq!(
2030 err.to_string(),
2031 "target //:default was asked for as a test, but //:app is declared with b.target in \
2032 build.lua, plugin ourgo@0.1.0 > go@1.2.0"
2033 );
2034 }
2035
2036 #[test]
2037 fn invalid_query_names_the_query_and_the_two_forms() {
2038 let err = Error::InvalidQuery {
2039 expression: "dep(//:a)".to_owned(),
2040 };
2041 assert_eq!(
2042 err.to_string(),
2043 "query `dep(//:a)` is not deps(<target>) or rdeps(<target>)"
2044 );
2045 }
2046
2047 fn line(number: usize) -> NonZeroUsize {
2048 NonZeroUsize::new(number).unwrap()
2049 }
2050
2051 #[test]
2052 fn no_run_names_the_target_and_a_suggestion() {
2053 let err = Error::NoRun {
2054 label: label("//:ap"),
2055 suggestion: Some(label("//:app")),
2056 damaged: Vec::new(),
2057 };
2058 assert_eq!(
2059 err.to_string(),
2060 "target //:ap has no run in the log (did you mean //:app?)"
2061 );
2062 let without = Error::NoRun {
2063 label: label("//:ap"),
2064 suggestion: None,
2065 damaged: Vec::new(),
2066 };
2067 assert_eq!(without.to_string(), "target //:ap has no run in the log");
2068 }
2069
2070 #[test]
2071 fn no_run_names_the_damaged_lines() {
2072 let two = Error::NoRun {
2073 label: label("//:app"),
2074 suggestion: None,
2075 damaged: vec![line(14), line(90)],
2076 };
2077 assert_eq!(
2078 two.to_string(),
2079 "target //:app has no run in the log; 2 damaged lines were skipped (lines 14, 90)"
2080 );
2081 let one = Error::NoRun {
2082 label: label("//:app"),
2083 suggestion: None,
2084 damaged: vec![line(14)],
2085 };
2086 assert_eq!(
2087 one.to_string(),
2088 "target //:app has no run in the log; 1 damaged line was skipped (line 14)"
2089 );
2090 }
2091
2092 #[test]
2093 fn missing_output_names_the_target() {
2094 let err = Error::MissingOutput {
2095 label: label("//:app"),
2096 };
2097 assert_eq!(
2098 err.to_string(),
2099 "target //:app: the output of its last logged run is no longer in the store"
2100 );
2101 }
2102
2103 #[test]
2104 fn a_foreign_plan_says_the_plan_does_not_belong_to_the_graph() {
2105 assert_eq!(
2106 Error::ForeignPlan.to_string(),
2107 "the plan was not made from this graph"
2108 );
2109 }
2110
2111 #[test]
2112 fn an_output_conflict_names_the_path_and_both_targets_with_their_files() {
2113 let err = Error::OutputConflict {
2114 path: OutputPath::of(
2115 &Directory::parse("out").unwrap(),
2116 &label("//:lib"),
2117 &OutputName::parse("lib").unwrap(),
2118 ),
2119 first: Box::new(root_site("//:lib")),
2120 second: Box::new(DeclarationSite {
2121 label: label("//lib:text"),
2122 provenance: lib_file(),
2123 origin: Origin::BuildFile,
2124 }),
2125 };
2126 assert_eq!(
2127 err.to_string(),
2128 "out/lib: //:lib (build.lua) and //lib:text (lib/build.lua) cannot both write here"
2129 );
2130 }
2131
2132 #[test]
2133 fn an_output_conflict_names_the_plugin_chain_of_a_target_a_plugin_declared() {
2134 let err = Error::OutputConflict {
2135 path: OutputPath::of(
2136 &Directory::parse("out").unwrap(),
2137 &label("//:lib"),
2138 &OutputName::parse("lib").unwrap(),
2139 ),
2140 first: Box::new(DeclarationSite {
2141 origin: ourgo_chain(),
2142 ..root_site("//:lib")
2143 }),
2144 second: Box::new(root_site("//:other")),
2145 };
2146 assert_eq!(
2147 err.to_string(),
2148 "out/lib: //:lib (build.lua, plugin ourgo@0.1.0 > go@1.2.0) and //:other (build.lua) \
2149 cannot both write here"
2150 );
2151 }
2152
2153 #[test]
2154 fn an_output_conflict_inside_one_target_names_that_target_twice() {
2155 let err = Error::OutputConflict {
2156 path: OutputPath::of(
2157 &Directory::parse("out").unwrap(),
2158 &label("//:app"),
2159 &OutputName::parse("app").unwrap(),
2160 ),
2161 first: Box::new(root_site("//:app")),
2162 second: Box::new(root_site("//:app")),
2163 };
2164 assert_eq!(
2165 err.to_string(),
2166 "out/app: //:app (build.lua) and //:app (build.lua) cannot both write here"
2167 );
2168 }
2169
2170 #[test]
2171 fn no_program_names_the_site_of_the_command() {
2172 let err = Error::NoProgram {
2173 site: Box::new(root_site("//:app")),
2174 };
2175 assert_eq!(
2176 err.to_string(),
2177 "build.lua: //:app: the command names no program once expanded"
2178 );
2179 }
2180
2181 #[test]
2182 fn a_program_a_command_names_only_once_expanded_is_refused_like_any_other() {
2183 let err = Error::Refused {
2184 want: Want::Program(Program::parse("out/app").unwrap()),
2185 site: Some(Box::new(root_site("//:app_test"))),
2186 ceiling: Box::new(Ceiling {
2187 run: BTreeSet::from([Program::parse("cc").unwrap()]),
2188 env: BTreeSet::new(),
2189 read: BTreeSet::new(),
2190 write: BTreeSet::new(),
2191 }),
2192 };
2193 assert_eq!(
2194 err.to_string(),
2195 "build.lua: //:app_test: program out/app is outside the ceiling (proc.run allows: cc)"
2196 );
2197 }
2198
2199 #[test]
2200 fn adapter_names_the_port_before_the_adapters_own_message() {
2201 let err = Error::Adapter {
2202 port: PortName::StatCache,
2203 diagnostic: Diagnostic::new("statcache.json: permission denied"),
2204 };
2205 assert_eq!(
2206 err.to_string(),
2207 "stat cache: statcache.json: permission denied"
2208 );
2209 }
2210
2211 #[test]
2212 fn a_dispatcher_fault_names_the_dispatcher_and_the_targets_left_without_an_outcome() {
2213 let lost = Error::DispatcherFault {
2214 targets: vec![label("//:a"), label("//lib:b")],
2215 };
2216 assert_eq!(
2217 lost.to_string(),
2218 "dispatcher: returned without an outcome for //:a, //lib:b"
2219 );
2220 }
2221
2222 #[test]
2223 fn lost_build_files_names_each_directory() {
2224 let lost = Error::LostBuildFiles {
2225 directories: vec![Directory::root(), Directory::parse("lib").unwrap()],
2226 };
2227 assert_eq!(
2228 lost.to_string(),
2229 "dispatcher: returned without evaluating the build files of //, //lib"
2230 );
2231 }
2232
2233 #[test]
2234 fn every_port_name_renders_a_human_phrase() {
2235 let cases = [
2236 (PortName::Manifest, "manifest"),
2237 (PortName::Host, "host"),
2238 (PortName::Digester, "digester"),
2239 (PortName::StatCache, "stat cache"),
2240 (PortName::ToolResolver, "tool resolver"),
2241 (PortName::ActionCache, "action cache"),
2242 (PortName::ContentStore, "content store"),
2243 (PortName::EventLog, "event log"),
2244 (PortName::RunHistory, "run history"),
2245 (PortName::ExecStrategy, "exec strategy"),
2246 (PortName::Dispatcher, "dispatcher"),
2247 (PortName::GraphRecord, "graph record"),
2248 (PortName::Sweep, "sweep"),
2249 (PortName::Approver, "approver"),
2250 (PortName::PluginStore, "plugin store"),
2251 (PortName::RemoteCache, "remote cache"),
2252 (PortName::Changes, "file watcher"),
2253 ];
2254 for (port, rendered) in cases {
2255 assert_eq!(port.to_string(), rendered);
2256 }
2257 }
2258
2259 #[test]
2260 fn the_remote_cache_port_is_named_in_errors() {
2261 let err = Error::Adapter {
2262 port: PortName::RemoteCache,
2263 diagnostic: Diagnostic::new("connection refused"),
2264 };
2265 assert_eq!(PortName::RemoteCache.to_string(), "remote cache");
2266 assert_eq!(err.to_string(), "remote cache: connection refused");
2267 }
2268
2269 #[test]
2270 fn name_kind_renders_a_human_phrase() {
2271 assert_eq!(NameKind::Directory.to_string(), "directory");
2272 assert_eq!(NameKind::TargetName.to_string(), "target name");
2273 assert_eq!(NameKind::Label.to_string(), "label");
2274 assert_eq!(NameKind::Digest.to_string(), "digest");
2275 assert_eq!(NameKind::SourcePath.to_string(), "source path");
2276 assert_eq!(NameKind::OutputName.to_string(), "output name");
2277 assert_eq!(NameKind::EnvName.to_string(), "environment variable name");
2278 assert_eq!(NameKind::Argument.to_string(), "argument");
2279 assert_eq!(NameKind::Command.to_string(), "command");
2280 assert_eq!(NameKind::Description.to_string(), "description");
2281 assert_eq!(NameKind::SettingName.to_string(), "setting name");
2282 assert_eq!(NameKind::SettingValue.to_string(), "setting value");
2283 assert_eq!(NameKind::EntryName.to_string(), "entry file name");
2284 assert_eq!(NameKind::FieldName.to_string(), "field name");
2285 assert_eq!(NameKind::Program.to_string(), "program");
2286 assert_eq!(NameKind::EnvValue.to_string(), "environment variable value");
2287 assert_eq!(NameKind::Platform.to_string(), "platform");
2288 assert_eq!(NameKind::Workers.to_string(), "worker count");
2289 assert_eq!(NameKind::Timeout.to_string(), "timeout");
2290 assert_eq!(NameKind::Isolation.to_string(), "execution strategy");
2291 assert_eq!(NameKind::Approver.to_string(), "approver mode");
2292 assert_eq!(NameKind::TreePath.to_string(), "tree path");
2293 assert_eq!(NameKind::PluginName.to_string(), "plugin name");
2294 assert_eq!(NameKind::PluginVersion.to_string(), "plugin version");
2295 assert_eq!(NameKind::PluginChain.to_string(), "plugin chain");
2296 assert_eq!(NameKind::RemoteUrl.to_string(), "remote cache URL");
2297 assert_eq!(NameKind::InstanceName.to_string(), "instance name");
2298 assert_eq!(NameKind::HostPath.to_string(), "host path");
2299 assert_eq!(NameKind::HeaderName.to_string(), "header name");
2300 assert_eq!(NameKind::ChangedPath.to_string(), "changed path");
2301 assert_eq!(NameKind::RemoteJobs.to_string(), "remote job count");
2302 assert_eq!(NameKind::RetryCount.to_string(), "retry count");
2303 assert_eq!(
2304 NameKind::PlatformProperty.to_string(),
2305 "platform property name"
2306 );
2307 }
2308
2309 #[test]
2310 fn an_insecure_token_names_the_url_and_the_fix() {
2311 let url = RemoteUrl::parse("grpc://cache:50051").unwrap();
2312 assert_eq!(
2313 Error::InsecureToken { url }.to_string(),
2314 "a token would be sent in clear text to grpc://cache:50051; use a grpcs:// URL"
2315 );
2316 }
2317
2318 #[test]
2319 fn invalid_name_states_what_was_found() {
2320 let err = Error::InvalidName {
2321 kind: NameKind::Label,
2322 value: "//lib".to_owned(),
2323 reason: "must hold ':' and a target name",
2324 };
2325 assert_eq!(
2326 err.to_string(),
2327 r#"invalid label: "//lib" — must hold ':' and a target name"#
2328 );
2329 }
2330
2331 #[test]
2332 fn canonical_json_states_the_value_could_not_be_serialized() {
2333 let Err(source) = serde_json::to_value(u128::MAX) else {
2334 unreachable!("u128::MAX has no JSON number representation")
2335 };
2336 let err = Error::CanonicalJson { source };
2337 assert_eq!(
2338 err.to_string(),
2339 "value could not be serialized as canonical JSON"
2340 );
2341 }
2342
2343 #[test]
2344 fn float_rejected_states_where_the_float_was_found() {
2345 let err = Error::FloatRejected {
2346 path: "$.timings.elapsed".to_owned(),
2347 };
2348 assert_eq!(
2349 err.to_string(),
2350 "floating-point value at $.timings.elapsed cannot appear in canonical JSON"
2351 );
2352 }
2353
2354 #[test]
2355 fn unreadable_json_states_what_could_not_be_read() {
2356 let Err(source) = serde_json::from_slice::<u32>(b"[]") else {
2357 unreachable!("an array is not a number")
2358 };
2359 let err = Error::UnreadableJson { source };
2360 assert_eq!(
2361 err.to_string(),
2362 "canonical JSON could not be read: invalid type: sequence, expected u32 at line 1 \
2363 column 0"
2364 );
2365 }
2366
2367 #[test]
2368 fn non_canonical_json_states_where_the_bytes_differ() {
2369 let err = Error::NonCanonicalJson { offset: 36 };
2370 assert_eq!(
2371 err.to_string(),
2372 "JSON is not in canonical form: it differs from it at byte 36"
2373 );
2374 }
2375
2376 #[test]
2377 fn corrupt_state_names_the_file_and_keeps_the_reading_failure() {
2378 let err = Error::CorruptState {
2379 file: PathBuf::from("/ws/.buildl/cache.json"),
2380 source: Box::new(Error::NonCanonicalJson { offset: 36 }),
2381 };
2382 assert_eq!(
2383 err.to_string(),
2384 "/ws/.buildl/cache.json is not a file buildl wrote: JSON is not in canonical form: \
2385 it differs from it at byte 36"
2386 );
2387 assert_eq!(
2388 std::error::Error::source(&err).unwrap().to_string(),
2389 "JSON is not in canonical form: it differs from it at byte 36"
2390 );
2391 let Error::CorruptState { source, .. } = err else {
2392 unreachable!("built as CorruptState above")
2393 };
2394 assert!(matches!(*source, Error::NonCanonicalJson { offset: 36 }));
2395 }
2396
2397 #[test]
2398 fn evaluation_names_the_file_the_failure_and_the_message() {
2399 let err = Error::Evaluation {
2400 provenance: lib_file(),
2401 failure: EvaluationFailure::Syntax,
2402 diagnostic: Diagnostic::new("unexpected symbol near '}'"),
2403 };
2404 assert_eq!(
2405 err.to_string(),
2406 "lib/build.lua: syntax error: unexpected symbol near '}'"
2407 );
2408 }
2409
2410 #[test]
2411 fn every_evaluation_failure_renders_a_human_phrase() {
2412 let field = || Written::<FieldName>::new("dep");
2413 let cases = [
2414 (EvaluationFailure::Syntax, "syntax error"),
2415 (EvaluationFailure::Runtime, "runtime error"),
2416 (EvaluationFailure::Refused, "operation refused"),
2417 (
2418 EvaluationFailure::LimitReached {
2419 limit: EvaluationLimit::Instructions,
2420 },
2421 "instruction ceiling reached",
2422 ),
2423 (
2424 EvaluationFailure::LimitReached {
2425 limit: EvaluationLimit::Memory,
2426 },
2427 "memory ceiling reached",
2428 ),
2429 (
2430 EvaluationFailure::LimitReached {
2431 limit: EvaluationLimit::Staging,
2432 },
2433 "staging cap reached",
2434 ),
2435 (
2436 EvaluationFailure::LimitReached {
2437 limit: EvaluationLimit::Walk,
2438 },
2439 "walk cap reached",
2440 ),
2441 (
2442 EvaluationFailure::UnknownField { field: field() },
2443 r#"unknown field "dep""#,
2444 ),
2445 (
2446 EvaluationFailure::WrongFieldType { field: field() },
2447 r#"field "dep" has the wrong type"#,
2448 ),
2449 ];
2450 for (failure, rendered) in cases {
2451 assert_eq!(failure.to_string(), rendered);
2452 }
2453 }
2454
2455 #[test]
2456 fn missing_build_file_names_the_root_or_the_requester() {
2457 let root = Error::MissingBuildFile {
2458 directory: Directory::root(),
2459 requested_by: None,
2460 };
2461 assert_eq!(root.to_string(), "no build file in // (the workspace root)");
2462 let requested = Error::MissingBuildFile {
2463 directory: Directory::parse("lib/text").unwrap(),
2464 requested_by: Some(lib_file()),
2465 };
2466 assert_eq!(
2467 requested.to_string(),
2468 "no build file in //lib/text (requested by lib/build.lua)"
2469 );
2470 }
2471
2472 #[test]
2473 fn invalid_declaration_names_the_site_the_field_and_the_grammar() {
2474 let source = TargetName::parse("a/b").unwrap_err();
2475 let source_text = source.to_string();
2476 let err = Error::InvalidDeclaration {
2477 provenance: lib_file(),
2478 origin: Origin::BuildFile,
2479 order: DeclarationOrder::new(2),
2480 field: DeclarationField::Dep,
2481 source: Box::new(source),
2482 };
2483 assert_eq!(
2484 err.to_string(),
2485 r#"lib/build.lua: declaration #2: invalid dep: invalid target name: "a/b" — may hold only ASCII letters, digits, '.', '-' and '_'"#
2486 );
2487 assert_eq!(
2488 std::error::Error::source(&err).unwrap().to_string(),
2489 source_text
2490 );
2491 }
2492
2493 #[test]
2494 fn stdout_outputs_names_the_target_and_the_count() {
2495 let err = Error::StdoutOutputs {
2496 target: "//svc:gen".parse().unwrap(),
2497 outputs: 2,
2498 };
2499 assert_eq!(
2500 err.to_string(),
2501 "target //svc:gen declares 2 outputs; a target whose output is its stdout declares exactly one"
2502 );
2503 }
2504
2505 #[test]
2506 fn not_accepted_states_why_the_declaration_cannot_hold_the_value() {
2507 let err = Error::NotAccepted {
2508 reason: "a discovery target is always cached",
2509 };
2510 assert_eq!(err.to_string(), "a discovery target is always cached");
2511 }
2512
2513 #[test]
2514 fn invalid_declaration_names_the_plugin_chain_of_a_declaration_a_plugin_made() {
2515 let err = Error::InvalidDeclaration {
2516 provenance: lib_file(),
2517 origin: ourgo_chain(),
2518 order: DeclarationOrder::new(2),
2519 field: DeclarationField::Dep,
2520 source: Box::new(TargetName::parse("a/b").unwrap_err()),
2521 };
2522 assert!(
2523 err.to_string().starts_with(
2524 "lib/build.lua (plugin ourgo@0.1.0 > go@1.2.0): declaration #2: invalid dep: "
2525 ),
2526 "{err}"
2527 );
2528 }
2529
2530 #[test]
2531 fn every_declaration_field_renders_a_human_phrase() {
2532 let cases = [
2533 (DeclarationField::Name, "name"),
2534 (DeclarationField::Dep, "dep"),
2535 (DeclarationField::Input, "input"),
2536 (DeclarationField::Output, "output"),
2537 (DeclarationField::Env, "env"),
2538 (DeclarationField::Run, "run"),
2539 (DeclarationField::Rule, "rule"),
2540 (DeclarationField::Description, "description"),
2541 (DeclarationField::Target, "target"),
2542 (DeclarationField::SettingName, "setting name"),
2543 (DeclarationField::SettingValue, "setting value"),
2544 (DeclarationField::Freshness, "freshness"),
2545 (DeclarationField::Stdout, "stdout"),
2546 (DeclarationField::Subdir, "subdir"),
2547 ];
2548 for (field, rendered) in cases {
2549 assert_eq!(field.to_string(), rendered);
2550 }
2551 }
2552
2553 #[test]
2554 fn action_conflict_states_what_was_found() {
2555 let both = Error::ActionConflict {
2556 provenance: lib_file(),
2557 origin: Origin::BuildFile,
2558 order: DeclarationOrder::new(0),
2559 found: ActionFound::Both,
2560 };
2561 assert_eq!(
2562 both.to_string(),
2563 "lib/build.lua: declaration #0: a target names both 'rule' and 'run'"
2564 );
2565 let neither = Error::ActionConflict {
2566 provenance: lib_file(),
2567 origin: Origin::BuildFile,
2568 order: DeclarationOrder::new(1),
2569 found: ActionFound::Neither,
2570 };
2571 assert_eq!(
2572 neither.to_string(),
2573 "lib/build.lua: declaration #1: a target names neither 'rule' nor 'run'"
2574 );
2575 }
2576
2577 #[test]
2578 fn action_conflict_names_the_plugin_chain_of_a_declaration_a_plugin_made() {
2579 let err = Error::ActionConflict {
2580 provenance: lib_file(),
2581 origin: ourgo_chain(),
2582 order: DeclarationOrder::new(0),
2583 found: ActionFound::Both,
2584 };
2585 assert_eq!(
2586 err.to_string(),
2587 "lib/build.lua (plugin ourgo@0.1.0 > go@1.2.0): declaration #0: a target names both \
2588 'rule' and 'run'"
2589 );
2590 }
2591
2592 #[test]
2593 fn nondeterministic_names_the_file_to_fix() {
2594 let err = Error::Nondeterministic {
2595 provenance: lib_file(),
2596 first_run: None,
2597 second_run: None,
2598 };
2599 assert_eq!(
2600 err.to_string(),
2601 "lib/build.lua: declarations differ between two evaluations"
2602 );
2603 }
2604
2605 #[test]
2606 fn discovery_changed_names_the_target_and_its_file() {
2607 let err = Error::DiscoveryChanged {
2608 label: Label::parse("//lib:pkgs").unwrap(),
2609 provenance: lib_file(),
2610 };
2611 assert_eq!(
2612 err.to_string(),
2613 "lib/build.lua: discovery target //lib:pkgs differs once discovery results are \
2614 read; a discovery target may not depend on a discovery result"
2615 );
2616 }
2617
2618 #[test]
2619 fn an_invalid_tree_says_what_is_wrong_with_the_list() {
2620 let path = TreePath::parse("assets/app.js").unwrap();
2621 for (fault, rendered) in [
2622 (TreeFault::Empty, "not a tree: it holds no file"),
2623 (
2624 TreeFault::Repeated(path.clone()),
2625 "not a tree: assets/app.js is listed twice",
2626 ),
2627 (
2628 TreeFault::Clash(path),
2629 "not a tree: assets/app.js is both a file and a directory",
2630 ),
2631 ] {
2632 assert_eq!(Error::InvalidTree { fault }.to_string(), rendered);
2633 }
2634 }
2635}