#![expect(
clippy::result_large_err,
reason = "ProfilePlanError carries the full structured error contract (code, detail code, step, field, cause, recovery, docs) by value."
)]
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fmt;
use std::path::Path;
use serde_json::json;
use crate::CliError;
use crate::config::CONSUMER_SELECTOR_ALL;
use crate::workflow::WINDOWS_XWIN_TARGET;
pub const PROFILE_PLAN_ERROR_CODE: &str = "CLI.SC_LINT_PROFILE_CONFIG_INVALID";
const PROFILE_DOCS_REFERENCE: &str = "sc-lint docs configuration";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProfilePlanDetailCode {
EmptyMembers,
DuplicateMember,
UnknownMember,
AmbiguousName,
UnknownStepField,
TargetRequiresPlatform,
TargetOsMismatch,
UnsupportedCommandShape,
}
impl ProfilePlanDetailCode {
pub const fn as_str(self) -> &'static str {
match self {
Self::EmptyMembers => "PROFILE.EMPTY_MEMBERS",
Self::DuplicateMember => "PROFILE.DUPLICATE_MEMBER",
Self::UnknownMember => "PROFILE.UNKNOWN_MEMBER",
Self::AmbiguousName => "PROFILE.AMBIGUOUS_NAME",
Self::UnknownStepField => "PROFILE.UNKNOWN_STEP_FIELD",
Self::TargetRequiresPlatform => "PROFILE.TARGET_REQUIRES_PLATFORM",
Self::TargetOsMismatch => "PROFILE.TARGET_OS_MISMATCH",
Self::UnsupportedCommandShape => "PROFILE.UNSUPPORTED_COMMAND_SHAPE",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfilePlanError {
pub code: &'static str,
pub detail_code: ProfilePlanDetailCode,
pub step: Option<String>,
pub field: Option<String>,
pub cause: String,
pub recovery: String,
pub docs: Option<String>,
}
impl ProfilePlanError {
fn new(
detail_code: ProfilePlanDetailCode,
step: Option<&str>,
field: Option<&str>,
cause: impl Into<String>,
recovery: impl Into<String>,
) -> Self {
Self {
code: PROFILE_PLAN_ERROR_CODE,
detail_code,
step: step.map(str::to_string),
field: field.map(str::to_string),
cause: cause.into(),
recovery: recovery.into(),
docs: Some(PROFILE_DOCS_REFERENCE.to_string()),
}
}
}
impl fmt::Display for ProfilePlanError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{} ({}): {}",
self.code,
self.detail_code.as_str(),
self.cause
)
}
}
impl std::error::Error for ProfilePlanError {}
impl From<ProfilePlanError> for CliError {
fn from(error: ProfilePlanError) -> Self {
let mut converted = Self::config(format!(
"consumer lint profile configuration is invalid: {}",
error.cause
))
.with_code(error.code)
.with_detail("detail_code", json!(error.detail_code.as_str()))
.with_cause(error.cause)
.with_suggested_action(error.recovery);
if let Some(step) = error.step {
converted = converted.with_detail("step", json!(step));
}
if let Some(field) = error.field {
converted = converted.with_detail("field", json!(field));
}
if let Some(docs) = error.docs {
converted = converted.with_documentation(docs);
}
converted
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ProfileName(String);
impl ProfileName {
pub fn parse(value: String) -> Result<Self, ProfilePlanError> {
if value.trim().is_empty() {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::AmbiguousName,
None,
Some("name"),
"a lint profile or selector name must not be empty",
"Use a non-empty step or profile name.",
));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for ProfileName {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Platform {
Linux,
MacOS,
Windows,
}
impl Platform {
pub const ALL: [Self; 3] = [Self::Linux, Self::MacOS, Self::Windows];
pub const fn host() -> Self {
if cfg!(windows) {
Self::Windows
} else if cfg!(target_os = "macos") {
Self::MacOS
} else {
Self::Linux
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Linux => "linux",
Self::MacOS => "macos",
Self::Windows => "windows",
}
}
pub fn parse(value: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|platform| platform.as_str() == value)
}
}
impl fmt::Display for Platform {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlatformScope {
Host,
All,
Named(Platform),
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Target(String);
impl Target {
pub fn parse(value: String) -> Result<Self, ProfilePlanError> {
let well_formed = value.bytes().all(|byte| {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_.-".contains(&byte)
}) && value.split('-').count() >= 2
&& value.split('-').all(|part| !part.is_empty())
&& value.starts_with(|first: char| first.is_ascii_lowercase());
if !well_formed {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::TargetOsMismatch,
None,
Some("target"),
format!("`{value}` is not a valid Rust target triple"),
"Declare a target such as `x86_64-pc-windows-msvc`.",
));
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn os(&self) -> Option<Platform> {
if self.0.contains("windows") {
Some(Platform::Windows)
} else if self.0.contains("apple-darwin") {
Some(Platform::MacOS)
} else if self.0.contains("linux") {
Some(Platform::Linux)
} else {
None
}
}
}
impl fmt::Display for Target {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CargoVerb {
Check,
Clippy,
}
impl CargoVerb {
pub fn from_argv(argv: &[String]) -> Option<Self> {
match argv {
[program, verb, ..] if program == "cargo" => match verb.as_str() {
"check" => Some(Self::Check),
"clippy" => Some(Self::Clippy),
_ => None,
},
_ => None,
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Check => "check",
Self::Clippy => "clippy",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlannedStep {
name: String,
command: OsString,
args: Vec<OsString>,
platform: Option<Platform>,
target: Option<Target>,
cargo_verb: Option<CargoVerb>,
}
impl PlannedStep {
pub fn name(&self) -> &str {
&self.name
}
pub fn command(&self) -> &OsString {
&self.command
}
pub fn args(&self) -> &[OsString] {
&self.args
}
pub const fn platform(&self) -> Option<Platform> {
self.platform
}
pub const fn target(&self) -> Option<&Target> {
self.target.as_ref()
}
#[cfg_attr(
not(test),
expect(
dead_code,
reason = "Planner API accessor; production execution consumes the already-adapted argv."
)
)]
pub const fn cargo_verb(&self) -> Option<CargoVerb> {
self.cargo_verb
}
pub fn uses_cargo_xwin(&self) -> bool {
self.command == "cargo" && self.args.first().is_some_and(|arg| arg == "xwin")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkipReason {
UnsupportedCrossCommand,
UnsupportedCrossTarget,
}
impl SkipReason {
pub const fn as_str(self) -> &'static str {
match self {
Self::UnsupportedCrossCommand => "unsupported_cross_command",
Self::UnsupportedCrossTarget => "unsupported_cross_target",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkipRecord {
pub name: String,
pub host: Platform,
pub platform: Platform,
pub target: Option<Target>,
pub reason: SkipReason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlanDecision {
Run(PlannedStep),
Skip(SkipRecord),
}
fn invalid_shape(step: &str, cause: String, recovery: &str) -> ProfilePlanError {
ProfilePlanError::new(
ProfilePlanDetailCode::UnsupportedCommandShape,
Some(step),
Some("command"),
cause,
recovery,
)
}
fn embeds_target(argv: &[String]) -> bool {
argv.iter()
.any(|argument| argument == "--target" || argument.starts_with("--target="))
}
pub(crate) fn validate_lint_step(step: &ConsumerProfileStep) -> Result<(), ProfilePlanError> {
let Some(target) = step.target() else {
return Ok(());
};
let name = step.name();
let Some(platform) = step.platform() else {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::TargetRequiresPlatform,
Some(name),
Some("target"),
format!("step `{name}` declares target `{target}` without a `platform`"),
"Add `platform = \"linux\" | \"macos\" | \"windows\"` matching the target.",
));
};
if target.os() != Some(platform) {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::TargetOsMismatch,
Some(name),
Some("target"),
format!("step `{name}` target `{target}` does not name a {platform} target"),
"Use a target triple whose OS matches `platform`.",
));
}
if CargoVerb::from_argv(step.command()).is_none() {
return Err(invalid_shape(
name,
format!(
"step `{name}` declares a target but its command is not a literal `cargo check` or `cargo clippy`"
),
"Targets apply only to `[\"cargo\", \"check\"|\"clippy\", ...]`; remove the target or use that command.",
));
}
if embeds_target(step.command()) {
return Err(invalid_shape(
name,
format!("step `{name}` command already contains `--target`"),
"Remove `--target` from the command; the `target` field supplies it.",
));
}
Ok(())
}
pub(crate) fn decode_lint_step_fields(
step: &str,
platform: Option<&toml::Value>,
target: Option<&toml::Value>,
extra_keys: &BTreeMap<String, toml::Value>,
) -> Result<(Option<Platform>, Option<Target>), ProfilePlanError> {
if let Some(key) = extra_keys.keys().next() {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::UnknownStepField,
Some(step),
Some(key),
format!("lint step `{step}` has unknown field `{key}`"),
"Lint steps accept only `name`, `command`, `platform` and `target`.",
));
}
let platform = platform
.map(|value| {
value.as_str().and_then(Platform::parse).ok_or_else(|| {
ProfilePlanError::new(
ProfilePlanDetailCode::UnknownStepField,
Some(step),
Some("platform"),
format!("lint step `{step}` has an unsupported `platform` value `{value}`"),
"Use `platform = \"linux\"`, `\"macos\"` or `\"windows\"`.",
)
})
})
.transpose()?;
let target = target
.map(|value| {
let text = value.as_str().map(str::to_string).ok_or_else(|| {
ProfilePlanError::new(
ProfilePlanDetailCode::TargetOsMismatch,
Some(step),
Some("target"),
format!("lint step `{step}` has a non-string `target` value `{value}`"),
"Declare the target as a triple string such as `x86_64-pc-windows-msvc`.",
)
})?;
Target::parse(text).map_err(|mut error| {
error.step = Some(step.to_string());
error
})
})
.transpose()?;
Ok((platform, target))
}
pub(crate) fn reject_test_step_fields(
step: &str,
platform: Option<&toml::Value>,
target: Option<&toml::Value>,
extra_keys: &BTreeMap<String, toml::Value>,
) -> Result<(), ProfilePlanError> {
let field = platform
.is_some()
.then_some("platform")
.or_else(|| target.is_some().then_some("target"))
.or_else(|| extra_keys.keys().next().map(String::as_str));
let Some(field) = field else {
return Ok(());
};
Err(ProfilePlanError::new(
ProfilePlanDetailCode::UnknownStepField,
Some(step),
Some(field),
format!("test step `{step}` has unsupported field `{field}`"),
"Test steps accept only `name` and `command`; move platform selection to a lint step.",
))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct LintProfiles(BTreeMap<ProfileName, Vec<String>>);
impl LintProfiles {
pub(crate) fn parse(
raw: &BTreeMap<String, Vec<String>>,
steps: &[ConsumerProfileStep],
) -> Result<Self, ProfilePlanError> {
let declared: BTreeSet<&str> = steps.iter().map(ConsumerProfileStep::name).collect();
let mut profiles = BTreeMap::new();
for (raw_name, members) in raw {
let name = ProfileName::parse(raw_name.clone())?;
validate_profile_name(&name, &declared)?;
validate_members(&name, members, &declared)?;
profiles.insert(name, members.clone());
}
Ok(Self(profiles))
}
pub(crate) fn names(&self) -> Vec<&str> {
self.0.keys().map(ProfileName::as_str).collect()
}
pub(crate) fn resolve(
&self,
name: &str,
steps: &[ConsumerProfileStep],
) -> Option<Vec<ConsumerProfileStep>> {
let members = self.0.iter().find(|(key, _)| key.as_str() == name)?.1;
Some(
members
.iter()
.filter_map(|member| steps.iter().find(|step| step.name() == member))
.cloned()
.collect(),
)
}
}
fn validate_profile_name(
name: &ProfileName,
declared: &BTreeSet<&str>,
) -> Result<(), ProfilePlanError> {
if name.as_str() == CONSUMER_SELECTOR_ALL || declared.contains(name.as_str()) {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::AmbiguousName,
Some(name.as_str()),
Some("lint_profiles"),
format!(
"profile `{name}` collides with {}",
if name.as_str() == CONSUMER_SELECTOR_ALL {
"the reserved selector `all`"
} else {
"a lint step of the same name"
}
),
"Rename the profile so it differs from `all` and from every step name.",
));
}
Ok(())
}
fn validate_members(
name: &ProfileName,
members: &[String],
declared: &BTreeSet<&str>,
) -> Result<(), ProfilePlanError> {
if members.is_empty() {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::EmptyMembers,
Some(name.as_str()),
Some("lint_profiles"),
format!("profile `{name}` lists no steps"),
"List at least one declared lint step name.",
));
}
let mut seen = BTreeSet::new();
for member in members {
if !declared.contains(member.as_str()) {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::UnknownMember,
Some(name.as_str()),
Some(member),
format!("profile `{name}` lists `{member}`, which is not a declared lint step"),
"List only names declared by `[[tool.sc-lint.lint]]` rows.",
));
}
if !seen.insert(member.as_str()) {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::DuplicateMember,
Some(name.as_str()),
Some(member),
format!("profile `{name}` lists `{member}` more than once"),
"List each step at most once per profile.",
));
}
}
Ok(())
}
pub fn plan_consumer_lint(
steps: &[ConsumerProfileStep],
selector: Option<&ProfileName>,
scope: PlatformScope,
host: Platform,
) -> Result<Vec<PlanDecision>, ProfilePlanError> {
let members = select_members(steps, selector)?;
let mut decisions = Vec::with_capacity(members.len());
for step in members {
validate_lint_step(step)?;
if scope_selects(step.platform(), scope, host) {
decisions.push(decide(step, host)?);
}
}
Ok(decisions)
}
fn select_members<'a>(
steps: &'a [ConsumerProfileStep],
selector: Option<&ProfileName>,
) -> Result<Vec<&'a ConsumerProfileStep>, ProfilePlanError> {
let mut seen = BTreeSet::new();
for step in steps {
if !seen.insert(step.name()) {
return Err(ProfilePlanError::new(
ProfilePlanDetailCode::DuplicateMember,
Some(step.name()),
Some("name"),
format!("step `{}` is declared more than once", step.name()),
"Give every lint step a unique name.",
));
}
}
let Some(name) = selector.filter(|name| name.as_str() != CONSUMER_SELECTOR_ALL) else {
return Ok(steps.iter().collect());
};
steps
.iter()
.find(|step| step.name() == name.as_str())
.map(|step| vec![step])
.ok_or_else(|| {
ProfilePlanError::new(
ProfilePlanDetailCode::UnknownMember,
Some(name.as_str()),
Some("selector"),
format!("selector `{name}` names no declared lint step"),
format!("Select `{CONSUMER_SELECTOR_ALL}` or one of the declared step names."),
)
})
}
fn scope_selects(platform: Option<Platform>, scope: PlatformScope, host: Platform) -> bool {
match (platform, scope) {
(None, _) | (_, PlatformScope::All) => true,
(Some(tag), PlatformScope::Host) => tag == host,
(Some(tag), PlatformScope::Named(named)) => tag == host || tag == named,
}
}
fn decide(step: &ConsumerProfileStep, host: Platform) -> Result<PlanDecision, ProfilePlanError> {
let Some(platform) = step.platform() else {
return Ok(PlanDecision::Run(planned(step, None, false)?));
};
let skip = |reason| {
PlanDecision::Skip(SkipRecord {
name: step.name().to_string(),
host,
platform,
target: step.target().cloned(),
reason,
})
};
match step.target() {
None if platform == host => Ok(PlanDecision::Run(planned(step, None, false)?)),
None => Ok(skip(SkipReason::UnsupportedCrossCommand)),
Some(_) if platform == host => Ok(PlanDecision::Run(planned(step, step.target(), false)?)),
Some(target) if uses_xwin(platform, target, host) => {
Ok(PlanDecision::Run(planned(step, Some(target), true)?))
}
Some(_) => Ok(skip(SkipReason::UnsupportedCrossTarget)),
}
}
fn uses_xwin(platform: Platform, target: &Target, host: Platform) -> bool {
platform == Platform::Windows
&& matches!(host, Platform::Linux | Platform::MacOS)
&& target.as_str() == WINDOWS_XWIN_TARGET
}
fn planned(
step: &ConsumerProfileStep,
target: Option<&Target>,
xwin: bool,
) -> Result<PlannedStep, ProfilePlanError> {
let (command, args) = match target {
Some(target) => targeted_argv(step, target, xwin)?,
None => {
let (program, rest) = step.command().split_first().ok_or_else(|| {
invalid_shape(
step.name(),
format!("step `{}` has an empty command", step.name()),
"Give the step a non-empty argv array.",
)
})?;
(
OsString::from(program),
rest.iter().map(OsString::from).collect(),
)
}
};
Ok(PlannedStep {
name: step.name().to_string(),
command,
args,
platform: step.platform(),
target: step.target().cloned(),
cargo_verb: CargoVerb::from_argv(step.command()),
})
}
fn targeted_argv(
step: &ConsumerProfileStep,
target: &Target,
xwin: bool,
) -> Result<(OsString, Vec<OsString>), ProfilePlanError> {
let (Some(verb), Some(tail)) = (
CargoVerb::from_argv(step.command()),
step.command().get(2..),
) else {
return Err(invalid_shape(
step.name(),
format!(
"step `{}` has no literal cargo check/clippy verb",
step.name()
),
"Use a literal `cargo check` or `cargo clippy` command.",
));
};
let separator = tail
.iter()
.position(|argument| argument == "--")
.unwrap_or(tail.len());
let mut args: Vec<OsString> = Vec::with_capacity(tail.len() + 3);
if xwin {
args.push("xwin".into());
}
args.push(verb.as_str().into());
args.extend(tail[..separator].iter().map(OsString::from));
args.push("--target".into());
args.push(target.as_str().into());
args.extend(tail[separator..].iter().map(OsString::from));
Ok(("cargo".into(), args))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ConsumerProfileStep {
name: String,
command: Vec<String>,
platform: Option<Platform>,
target: Option<Target>,
}
impl ConsumerProfileStep {
pub(crate) fn new(
name: impl Into<String>,
command: Vec<String>,
platform: Option<Platform>,
target: Option<Target>,
) -> Self {
Self {
name: name.into(),
command,
platform,
target,
}
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn command(&self) -> &[String] {
&self.command
}
pub(crate) const fn platform(&self) -> Option<Platform> {
self.platform
}
pub(crate) const fn target(&self) -> Option<&Target> {
self.target.as_ref()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LintPlanInput<'a> {
pub(crate) root: &'a Path,
pub(crate) steps: Vec<ConsumerProfileStep>,
pub(crate) selector: Option<ProfileName>,
}
pub(crate) fn profile_plan_config_error(error: ProfilePlanError, path: &Path) -> CliError {
CliError::from(error).with_detail("config_path", json!(path.display().to_string()))
}