use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::serde_path;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BoundaryViolation {
#[serde(serialize_with = "serde_path::serialize")]
pub from_path: PathBuf,
#[serde(serialize_with = "serde_path::serialize")]
pub to_path: PathBuf,
pub from_zone: String,
pub to_zone: String,
pub import_specifier: String,
pub line: u32,
pub col: u32,
#[serde(
default,
serialize_with = "serde_path::serialize_option",
skip_serializing_if = "Option::is_none"
)]
pub via_path: Option<PathBuf>,
#[serde(
default,
skip_serializing_if = "BoundaryViolationReason::is_disallowed_zone"
)]
pub reason: BoundaryViolationReason,
#[serde(
default,
serialize_with = "serde_path::serialize_vec",
skip_serializing_if = "Vec::is_empty"
)]
pub public_files: Vec<PathBuf>,
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum BoundaryViolationReason {
#[default]
DisallowedZone,
InternalFile,
}
const SHOWN_PUBLIC_API_PATHS: usize = 3;
impl BoundaryViolationReason {
#[must_use]
pub const fn is_disallowed_zone(&self) -> bool {
matches!(self, Self::DisallowedZone)
}
}
impl BoundaryViolation {
#[must_use]
pub fn internal_file_message(
&self,
display: &dyn Fn(&std::path::Path) -> String,
) -> Option<String> {
if self.reason != BoundaryViolationReason::InternalFile {
return None;
}
let target = display(&self.to_path);
let zone = &self.to_zone;
if self.public_files.is_empty() {
return Some(format!(
"{target} is not a public entry file of zone '{zone}', and no file of the zone \
matches its publicFiles globs"
));
}
let mut shown: Vec<String> = self
.public_files
.iter()
.take(SHOWN_PUBLIC_API_PATHS)
.map(|path| display(path))
.collect();
let hidden = self
.public_files
.len()
.saturating_sub(SHOWN_PUBLIC_API_PATHS);
if hidden > 0 {
shown.push(format!("{hidden} more"));
}
let through = if self.public_files.len() == 1 {
shown.join("")
} else {
format!("one of {}", shown.join(", "))
};
Some(format!(
"{target} is not a public entry file of zone '{zone}'; import it through {through}"
))
}
#[must_use]
pub const fn refactor_action_text(&self) -> (&'static str, &'static str) {
match self.reason {
BoundaryViolationReason::DisallowedZone => (
"Move the import through an allowed zone or restructure the dependency",
"This import crosses an architecture boundary that is not permitted by the configured rules",
),
BoundaryViolationReason::InternalFile => (
"Import the symbol through a public entry file of the target zone (public_files)",
"The target zone declares publicFiles, and the imported file is not one of its public entry files",
),
}
}
}