1use std::path::Path;
5use std::path::PathBuf;
6use std::process::ExitStatus;
7use std::str::FromStr;
8use std::time::Duration;
9
10use semver::Version;
11use serde::Deserialize;
12use serde_json::Value;
13use serde_json::json;
14
15use crate::CliError;
16use crate::config::ConfigCode;
17use crate::config::ScLintConfigFile;
18use crate::config::parse_repo_config;
19use crate::consumer_integration::BINARY_NOT_FOUND_RECOVERY;
20use crate::consumer_integration::DOCS_SETUP_REFERENCE;
21use crate::error::ErrorCode;
22use crate::installer::BACKEND_PROBE_TIMEOUT;
23use crate::installer::ProbeFailure;
24use crate::installer::run_version_command;
25
26pub(crate) const VERSION_PROBE_SCHEMA: &str = "sc-lint-version-v1";
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub(crate) enum CompatibilityErrorCode {
30 ConfigMissing,
31 ConfigMalformed,
32 BinaryNotFound,
33 BinaryExecutionFailed,
34 ProbeMalformed,
35 VersionUnparsable,
36 VersionTooOld,
37}
38
39impl ErrorCode for CompatibilityErrorCode {
40 fn as_str(&self) -> &'static str {
41 match self {
42 Self::ConfigMissing => "CLI.SC_LINT_CONFIG_MISSING",
43 Self::ConfigMalformed => "CLI.SC_LINT_CONFIG_MALFORMED",
44 Self::BinaryNotFound => "CLI.SC_LINT_BINARY_NOT_FOUND",
45 Self::BinaryExecutionFailed => "CLI.SC_LINT_BINARY_EXECUTION_FAILED",
46 Self::ProbeMalformed => "CLI.SC_LINT_VERSION_PROBE_MALFORMED",
47 Self::VersionUnparsable => "CLI.SC_LINT_VERSION_UNPARSABLE",
48 Self::VersionTooOld => "CLI.SC_LINT_VERSION_TOO_OLD",
49 }
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct MinimumVersion(Version);
59
60impl MinimumVersion {
61 pub const FIELD_PATH: &'static str = "[tool.sc-lint].minimum_version";
62
63 pub fn as_semver(&self) -> &Version {
64 &self.0
65 }
66}
67
68impl FromStr for MinimumVersion {
69 type Err = semver::Error;
70
71 fn from_str(value: &str) -> Result<Self, Self::Err> {
72 Version::parse(value).map(Self)
73 }
74}
75
76impl std::fmt::Display for MinimumVersion {
77 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 self.0.fmt(formatter)
79 }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub(crate) struct CompatibilityRequirement {
84 pub(crate) minimum_version: MinimumVersion,
85 pub(crate) config_path: PathBuf,
86}
87
88#[expect(
89 clippy::result_large_err,
90 reason = "Consumer configuration is validated before any lint or test command can begin."
91)]
92pub(crate) fn load_compatibility_requirement(
93 path: &Path,
94) -> Result<CompatibilityRequirement, CliError> {
95 if !path.is_file() {
96 return Err(compatibility_config_error(
97 CompatibilityErrorCode::ConfigMissing,
98 format!(
99 "required sc-lint configuration `{}` was not found",
100 path.display()
101 ),
102 Some(path),
103 None,
104 ));
105 }
106 let file_config = parse_repo_config(path).map_err(|error| {
107 if error.code() == ConfigCode::UnknownTable.as_str() {
108 return error;
109 }
110 compatibility_config_error(
111 CompatibilityErrorCode::ConfigMalformed,
112 format!("failed to parse sc-lint configuration `{}`", path.display()),
113 Some(path),
114 Some(error.to_string()),
115 )
116 })?;
117 let sc_lint = file_config
118 .tool
119 .as_ref()
120 .and_then(|tool| tool.sc_lint.as_ref())
121 .ok_or_else(|| missing_consumer_field(path, "[tool.sc-lint]"))?;
122 compatibility_requirement_from_file(sc_lint, path)
123}
124
125#[expect(
126 clippy::result_large_err,
127 reason = "Consumer configuration validation returns the shared top-level CliError contract."
128)]
129pub(crate) fn compatibility_requirement_from_file(
130 sc_lint: &ScLintConfigFile,
131 path: &Path,
132) -> Result<CompatibilityRequirement, CliError> {
133 let raw_minimum = sc_lint
134 .minimum_version
135 .as_ref()
136 .ok_or_else(|| missing_consumer_field(path, MinimumVersion::FIELD_PATH))?;
137 let minimum_version = MinimumVersion::from_str(raw_minimum).map_err(|error| {
138 compatibility_config_error(
139 CompatibilityErrorCode::ConfigMalformed,
140 format!(
141 "configuration `{}` has malformed `{}` value `{raw_minimum}`",
142 path.display(),
143 MinimumVersion::FIELD_PATH
144 ),
145 Some(path),
146 Some(error.to_string()),
147 )
148 })?;
149 Ok(CompatibilityRequirement {
150 minimum_version,
151 config_path: path.to_path_buf(),
152 })
153}
154
155pub(crate) fn missing_consumer_field(path: &Path, field: &str) -> CliError {
156 compatibility_config_error(
157 CompatibilityErrorCode::ConfigMalformed,
158 format!(
159 "configuration `{}` is missing required field `{field}`",
160 path.display()
161 ),
162 Some(path),
163 None,
164 )
165}
166
167pub(crate) fn compatibility_config_error(
168 code: CompatibilityErrorCode,
169 message: impl Into<String>,
170 path: Option<&Path>,
171 cause: Option<String>,
172) -> CliError {
173 let recovery = if code == CompatibilityErrorCode::ConfigMissing {
174 "Run `sc-lint init --just` to create the consumer configuration and Just integration."
175 } else if code == CompatibilityErrorCode::ConfigMalformed {
176 "Correct the reported `sc-lint.toml` configuration error, then rerun the command."
177 } else {
178 BINARY_NOT_FOUND_RECOVERY
179 };
180 let mut error = CliError::config(message)
181 .with_code(code.as_str())
182 .with_suggested_action(recovery)
183 .with_documentation(DOCS_SETUP_REFERENCE)
184 .with_detail("required_field", json!(MinimumVersion::FIELD_PATH));
185 if let Some(path) = path {
186 error = error.with_detail("config_path", json!(path.display().to_string()));
187 }
188 error = error.with_cause(cause.unwrap_or_else(|| {
189 "the canonical sc-lint compatibility requirement was absent".to_string()
190 }));
191 error
192}
193
194pub(crate) fn compatibility_runtime_error(
195 code: CompatibilityErrorCode,
196 message: impl Into<String>,
197 requirement: &CompatibilityRequirement,
198 binary: &Path,
199 observed: Option<&Version>,
200 cause: String,
201) -> CliError {
202 let mut error = CliError::backend_failure(message)
203 .with_code(code.as_str())
204 .with_cause(cause)
205 .with_suggested_action(
206 "Run `just setup` (or your repository's sc-lint installer) to install or upgrade sc-lint, then retry.",
207 )
208 .with_documentation(DOCS_SETUP_REFERENCE)
209 .with_detail("minimum_version", json!(requirement.minimum_version.to_string()))
210 .with_detail("binary_path", json!(binary.display().to_string()))
211 .with_detail("config_path", json!(requirement.config_path.display().to_string()));
212 if let Some(observed) = observed {
213 error = error.with_detail("installed_version", json!(observed.to_string()));
214 }
215 error
216}
217
218#[derive(Debug, Deserialize)]
219pub(crate) struct VersionProbeEnvelope {
220 ok: bool,
221 command: String,
222 data: Option<VersionProbeData>,
223}
224
225#[derive(Debug, Deserialize)]
226struct VersionProbeData {
227 tool: String,
228 version: String,
229 contract_schema: String,
230}
231
232#[expect(
233 clippy::result_large_err,
234 reason = "An invalid external version probe is exposed as a structured recovery error."
235)]
236pub(crate) fn validate_version_probe(
237 probe: VersionProbeEnvelope,
238 requirement: &CompatibilityRequirement,
239 binary: &Path,
240) -> Result<Version, CliError> {
241 let invalid_probe = |cause: String| {
242 compatibility_runtime_error(
243 CompatibilityErrorCode::ProbeMalformed,
244 format!(
245 "sc-lint binary `{}` emitted an unsupported version probe for required minimum `{}` from `{}`",
246 binary.display(),
247 requirement.minimum_version,
248 requirement.config_path.display()
249 ),
250 requirement,
251 binary,
252 None,
253 cause,
254 )
255 };
256 if !probe.ok || probe.command != "version" {
257 return Err(invalid_probe(
258 "the version probe envelope was not a successful `version` result".to_string(),
259 ));
260 }
261 let data = probe.data.ok_or_else(|| {
262 invalid_probe("the version probe envelope did not include data".to_string())
263 })?;
264 if data.tool != crate::consts::SERVICE_NAME || data.contract_schema != VERSION_PROBE_SCHEMA {
265 return Err(invalid_probe(
266 "the version probe contract schema or tool name was unsupported".to_string(),
267 ));
268 }
269 Version::parse(&data.version).map_err(|error| {
270 compatibility_runtime_error(
271 CompatibilityErrorCode::VersionUnparsable,
272 format!(
273 "sc-lint binary `{}` reported unparsable version `{}`; required minimum `{}` comes from `{}`",
274 binary.display(),
275 data.version,
276 requirement.minimum_version,
277 requirement.config_path.display()
278 ),
279 requirement,
280 binary,
281 None,
282 error.to_string(),
283 )
284 .with_detail("reported_version", json!(data.version))
285 })
286}
287
288#[expect(
291 clippy::result_large_err,
292 reason = "The compatibility check must return one stable CliError envelope for each recoverable failure."
293)]
294pub(crate) fn evaluate_compatibility(
295 requirement: &CompatibilityRequirement,
296 binary_override: Option<&Path>,
297) -> Result<Value, CliError> {
298 let binary = binary_override.unwrap_or_else(|| Path::new(crate::consts::SERVICE_NAME));
299 let stdout = run_version_probe(requirement, binary)?;
300 let probe = serde_json::from_slice::<VersionProbeEnvelope>(&stdout).map_err(|error| {
301 compatibility_runtime_error(
302 CompatibilityErrorCode::ProbeMalformed,
303 format!(
304 "sc-lint binary {} did not emit a valid version probe",
305 required_by(requirement, binary)
306 ),
307 requirement,
308 binary,
309 None,
310 error.to_string(),
311 )
312 })?;
313 let observed = validate_version_probe(probe, requirement, binary)?;
314 if observed < *requirement.minimum_version.as_semver() {
315 return Err(compatibility_runtime_error(
316 CompatibilityErrorCode::VersionTooOld,
317 format!(
318 "installed sc-lint version `{observed}` at `{}` does not satisfy required minimum `{}` from `{}`",
319 binary.display(),
320 requirement.minimum_version,
321 requirement.config_path.display()
322 ),
323 requirement,
324 binary,
325 Some(&observed),
326 "the installed release is below the repository minimum version".to_string(),
327 ));
328 }
329
330 Ok(json!({
331 "status": "pass",
332 "minimum_version": requirement.minimum_version.to_string(),
333 "installed_version": observed.to_string(),
334 "binary_path": binary.display().to_string(),
335 "config_path": requirement.config_path.display().to_string(),
336 }))
337}
338
339fn required_by(requirement: &CompatibilityRequirement, binary: &Path) -> String {
342 format!(
343 "`{}` required at least `{}` by `{}`",
344 binary.display(),
345 requirement.minimum_version,
346 requirement.config_path.display()
347 )
348}
349
350#[expect(
354 clippy::result_large_err,
355 reason = "The compatibility check must return one stable CliError envelope for each recoverable failure."
356)]
357fn run_version_probe(
358 requirement: &CompatibilityRequirement,
359 binary: &Path,
360) -> Result<Vec<u8>, CliError> {
361 run_version_probe_with(requirement, binary, run_version_command)
362}
363
364#[expect(
368 clippy::result_large_err,
369 reason = "The compatibility check must return one stable CliError envelope for each recoverable failure."
370)]
371fn run_version_probe_with(
372 requirement: &CompatibilityRequirement,
373 binary: &Path,
374 run: impl FnOnce(&Path, Duration) -> Result<(ExitStatus, Vec<u8>), ProbeFailure>,
375) -> Result<Vec<u8>, CliError> {
376 let (status, stdout) = run(binary, BACKEND_PROBE_TIMEOUT).map_err(|failure| {
377 let (code, verb, cause) = match failure {
378 ProbeFailure::Start(error) if error.kind() == std::io::ErrorKind::NotFound => (
379 CompatibilityErrorCode::BinaryNotFound,
380 "find",
381 error.to_string(),
382 ),
383 ProbeFailure::Start(error) => (
384 CompatibilityErrorCode::BinaryExecutionFailed,
385 "execute",
386 error.to_string(),
387 ),
388 ProbeFailure::Probe(message) => (
389 CompatibilityErrorCode::BinaryExecutionFailed,
390 "complete the version probe of",
391 message,
392 ),
393 };
394 compatibility_runtime_error(
395 code,
396 format!(
397 "could not {verb} sc-lint binary {}",
398 required_by(requirement, binary)
399 ),
400 requirement,
401 binary,
402 None,
403 cause,
404 )
405 })?;
406 if !status.success() {
407 return Err(compatibility_runtime_error(
408 CompatibilityErrorCode::BinaryExecutionFailed,
409 format!(
410 "sc-lint binary {} exited unsuccessfully",
411 required_by(requirement, binary)
412 ),
413 requirement,
414 binary,
415 None,
416 format!("process exited with status {status}"),
417 ));
418 }
419 Ok(stdout)
420}
421
422#[cfg(test)]
423mod tests {
424 use std::cell::Cell;
425 #[cfg(unix)]
426 use std::os::unix::process::ExitStatusExt;
427 #[cfg(windows)]
428 use std::os::windows::process::ExitStatusExt;
429
430 use super::*;
431
432 fn requirement() -> CompatibilityRequirement {
433 CompatibilityRequirement {
434 minimum_version: MinimumVersion::from_str("0.4.1").expect("minimum version"),
435 config_path: PathBuf::from("sc-lint.toml"),
436 }
437 }
438
439 #[cfg(unix)]
440 fn exit_status(code: i32) -> ExitStatus {
441 ExitStatus::from_raw(code << 8)
442 }
443
444 #[cfg(windows)]
445 fn exit_status(code: u32) -> ExitStatus {
446 ExitStatus::from_raw(code)
447 }
448
449 fn probe_with(
452 result: Result<(ExitStatus, Vec<u8>), ProbeFailure>,
453 ) -> (Result<Vec<u8>, CliError>, Option<Duration>) {
454 let seen = Cell::new(None);
455 let outcome = run_version_probe_with(&requirement(), Path::new("sc-lint"), |_, timeout| {
456 seen.set(Some(timeout));
457 result
458 });
459 (outcome, seen.get())
460 }
461
462 #[test]
463 fn version_probe_is_bounded_by_the_installer_probe_timeout() {
464 let (outcome, timeout) = probe_with(Ok((exit_status(0), b"{}".to_vec())));
465 assert_eq!(timeout, Some(BACKEND_PROBE_TIMEOUT));
466 assert_eq!(outcome.expect("successful probe"), b"{}");
467 }
468
469 #[test]
470 fn version_probe_timeout_is_a_binary_execution_failure() {
471 let timed_out = "backend companion `sc-lint` at `sc-lint` timed out after 15000 ms during its `--json version` probe; process-tree cleanup was attempted";
472 let (outcome, _) = probe_with(Err(ProbeFailure::Probe(timed_out.to_string())));
473 let error = outcome.expect_err("a timed-out probe fails");
474 assert_eq!(error.code(), "CLI.SC_LINT_BINARY_EXECUTION_FAILED");
475 assert_eq!(error.cause.as_deref(), Some(timed_out));
476 assert_eq!(
477 error.message,
478 "could not complete the version probe of sc-lint binary `sc-lint` required at least `0.4.1` by `sc-lint.toml`"
479 );
480 }
481
482 #[test]
483 fn version_probe_start_failures_keep_their_codes() {
484 let (missing, _) = probe_with(Err(ProbeFailure::Start(std::io::Error::from(
485 std::io::ErrorKind::NotFound,
486 ))));
487 assert_eq!(
488 missing.expect_err("missing binary").code(),
489 "CLI.SC_LINT_BINARY_NOT_FOUND"
490 );
491 let (denied, _) = probe_with(Err(ProbeFailure::Start(std::io::Error::from(
492 std::io::ErrorKind::PermissionDenied,
493 ))));
494 assert_eq!(
495 denied.expect_err("unexecutable binary").code(),
496 "CLI.SC_LINT_BINARY_EXECUTION_FAILED"
497 );
498 }
499
500 #[test]
501 fn version_probe_unsuccessful_exit_is_a_binary_execution_failure() {
502 let (outcome, _) = probe_with(Ok((exit_status(3), Vec::new())));
503 let error = outcome.expect_err("non-zero exit fails");
504 assert_eq!(error.code(), "CLI.SC_LINT_BINARY_EXECUTION_FAILED");
505 assert!(
506 error
507 .cause
508 .as_deref()
509 .is_some_and(|cause| cause.starts_with("process exited with status ")),
510 "{error:?}"
511 );
512 }
513}