1use std::fs;
2use std::path::Path;
3use std::path::PathBuf;
4
5use serde::Deserialize;
6use serde_json::Value;
7use serde_json::json;
8
9use crate::Cli;
10use crate::CliError;
11use crate::command::CommandContext;
12pub(crate) use crate::compatibility::CompatibilityErrorCode;
13pub(crate) use crate::compatibility::CompatibilityRequirement;
14pub use crate::compatibility::MinimumVersion;
15pub(crate) use crate::compatibility::VERSION_PROBE_SCHEMA;
16pub(crate) use crate::compatibility::compatibility_config_error;
17pub(crate) use crate::compatibility::compatibility_requirement_from_file;
18pub(crate) use crate::compatibility::load_compatibility_requirement;
19pub(crate) use crate::compatibility::missing_consumer_field;
20pub(crate) use crate::consumer_integration::run_consumer_init;
21#[cfg(test)]
22pub(crate) use crate::consumer_integration::run_consumer_init_at;
23use crate::error::ErrorCode;
24pub(crate) use crate::profile_plan::ConsumerProfileStep;
25use crate::profile_plan::LintPlanInput;
26use crate::profile_plan::LintProfiles;
27use crate::profile_plan::ProfileName;
28use crate::profile_plan::decode_after_all;
29use crate::profile_plan::decode_lint_step_fields;
30use crate::profile_plan::profile_plan_config_error;
31use crate::profile_plan::reject_test_step_fields;
32use crate::profile_plan::validate_lint_step;
33
34use crate::test_selectors::TestSelectors;
35
36pub(crate) const CONFIG_FILENAME: &str = "sc-lint.toml";
37
38pub(crate) const CONSUMER_SELECTOR_ALL: &str = "all";
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum ConsumerProfile {
43 Lint,
44 Test,
45}
46
47impl ConsumerProfile {
48 pub(crate) const fn as_str(self) -> &'static str {
49 match self {
50 Self::Lint => "lint",
51 Self::Test => "test",
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct LoadedConfig {
58 repo_root: Option<RepoRoot>,
59 config_path: Option<PathBuf>,
60 explicit_config: Option<PathBuf>,
61 logging_root: Option<PathBuf>,
62 logging_console: bool,
63 mode: LoadedConfigMode,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
69enum LoadedConfigMode {
70 Standard,
71 Compatibility(CompatibilityRequirement),
72 Consumer(ConsumerRequirement),
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76struct ConsumerRequirement {
77 compatibility: CompatibilityRequirement,
78 root: PathBuf,
79 lint: Vec<ConsumerProfileStep>,
80 lint_profiles: LintProfiles,
81 default_lint_profile: Option<String>,
82 test: TestSelectors,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub(crate) enum ConfigCode {
87 BoundariesDirMissing,
88 TableMissing,
89 UnknownTable,
90}
91
92impl ConfigCode {
93 pub(crate) fn from_wire(value: &str) -> Option<Self> {
94 match value {
95 "config.table_missing" => Some(Self::TableMissing),
96 _ => None,
97 }
98 }
99}
100
101impl ErrorCode for ConfigCode {
102 fn as_str(&self) -> &'static str {
103 match self {
104 Self::BoundariesDirMissing => "config.boundaries_dir_missing",
105 Self::TableMissing => "config.table_missing",
106 Self::UnknownTable => "config.unknown_table",
107 }
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub(crate) struct RepoRoot(PathBuf);
113
114impl RepoRoot {
115 #[expect(
116 clippy::result_large_err,
117 reason = "Repo-root discovery failures are part of the stable top-level CliError contract."
118 )]
119 fn discover(start: &Path) -> Result<Self, CliError> {
120 let mut current = if start.is_dir() {
121 start.to_path_buf()
122 } else {
123 start
124 .parent()
125 .map_or_else(|| start.to_path_buf(), Path::to_path_buf)
126 };
127 current = dunce::canonicalize(¤t).map_err(|error| {
128 let message = if error.kind() == std::io::ErrorKind::NotFound {
129 format!("repository root path `{}` does not exist", start.display())
130 } else {
131 format!("failed to canonicalize repo-root discovery start `{}`", start.display())
132 };
133 CliError::config(message)
134 .with_source(error)
135 .with_detail("discovery_start", json!(start.display().to_string()))
136 .with_suggested_action("Pass `--root <path>` to an existing repository root, or change to the repository and rerun the command.")
137 })?;
138
139 loop {
140 if current.join(CONFIG_FILENAME).is_file() || workspace_manifest(¤t) {
141 return Ok(Self(current));
142 }
143 let inspected = current.clone();
144 if !current.pop() {
145 return Err(CliError::config(format!(
146 "could not discover the sc-lint repo root from `{}`; last inspected `{}` was missing required sentinels `sc-lint.toml` or `Cargo.toml [workspace]`",
147 start.display(),
148 inspected.display()
149 ))
150 .with_detail("discovery_start", json!(start.display().to_string()))
151 .with_detail("last_inspected", json!(inspected.display().to_string()))
152 .with_detail("required_sentinels", json!(["sc-lint.toml", "Cargo.toml [workspace]"]))
153 .with_suggested_action(
154 "Run the command inside the repo or pass `--root <path>` to the workspace root.",
155 ));
156 }
157 }
158 }
159
160 pub(crate) fn as_path(&self) -> &Path {
161 &self.0
162 }
163}
164
165fn workspace_manifest(path: &Path) -> bool {
166 let manifest = path.join("Cargo.toml");
167 manifest.is_file()
168 && fs::read_to_string(manifest)
169 .ok()
170 .and_then(|contents| toml::from_str::<toml::Value>(&contents).ok())
171 .and_then(|value| value.get("workspace").cloned())
172 .is_some_and(|value| value.is_table())
173}
174
175impl LoadedConfig {
176 #[expect(
177 clippy::result_large_err,
178 reason = "Config loading failures are part of the stable top-level CliError contract."
179 )]
180 pub fn load(cli: &Cli, context: &CommandContext) -> Result<Self, CliError> {
181 if matches!(
182 context.id(),
183 crate::command::CommandId::ConsumerLintCi | crate::command::CommandId::ConsumerTest
184 ) {
185 return Self::load_consumer(cli);
186 }
187 if context.requires_compatibility_config() {
188 return Self::load_compatibility(cli);
189 }
190 if !context.requires_repo_root() {
191 return Ok(Self {
192 repo_root: None,
193 config_path: None,
194 explicit_config: None,
195 logging_root: cli.log_root.clone(),
196 logging_console: cli.log_console,
197 mode: LoadedConfigMode::Standard,
198 });
199 }
200
201 let discovery_base = if let Some(root) = cli.root.as_ref() {
202 root.clone()
203 } else {
204 std::env::current_dir().map_err(|error| {
205 CliError::config("failed to read current directory").with_source(error)
206 })?
207 };
208 let repo_root = RepoRoot::discover(&discovery_base)?;
209 let explicit_config = cli
210 .config
211 .as_ref()
212 .map(|path| resolve_repo_relative_path(repo_root.as_path(), path));
213 let config_path = find_repo_config(repo_root.as_path(), explicit_config.as_deref());
214 let file_config = if let Some(path) = config_path.as_ref() {
215 parse_repo_config(path)?
216 } else {
217 RepoConfigFile::default()
218 };
219
220 let logging_root = cli.log_root.clone().or_else(|| {
221 file_config
222 .logging
223 .as_ref()
224 .and_then(|logging| logging.root.as_ref())
225 .map(|path| resolve_repo_relative_path(repo_root.as_path(), path))
226 });
227 let logging_console = if cli.log_console {
228 true
229 } else {
230 file_config
231 .logging
232 .as_ref()
233 .and_then(|logging| logging.console)
234 .unwrap_or(false)
235 };
236
237 Ok(Self {
238 repo_root: Some(repo_root),
239 config_path,
240 explicit_config,
241 logging_root,
242 logging_console,
243 mode: LoadedConfigMode::Standard,
244 })
245 }
246
247 #[expect(
248 clippy::result_large_err,
249 reason = "The installer shares the established stable CliError contract at the consumer configuration boundary."
250 )]
251 pub(crate) fn compatibility_requirement(&self) -> Result<(&MinimumVersion, &Path), CliError> {
252 match &self.mode {
253 LoadedConfigMode::Compatibility(requirement) => {
254 Ok((&requirement.minimum_version, &requirement.config_path))
255 }
256 LoadedConfigMode::Consumer(requirement) => Ok((
257 &requirement.compatibility.minimum_version,
258 &requirement.compatibility.config_path,
259 )),
260 LoadedConfigMode::Standard => Err(CliError::internal(
261 "installation commands require a loaded consumer compatibility configuration",
262 )),
263 }
264 }
265
266 #[expect(
268 clippy::result_large_err,
269 reason = "Consumer test selection retains the shared top-level CliError contract."
270 )]
271 pub(crate) fn test_selectors(&self) -> Result<(&Path, &TestSelectors), CliError> {
272 let LoadedConfigMode::Consumer(requirement) = &self.mode else {
273 return Err(CliError::internal(
274 "consumer profile execution requires a consumer configuration",
275 ));
276 };
277 Ok((&requirement.root, &requirement.test))
278 }
279
280 #[expect(
286 clippy::result_large_err,
287 reason = "Consumer lint selection retains the shared top-level CliError contract."
288 )]
289 pub(crate) fn consumer_lint_inputs(
290 &self,
291 selector: Option<&str>,
292 ) -> Result<LintPlanInput<'_>, CliError> {
293 let LoadedConfigMode::Consumer(requirement) = &self.mode else {
294 return Err(CliError::internal(
295 "consumer profile execution requires a consumer configuration",
296 ));
297 };
298 if requirement.lint.is_empty() {
299 return Err(consumer_profile_error(
300 self.config_path.as_deref().unwrap_or_else(|| Path::new(CONFIG_FILENAME)),
301 ConsumerProfile::Lint.as_str(),
302 "consumer `lint` profile has no configured steps".to_string(),
303 ).with_suggested_action(
304 "Add at least one `[[tool.sc-lint.lint]]` command row before running consumer lint.",
305 ));
306 }
307 let selector = crate::profile_host::lint_selector(
308 selector,
309 requirement.default_lint_profile.as_deref(),
310 &requirement.lint_profiles.names(),
311 self.config_path
312 .as_deref()
313 .expect("consumer config has path"),
314 )?;
315 let report_selector = selector.unwrap_or(CONSUMER_SELECTOR_ALL).to_owned();
316 let steps = &requirement.lint;
317 let root = requirement.root.as_path();
318 let Some(name) = selector.filter(|name| *name != CONSUMER_SELECTOR_ALL) else {
319 return Ok(LintPlanInput {
320 root,
321 report_selector,
322 steps: steps.clone(),
323 selector: None,
324 });
325 };
326 if steps.iter().any(|step| step.name() == name) {
327 let selector = Some(ProfileName::parse(name.to_string())?);
328 return Ok(LintPlanInput {
329 root,
330 report_selector,
331 steps: steps.clone(),
332 selector,
333 });
334 }
335 if let Some(members) = requirement.lint_profiles.resolve(name, steps) {
336 return Ok(LintPlanInput {
337 root,
338 report_selector,
339 steps: members,
340 selector: None,
341 });
342 }
343 let mut available: Vec<&str> = steps.iter().map(ConsumerProfileStep::name).collect();
344 available.extend(requirement.lint_profiles.names());
345 Err(consumer_profile_error(
346 self.config_path
347 .as_deref()
348 .unwrap_or_else(|| Path::new(CONFIG_FILENAME)),
349 ConsumerProfile::Lint.as_str(),
350 format!(
351 "consumer `lint` profile has no step or profile named `{name}`; configured: {}",
352 available.join(", ")
353 ),
354 )
355 .with_detail("selector", json!(name))
356 .with_detail("available", json!(available))
357 .with_suggested_action(format!(
358 "Pass one of the configured step or profile names or `{CONSUMER_SELECTOR_ALL}`."
359 )))
360 }
361
362 #[expect(
363 clippy::result_large_err,
364 reason = "Compatibility configuration errors are deliberately surfaced through CliError."
365 )]
366 fn load_compatibility(cli: &Cli) -> Result<Self, CliError> {
367 let current_dir = std::env::current_dir().map_err(|error| {
368 compatibility_config_error(
369 CompatibilityErrorCode::ConfigMissing,
370 format!("failed to read the current directory while locating `{CONFIG_FILENAME}`"),
371 None,
372 None,
373 )
374 .with_source(error)
375 })?;
376 let config_path = cli.config.as_ref().map_or_else(
377 || current_dir.join(CONFIG_FILENAME),
378 |path| resolve_current_dir_relative_path(¤t_dir, path),
379 );
380 let requirement = load_compatibility_requirement(&config_path)?;
381
382 Ok(Self {
383 repo_root: None,
384 config_path: Some(config_path),
385 explicit_config: None,
386 logging_root: cli.log_root.clone(),
387 logging_console: cli.log_console,
388 mode: LoadedConfigMode::Compatibility(requirement),
389 })
390 }
391
392 #[expect(
393 clippy::result_large_err,
394 reason = "Consumer profiles are validated before a product command can launch any configured backend."
395 )]
396 fn load_consumer(cli: &Cli) -> Result<Self, CliError> {
397 let current_dir = std::env::current_dir().map_err(|error| {
398 compatibility_config_error(
399 CompatibilityErrorCode::ConfigMissing,
400 format!("failed to read the current directory while locating `{CONFIG_FILENAME}`"),
401 None,
402 None,
403 )
404 .with_source(error)
405 })?;
406 let config_path = cli.config.as_ref().map_or_else(
407 || current_dir.join(CONFIG_FILENAME),
408 |path| resolve_current_dir_relative_path(¤t_dir, path),
409 );
410 let file_config = load_consumer_config_file(&config_path)?;
411 let sc_lint = file_config
412 .tool
413 .as_ref()
414 .and_then(|tool| tool.sc_lint.as_ref())
415 .ok_or_else(|| missing_consumer_field(&config_path, "[tool.sc-lint]"))?;
416 let compatibility = compatibility_requirement_from_file(sc_lint, &config_path)?;
417 let lint = validate_consumer_profile("lint", &sc_lint.lint, &config_path)?;
418 let lint_profiles = LintProfiles::parse(&sc_lint.lint_profiles, &lint)
419 .map_err(|error| profile_plan_config_error(error, &config_path))?;
420 let test = test_selectors_from_file(sc_lint.test.as_ref(), &config_path)?;
421 let root = config_path
422 .parent()
423 .ok_or_else(|| CliError::internal("consumer configuration has no parent directory"))?
424 .to_path_buf();
425
426 Ok(Self {
427 repo_root: None,
428 config_path: Some(config_path),
429 explicit_config: None,
430 logging_root: cli.log_root.clone(),
431 logging_console: cli.log_console,
432 mode: LoadedConfigMode::Consumer(ConsumerRequirement {
433 compatibility,
434 root,
435 lint,
436 lint_profiles,
437 default_lint_profile: sc_lint.default_lint_profile.clone(),
438 test,
439 }),
440 })
441 }
442
443 pub fn repo_root(&self) -> Option<&Path> {
444 self.repo_root.as_ref().map(RepoRoot::as_path)
445 }
446
447 #[expect(
448 clippy::result_large_err,
449 reason = "Commands that require a repo root must surface failures through the shared CliError contract."
450 )]
451 pub fn require_repo_root(&self) -> Result<&Path, CliError> {
452 self.repo_root
453 .as_ref()
454 .map(RepoRoot::as_path)
455 .ok_or_else(|| {
456 CliError::internal("repo root required but configuration did not resolve one")
457 })
458 }
459
460 pub fn config_path(&self) -> Option<&Path> {
461 self.config_path.as_deref()
462 }
463
464 pub(crate) fn explicit_config(&self) -> Option<&Path> {
465 self.explicit_config.as_deref()
466 }
467
468 #[expect(
469 clippy::result_large_err,
470 reason = "Boundary configuration failures are part of the stable top-level CliError contract."
471 )]
472 pub(crate) fn require_boundaries_dir(&self) -> Result<(), CliError> {
473 let root = self.require_repo_root()?;
474 if root.join("boundaries").is_dir() {
475 return Ok(());
476 }
477 Err(
478 CliError::config("the boundary family requires a `boundaries/` directory")
479 .with_code(ConfigCode::BoundariesDirMissing.as_str())
480 .with_cause(format!(
481 "no `boundaries/` directory under repo root `{}`",
482 root.display()
483 ))
484 .with_detail("repo_root", json!(root.display().to_string()))
485 .with_suggested_action("create `boundaries/` or do not run the boundary family"),
486 )
487 }
488
489 pub fn logging_root(&self) -> Option<&PathBuf> {
490 self.logging_root.as_ref()
491 }
492
493 pub const fn logging_console(&self) -> bool {
494 self.logging_console
495 }
496
497 #[expect(
498 clippy::result_large_err,
499 reason = "The compatibility check must return one stable CliError envelope for each recoverable failure."
500 )]
501 pub(crate) fn evaluate_compatibility(
502 &self,
503 binary_override: Option<&Path>,
504 ) -> Result<Value, CliError> {
505 let LoadedConfigMode::Compatibility(requirement) = &self.mode else {
506 return Err(CliError::internal(
507 "compatibility evaluation requires a compatibility configuration",
508 ));
509 };
510 crate::compatibility::evaluate_compatibility(requirement, binary_override)
511 }
512}
513
514#[derive(Debug, Clone, Default, Deserialize)]
515pub(crate) struct RepoConfigFile {
516 logging: Option<LoggingConfigFile>,
517 pub(crate) tool: Option<ToolConfigFile>,
518}
519
520#[derive(Debug, Clone, Default, Deserialize)]
521pub(crate) struct ToolConfigFile {
522 #[serde(rename = "sc-lint")]
523 pub(crate) sc_lint: Option<ScLintConfigFile>,
524}
525
526#[derive(Debug, Clone, Default, Deserialize)]
527pub(crate) struct ScLintConfigFile {
528 pub(crate) minimum_version: Option<String>,
529 default_lint_profile: Option<String>,
530 #[serde(default)]
531 lint: Vec<ConsumerProfileStepFile>,
532 #[serde(default)]
534 lint_profiles: std::collections::BTreeMap<String, Vec<String>>,
535 #[serde(default)]
537 test: Option<toml::Value>,
538}
539
540#[derive(Debug, Clone, Deserialize)]
543struct ConsumerProfileStepFile {
544 name: Option<String>,
545 command: Option<Vec<String>>,
546 platform: Option<toml::Value>,
547 host: Option<toml::Value>,
548 target: Option<toml::Value>,
549 after_all: Option<toml::Value>,
550 env: Option<toml::Value>,
551 env_paths: Option<toml::Value>,
552 cwd: Option<toml::Value>,
553 #[serde(flatten)]
554 extra: std::collections::BTreeMap<String, toml::Value>,
555}
556
557#[derive(Debug, Clone, Default, Deserialize)]
558struct LoggingConfigFile {
559 root: Option<PathBuf>,
560 console: Option<bool>,
561}
562
563fn find_repo_config(repo_root: &Path, override_path: Option<&Path>) -> Option<PathBuf> {
564 if let Some(path) = override_path {
565 return Some(resolve_repo_relative_path(repo_root, path));
566 }
567 Some(repo_root.join(CONFIG_FILENAME)).filter(|path| path.exists())
568}
569
570#[expect(
571 clippy::result_large_err,
572 reason = "Repo config parse failures are part of the stable top-level CliError contract."
573)]
574pub(crate) fn parse_repo_config(path: &Path) -> Result<RepoConfigFile, CliError> {
575 let text = fs::read_to_string(path).map_err(|error| {
576 CliError::config(format!("failed to read repo config `{}`", path.display()))
577 .with_source(error)
578 .with_detail("config_path", Value::String(path.display().to_string()))
579 .with_suggested_action("Check that the configuration path exists and is readable, then rerun with `--config <path>` if it is outside the repository default.")
580 })?;
581 let parse_error = |error: toml::de::Error| {
582 CliError::config(format!("failed to parse repo config `{}`", path.display()))
583 .with_source(error)
584 .with_detail("config_path", Value::String(path.display().to_string()))
585 };
586 let raw: toml::Table = toml::from_str(&text).map_err(parse_error)?;
587 reject_unknown_tables(path, &raw)?;
588 toml::from_str(&text).map_err(parse_error)
589}
590
591const SC_LINT_KEYS: &[&str] = &[
593 "minimum_version",
594 "lint",
595 "lint_profiles",
596 "default_lint_profile",
597 "test",
598 "analyzers",
599];
600const DECLINED_TABLES: &[&str] = &["setup", "runner"];
603
604#[expect(
611 clippy::result_large_err,
612 reason = "Repo config validation failures are part of the stable top-level CliError contract."
613)]
614fn reject_unknown_tables(path: &Path, raw: &toml::Table) -> Result<(), CliError> {
615 if let Some(key) = DECLINED_TABLES.iter().find(|key| raw.contains_key(**key)) {
616 return Err(unknown_table_error(path, key, SC_LINT_KEYS));
617 }
618 let Some(sc_lint) = raw
619 .get("tool")
620 .and_then(toml::Value::as_table)
621 .and_then(|tool| tool.get("sc-lint"))
622 .and_then(toml::Value::as_table)
623 else {
624 return Ok(());
625 };
626 match sc_lint
627 .keys()
628 .find(|key| !SC_LINT_KEYS.contains(&key.as_str()))
629 {
630 Some(key) => Err(unknown_table_error(
631 path,
632 &format!("tool.sc-lint.{key}"),
633 SC_LINT_KEYS,
634 )),
635 None => Ok(()),
636 }
637}
638
639fn unknown_table_error(path: &Path, key: &str, supported: &[&str]) -> CliError {
640 let declined = DECLINED_TABLES.contains(&key.strip_prefix("tool.sc-lint.").unwrap_or(key));
641 let (cause, action) = if declined {
642 (
643 format!(
644 "`{key}` is not supported: `setup.pre` and `runner.python` are Won't-do (ADR-020 decision 9)"
645 ),
646 "remove the table; provision tools with `sc_lint.setup_tools` and run direct manifest, shear and spell checks as `.sc-lint/venv/bin/python -m sc_lint.<module>`".to_owned(),
647 )
648 } else {
649 (
650 format!("`{key}` is not a supported sc-lint.toml key"),
651 format!(
652 "remove or rename `{key}`; supported keys here are {}",
653 supported
654 .iter()
655 .map(|name| format!("`{name}`"))
656 .collect::<Vec<_>>()
657 .join(", ")
658 ),
659 )
660 };
661 CliError::config(format!(
662 "unsupported key `{key}` in repo config `{}`",
663 path.display()
664 ))
665 .with_code(ConfigCode::UnknownTable.as_str())
666 .with_cause(cause)
667 .with_detail("config_path", Value::String(path.display().to_string()))
668 .with_detail("key", Value::String(key.to_owned()))
669 .with_suggested_action(action)
670}
671
672fn resolve_repo_relative_path(repo_root: &Path, candidate: &Path) -> PathBuf {
673 if candidate.is_absolute() {
674 candidate.to_path_buf()
675 } else {
676 repo_root.join(candidate)
677 }
678}
679
680fn resolve_current_dir_relative_path(current_dir: &Path, candidate: &Path) -> PathBuf {
681 if candidate.is_absolute() {
682 candidate.to_path_buf()
683 } else {
684 current_dir.join(candidate)
685 }
686}
687
688#[expect(
689 clippy::result_large_err,
690 reason = "Consumer configuration loading returns the shared top-level CliError contract."
691)]
692fn load_consumer_config_file(path: &Path) -> Result<RepoConfigFile, CliError> {
693 if !path.is_file() {
694 return Err(compatibility_config_error(
695 CompatibilityErrorCode::ConfigMissing,
696 format!(
697 "required sc-lint configuration `{}` was not found",
698 path.display()
699 ),
700 Some(path),
701 None,
702 ));
703 }
704 parse_repo_config(path).map_err(|error| {
705 if error.code().starts_with("config.") {
706 return error;
707 }
708 compatibility_config_error(
709 CompatibilityErrorCode::ConfigMalformed,
710 format!("failed to parse sc-lint configuration `{}`", path.display()),
711 Some(path),
712 Some(error.to_string()),
713 )
714 })
715}
716
717#[expect(
721 clippy::result_large_err,
722 reason = "Consumer profile validation returns the shared top-level CliError contract."
723)]
724fn test_selectors_from_file(
725 test: Option<&toml::Value>,
726 path: &Path,
727) -> Result<TestSelectors, CliError> {
728 let rows = match test {
729 Some(toml::Value::Table(table)) => return TestSelectors::parse_table(table, path),
730 None => Vec::new(),
731 Some(toml::Value::Array(rows)) => rows
732 .iter()
733 .map(|row| {
734 row.clone()
735 .try_into::<ConsumerProfileStepFile>()
736 .map_err(|error| {
737 consumer_profile_error(
738 path,
739 ConsumerProfile::Test.as_str(),
740 format!("failed to parse test profile row: {error}"),
741 )
742 })
743 })
744 .collect::<Result<Vec<_>, _>>()?,
745 Some(_) => {
746 return Err(consumer_profile_error(
747 path,
748 ConsumerProfile::Test.as_str(),
749 "tool.sc-lint.test must be an array of tables or a table of selectors".to_string(),
750 ));
751 }
752 };
753 let steps = validate_consumer_profile(ConsumerProfile::Test.as_str(), &rows, path)?;
754 Ok(TestSelectors::from_rows(steps, path.to_path_buf()))
755}
756
757#[expect(
758 clippy::result_large_err,
759 reason = "Consumer profile validation returns the shared top-level CliError contract."
760)]
761fn validate_consumer_profile(
762 profile: &str,
763 raw_steps: &[ConsumerProfileStepFile],
764 path: &Path,
765) -> Result<Vec<ConsumerProfileStep>, CliError> {
766 if raw_steps.is_empty() {
767 return empty_consumer_profile(profile, path);
768 }
769 let mut names = std::collections::BTreeSet::new();
770 let mut steps = Vec::with_capacity(raw_steps.len());
771 for (index, step) in raw_steps.iter().enumerate() {
772 let name = step
773 .name
774 .as_deref()
775 .filter(|name| !name.trim().is_empty())
776 .ok_or_else(|| {
777 consumer_profile_error(
778 path,
779 profile,
780 format!(
781 "consumer `{profile}` profile step {} is missing a non-empty `name`",
782 index + 1
783 ),
784 )
785 })?;
786 if !names.insert(name.to_string()) {
787 return Err(consumer_profile_error(
788 path,
789 profile,
790 format!("consumer `{profile}` profile repeats step name `{name}`"),
791 ));
792 }
793 let command = step
794 .command
795 .as_ref()
796 .filter(|command| !command.is_empty())
797 .ok_or_else(|| {
798 consumer_profile_error(
799 path,
800 profile,
801 format!(
802 "consumer `{profile}` profile step `{name}` is missing a command argv array"
803 ),
804 )
805 })?;
806 if command.iter().any(|argument| argument.is_empty()) {
807 return Err(consumer_profile_error(
808 path,
809 profile,
810 format!("consumer `{profile}` profile step `{name}` has an empty command argument"),
811 ));
812 }
813 let (platform, target) = profile_step_fields(profile, name, step, path)?;
814 let after_all = decode_after_all(step.after_all.as_ref(), name, path)?;
815 let (env, cwd) = profile_step_execution(profile, name, step, path)?;
816 let declared = ConsumerProfileStep::new(name, command.clone(), platform, target)
817 .with_after_all(after_all)
818 .with_execution(env, cwd)
819 .with_context(
820 crate::profile_host::RowContext::declared(
821 name,
822 step.host.as_ref(),
823 step.env_paths.as_ref(),
824 )
825 .map_err(|error| profile_plan_config_error(error, path))?,
826 );
827 if profile == ConsumerProfile::Lint.as_str() {
828 validate_lint_step(&declared)
829 .map_err(|error| profile_plan_config_error(error, path))?;
830 }
831 steps.push(declared);
832 }
833 Ok(steps)
834}
835
836#[expect(
837 clippy::result_large_err,
838 reason = "Empty consumer profile failures use the shared top-level CliError contract."
839)]
840fn empty_consumer_profile(
841 profile: &str,
842 path: &Path,
843) -> Result<Vec<ConsumerProfileStep>, CliError> {
844 if profile == ConsumerProfile::Lint.as_str() {
845 return Ok(Vec::new());
846 }
847 Err(consumer_profile_error(
848 path,
849 profile,
850 format!("consumer `{profile}` profile must contain at least one command"),
851 ))
852}
853
854#[expect(
855 clippy::result_large_err,
856 reason = "Profile field validation preserves structured CLI configuration errors."
857)]
858fn profile_step_execution(
859 profile: &str,
860 name: &str,
861 step: &ConsumerProfileStepFile,
862 path: &Path,
863) -> Result<(std::collections::BTreeMap<String, String>, Option<PathBuf>), CliError> {
864 if profile != ConsumerProfile::Lint.as_str() {
865 if step.env.is_some()
866 || step.env_paths.is_some()
867 || step.cwd.is_some()
868 || step.host.is_some()
869 {
870 return Err(profile_plan_config_error(
871 crate::profile_plan::ProfilePlanError::new(
872 crate::profile_plan::ProfilePlanDetailCode::UnknownStepField,
873 Some(name),
874 Some(if step.host.is_some() {
875 "host"
876 } else if step.env_paths.is_some() {
877 "env_paths"
878 } else if step.env.is_some() {
879 "env"
880 } else {
881 "cwd"
882 }),
883 format!(
884 "test step `{name}` has unknown field `{}`",
885 if step.host.is_some() {
886 "host"
887 } else if step.env_paths.is_some() {
888 "env_paths"
889 } else if step.env.is_some() {
890 "env"
891 } else {
892 "cwd"
893 }
894 ),
895 "Test profile rows accept only `name`, `command` and `after_all`.",
896 ),
897 path,
898 ));
899 }
900 return Ok((std::collections::BTreeMap::new(), None));
901 }
902 let parse_error = |error: crate::step_exec::StepExecError| {
903 let detail_code = match error.kind {
904 crate::step_exec::StepExecErrorKind::Env => {
905 crate::profile_plan::ProfilePlanDetailCode::InvalidStepEnv
906 }
907 crate::step_exec::StepExecErrorKind::DuplicateEnvKey => {
908 crate::profile_plan::ProfilePlanDetailCode::DuplicateStepEnvKey
909 }
910 crate::step_exec::StepExecErrorKind::Cwd => {
911 crate::profile_plan::ProfilePlanDetailCode::InvalidStepCwd
912 }
913 };
914 let subject = format!("lint step `{name}`");
915 crate::profile_plan::profile_plan_config_error(
916 crate::profile_plan::ProfilePlanError::new(
917 detail_code,
918 Some(name),
919 Some(&error.field),
920 error.message(&subject),
921 format!("Correct the `{}` field on lint step `{name}`.", error.field),
922 ),
923 path,
924 )
925 };
926 let (env, _) =
927 crate::step_paths::execution_env(step.env.as_ref(), step.env_paths.as_ref(), path)
928 .map_err(parse_error)?;
929 let cwd = crate::step_exec::parse_cwd(step.cwd.as_ref()).map_err(parse_error)?;
930 Ok((env, cwd))
931}
932
933#[expect(
934 clippy::result_large_err,
935 reason = "Profile field validation preserves structured CLI configuration errors."
936)]
937fn profile_step_fields(
938 profile: &str,
939 name: &str,
940 step: &ConsumerProfileStepFile,
941 path: &Path,
942) -> Result<
943 (
944 Option<crate::profile_plan::Platform>,
945 Option<crate::profile_plan::Target>,
946 ),
947 CliError,
948> {
949 match profile {
950 "lint" => decode_lint_step_fields(
951 name,
952 step.platform.as_ref(),
953 step.target.as_ref(),
954 &step.extra,
955 )
956 .map_err(|error| profile_plan_config_error(error, path)),
957 "test" => {
958 reject_test_step_fields(
959 name,
960 step.platform.as_ref(),
961 step.target.as_ref(),
962 &step.extra,
963 )
964 .map_err(|error| profile_plan_config_error(error, path))?;
965 Ok((None, None))
966 }
967 _ => unreachable!("consumer profiles are lint or test"),
968 }
969}
970
971pub(crate) fn consumer_profile_error(path: &Path, profile: &str, message: String) -> CliError {
975 let path_text = path.display().to_string();
976 CliError::config(message.clone())
977 .with_code(CompatibilityErrorCode::ConfigMalformed.as_str())
978 .with_cause(format!("{message} in {path_text}"))
979 .with_suggested_action(format!(
980 "fix the `tool.sc-lint.{profile}` selectors in {path_text} as the cause describes"
981 ))
982 .with_detail("config_path", json!(path_text))
983 .with_detail("profile", json!(profile))
984}