use super::*;
use serde_json::Value;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Constitution {
name: String,
boundaries: Vec<Boundary>,
}
impl Constitution {
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
boundaries: Vec::new(),
}
}
pub fn boundary(mut self, boundary: impl Into<Boundary>) -> Self {
self.boundaries.push(boundary.into());
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn boundaries(&self) -> &[Boundary] {
&self.boundaries
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DependencyKind {
#[default]
Normal,
Dev,
Build,
}
impl DependencyKind {
pub(crate) fn finding_suffix(&self) -> &'static str {
match self {
DependencyKind::Normal => "",
DependencyKind::Dev => " (dev)",
DependencyKind::Build => " (build)",
}
}
pub(crate) fn key_label(&self) -> &'static str {
match self {
DependencyKind::Normal => "normal",
DependencyKind::Dev => "dev",
DependencyKind::Build => "build",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceKind {
Registry,
Git,
Path,
}
impl SourceKind {
pub(crate) fn label(&self) -> &'static str {
match self {
SourceKind::Registry => "registry",
SourceKind::Git => "git",
SourceKind::Path => "path",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Boundary {
Crate(CrateBoundary),
Module(ModuleBoundary),
}
impl From<CrateBoundary> for Boundary {
fn from(boundary: CrateBoundary) -> Self {
Boundary::Crate(boundary)
}
}
impl From<ModuleBoundary> for Boundary {
fn from(boundary: ModuleBoundary) -> Self {
Boundary::Module(boundary)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrateBoundary {
pub(crate) target: CrateTarget,
pub(crate) rule: Rule,
pub(crate) reason: String,
pub(crate) severity: Severity,
pub(crate) kind: DependencyKind,
pub(crate) anchor: Option<String>,
}
impl CrateBoundary {
pub fn crate_(package: &str) -> CrateBoundaryBuilder {
CrateBoundaryBuilder {
target: CrateTarget {
package: package.to_string(),
},
}
}
pub fn target(&self) -> &CrateTarget {
&self.target
}
pub fn rule(&self) -> &Rule {
&self.rule
}
pub fn reason(&self) -> &str {
&self.reason
}
pub fn severity(&self) -> Severity {
self.severity
}
pub fn dependency_kind(&self) -> DependencyKind {
self.kind
}
pub fn with_anchor(mut self, anchor: &str) -> Self {
self.anchor = Some(anchor.to_string());
self
}
pub fn anchor(&self) -> Option<&str> {
self.anchor.as_deref()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrateTarget {
pub package: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Rule {
#[non_exhaustive]
DenyExternalDependencies {
allowed: Vec<String>,
},
#[non_exhaustive]
ForbidDependencyOn {
crates: Vec<String>,
},
#[non_exhaustive]
RestrictDependenciesTo {
allowed: Vec<String>,
},
#[non_exhaustive]
RestrictWorkspaceDependenciesTo {
allowed: Vec<String>,
},
#[non_exhaustive]
RestrictDependencySourcesTo {
allowed: Vec<SourceKind>,
},
#[non_exhaustive]
RestrictFeaturesOf {
crate_: String,
allowed: Vec<String>,
},
#[non_exhaustive]
ForbidFeaturesOf {
crate_: String,
forbidden: Vec<String>,
},
}
impl Rule {
pub(crate) fn label(&self) -> &'static str {
match self {
Rule::DenyExternalDependencies { .. } => "deny external dependencies",
Rule::ForbidDependencyOn { .. } => "forbid dependency on",
Rule::RestrictDependenciesTo { .. } => "restrict dependencies to",
Rule::RestrictWorkspaceDependenciesTo { .. } => "restrict workspace dependencies to",
Rule::RestrictDependencySourcesTo { .. } => "restrict dependency sources to",
Rule::RestrictFeaturesOf { .. } => "restrict features of",
Rule::ForbidFeaturesOf { .. } => "forbid features of",
}
}
pub(crate) fn polarity(&self) -> Polarity {
match self {
Rule::ForbidDependencyOn { .. } | Rule::ForbidFeaturesOf { .. } => Polarity::DenyBreach,
Rule::DenyExternalDependencies { .. }
| Rule::RestrictDependenciesTo { .. }
| Rule::RestrictWorkspaceDependenciesTo { .. }
| Rule::RestrictDependencySourcesTo { .. }
| Rule::RestrictFeaturesOf { .. } => Polarity::AllowlistGap,
}
}
pub(crate) fn text(&self) -> String {
match self {
Rule::DenyExternalDependencies { allowed } if allowed.is_empty() => {
"deny external dependencies".to_string()
}
Rule::DenyExternalDependencies { allowed } => {
format!("deny external dependencies (allow: {})", allowed.join(", "))
}
Rule::ForbidDependencyOn { crates } => {
format!("forbid dependency on: {}", crates.join(", "))
}
Rule::RestrictDependenciesTo { allowed } if allowed.is_empty() => {
"restrict dependencies to nothing".to_string()
}
Rule::RestrictDependenciesTo { allowed } => {
format!("restrict dependencies to: {}", allowed.join(", "))
}
Rule::RestrictWorkspaceDependenciesTo { allowed } if allowed.is_empty() => {
"forbid all workspace dependencies".to_string()
}
Rule::RestrictWorkspaceDependenciesTo { allowed } => {
format!("restrict workspace dependencies to: {}", allowed.join(", "))
}
Rule::RestrictDependencySourcesTo { allowed } if allowed.is_empty() => {
"forbid all dependencies (by source)".to_string()
}
Rule::RestrictDependencySourcesTo { allowed } => {
format!(
"restrict dependency sources to: {}",
allowed
.iter()
.map(SourceKind::label)
.collect::<Vec<_>>()
.join(", ")
)
}
Rule::RestrictFeaturesOf { crate_, allowed } if allowed.is_empty() => {
format!("restrict features of {crate_} to nothing")
}
Rule::RestrictFeaturesOf { crate_, allowed } => {
format!("restrict features of {crate_} to: {}", allowed.join(", "))
}
Rule::ForbidFeaturesOf { crate_, forbidden } if forbidden.is_empty() => {
format!("forbid no features of {crate_}")
}
Rule::ForbidFeaturesOf { crate_, forbidden } => {
format!("forbid features of {crate_}: {}", forbidden.join(", "))
}
}
}
pub(crate) fn json_params(&self) -> Vec<(&'static str, Value)> {
match self {
Rule::DenyExternalDependencies { allowed } if allowed.is_empty() => Vec::new(),
Rule::DenyExternalDependencies { allowed } => {
vec![("allowed", serde_json::json!(allowed))]
}
Rule::ForbidDependencyOn { crates } => vec![("crates", serde_json::json!(crates))],
Rule::RestrictDependenciesTo { allowed } => vec![("only", serde_json::json!(allowed))],
Rule::RestrictWorkspaceDependenciesTo { allowed } => {
vec![("only_workspace", serde_json::json!(allowed))]
}
Rule::RestrictDependencySourcesTo { allowed } => {
let sources: Vec<&str> = allowed.iter().map(SourceKind::label).collect();
vec![("allowed_sources", serde_json::json!(sources))]
}
Rule::RestrictFeaturesOf { crate_, allowed } => vec![
("crate", serde_json::json!(crate_)),
("only_features", serde_json::json!(allowed)),
],
Rule::ForbidFeaturesOf { crate_, forbidden } => vec![
("crate", serde_json::json!(crate_)),
("forbidden_features", serde_json::json!(forbidden)),
],
}
}
#[cfg(test)]
pub(crate) fn findings(
&self,
package: &Value,
workspace_members: &[String],
kind: DependencyKind,
) -> Vec<String> {
self.facts(package, workspace_members, kind)
.into_iter()
.map(|fact| fact.into_finding().text().to_string())
.collect()
}
pub(crate) fn facts(
&self,
package: &Value,
workspace_members: &[String],
kind: DependencyKind,
) -> Vec<crate::finding::CrateFact> {
let dependencies: Vec<String> = match self {
Rule::DenyExternalDependencies { allowed } => external_dependencies(package, kind)
.into_iter()
.filter(|dependency| !allowed.contains(dependency))
.collect(),
Rule::ForbidDependencyOn { crates } => dependencies(package, kind)
.into_iter()
.filter(|dependency| crates.contains(dependency))
.collect(),
Rule::RestrictDependenciesTo { allowed } => dependencies(package, kind)
.into_iter()
.filter(|dependency| !allowed.contains(dependency))
.collect(),
Rule::RestrictWorkspaceDependenciesTo { allowed } => dependencies(package, kind)
.into_iter()
.filter(|dependency| {
workspace_members.contains(dependency) && !allowed.contains(dependency)
})
.collect(),
Rule::RestrictDependencySourcesTo { allowed } => {
dependencies_with_disallowed_source(package, kind, allowed)
}
Rule::RestrictFeaturesOf { crate_, allowed } => {
return declared_features(package, crate_, kind)
.into_iter()
.filter(|feature| !allowed.contains(feature))
.map(|feature| {
crate::finding::CrateFact::feature(crate_.clone(), feature, kind)
})
.collect();
}
Rule::ForbidFeaturesOf { crate_, forbidden } => {
return declared_features(package, crate_, kind)
.into_iter()
.filter(|feature| forbidden.contains(feature))
.map(|feature| {
crate::finding::CrateFact::feature(crate_.clone(), feature, kind)
})
.collect();
}
};
dependencies
.into_iter()
.map(|dependency| crate::finding::CrateFact::dependency(dependency, kind))
.collect()
}
}
pub struct CrateBoundaryBuilder {
target: CrateTarget,
}
impl CrateBoundaryBuilder {
pub fn deny_external_dependencies(self) -> DenyExternalDraft {
DenyExternalDraft {
target: self.target,
allowed: Vec::new(),
severity: Severity::Enforce,
kind: DependencyKind::Normal,
}
}
pub fn forbid_dependency_on<I, S>(self, crates: I) -> CrateBoundaryDraft
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
CrateBoundaryDraft {
target: self.target,
rule: Rule::ForbidDependencyOn {
crates: crates.into_iter().map(Into::into).collect(),
},
severity: Severity::Enforce,
kind: DependencyKind::Normal,
}
}
pub fn restrict_dependencies_to<I, S>(self, allowed: I) -> CrateBoundaryDraft
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
CrateBoundaryDraft {
target: self.target,
rule: Rule::RestrictDependenciesTo {
allowed: allowed.into_iter().map(Into::into).collect(),
},
severity: Severity::Enforce,
kind: DependencyKind::Normal,
}
}
pub fn restrict_workspace_dependencies_to<I, S>(self, allowed: I) -> CrateBoundaryDraft
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
CrateBoundaryDraft {
target: self.target,
rule: Rule::RestrictWorkspaceDependenciesTo {
allowed: allowed.into_iter().map(Into::into).collect(),
},
severity: Severity::Enforce,
kind: DependencyKind::Normal,
}
}
pub fn forbid_all_workspace_dependencies(self) -> CrateBoundaryDraft {
self.restrict_workspace_dependencies_to(Vec::<String>::new())
}
pub fn restrict_dependency_sources_to<I>(self, allowed: I) -> CrateBoundaryDraft
where
I: IntoIterator<Item = SourceKind>,
{
CrateBoundaryDraft {
target: self.target,
rule: Rule::RestrictDependencySourcesTo {
allowed: allowed.into_iter().collect(),
},
severity: Severity::Enforce,
kind: DependencyKind::Normal,
}
}
pub fn restrict_features_of<C, I, S>(self, crate_: C, allowed: I) -> CrateBoundaryDraft
where
C: Into<String>,
I: IntoIterator<Item = S>,
S: Into<String>,
{
CrateBoundaryDraft {
target: self.target,
rule: Rule::RestrictFeaturesOf {
crate_: crate_.into(),
allowed: allowed.into_iter().map(Into::into).collect(),
},
severity: Severity::Enforce,
kind: DependencyKind::Normal,
}
}
pub fn forbid_features_of<C, I, S>(self, crate_: C, forbidden: I) -> CrateBoundaryDraft
where
C: Into<String>,
I: IntoIterator<Item = S>,
S: Into<String>,
{
CrateBoundaryDraft {
target: self.target,
rule: Rule::ForbidFeaturesOf {
crate_: crate_.into(),
forbidden: forbidden.into_iter().map(Into::into).collect(),
},
severity: Severity::Enforce,
kind: DependencyKind::Normal,
}
}
pub fn forbid_feature<C, S>(self, crate_: C, feature: S) -> CrateBoundaryDraft
where
C: Into<String>,
S: Into<String>,
{
self.forbid_features_of(crate_, [feature])
}
}
pub struct DenyExternalDraft {
target: CrateTarget,
allowed: Vec<String>,
severity: Severity,
kind: DependencyKind,
}
impl DenyExternalDraft {
pub fn allow_external<I, S>(mut self, crates: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.allowed.extend(crates.into_iter().map(Into::into));
self
}
pub fn warn(mut self) -> Self {
self.severity = Severity::Warn;
self
}
pub fn dependency_kind(mut self, kind: DependencyKind) -> Self {
self.kind = kind;
self
}
pub fn because(self, reason: &str) -> CrateBoundary {
CrateBoundary {
target: self.target,
rule: Rule::DenyExternalDependencies {
allowed: self.allowed,
},
reason: reason.to_string(),
severity: self.severity,
kind: self.kind,
anchor: None,
}
}
}
pub struct CrateBoundaryDraft {
target: CrateTarget,
rule: Rule,
severity: Severity,
kind: DependencyKind,
}
impl CrateBoundaryDraft {
pub fn warn(mut self) -> Self {
self.severity = Severity::Warn;
self
}
pub fn dependency_kind(mut self, kind: DependencyKind) -> Self {
self.kind = kind;
self
}
pub fn because(self, reason: &str) -> CrateBoundary {
CrateBoundary {
target: self.target,
rule: self.rule,
reason: reason.to_string(),
severity: self.severity,
kind: self.kind,
anchor: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleBoundary {
pub(crate) crate_package: String,
pub(crate) module: String,
pub(crate) rule: ModuleRule,
pub(crate) reason: String,
pub(crate) severity: Severity,
pub(crate) anchor: Option<String>,
}
impl ModuleBoundary {
pub fn in_crate(package: &str) -> ModuleBoundaryBuilder {
ModuleBoundaryBuilder {
crate_package: package.to_string(),
}
}
pub fn with_anchor(mut self, anchor: &str) -> Self {
self.anchor = Some(anchor.to_string());
self
}
pub fn anchor(&self) -> Option<&str> {
self.anchor.as_deref()
}
pub fn rule(&self) -> &ModuleRule {
&self.rule
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ModuleRule {
#[non_exhaustive]
MustNotImport {
module: String,
},
#[non_exhaustive]
RestrictImportsTo {
allowed: Vec<String>,
},
#[non_exhaustive]
MustNotBeImportedBy {
importer: String,
},
#[non_exhaustive]
MustOnlyBeImportedBy {
allowed: Vec<String>,
},
#[non_exhaustive]
ConfineExternalCrate {
crate_name: String,
},
#[non_exhaustive]
ConfineInlineSymbolPath {
prefix: String,
ending_with: Option<Vec<String>>,
strict: bool,
strict_external: bool,
},
}
fn inline_confinement_text(
prefix: &str,
ending_with: &Option<Vec<String>>,
strict: bool,
) -> String {
match (ending_with, strict) {
(_, true) => format!("must not name inline under {prefix} (strict: mentions too)"),
(Some(verbs), false) => format!(
"must not call inline under {prefix} ending with: {}",
verbs.join(", ")
),
(None, false) => format!("must not call inline under {prefix}"),
}
}
fn inline_confinement_json(
prefix: &str,
ending_with: &Option<Vec<String>>,
strict: bool,
external: bool,
) -> Vec<(&'static str, Value)> {
let mut params = vec![("confined_prefix", serde_json::json!(prefix))];
if let Some(verbs) = ending_with {
params.push(("ending_with", serde_json::json!(verbs)));
}
if strict {
params.push(("strict", serde_json::json!(true)));
}
if external {
params.push(("strict_external", serde_json::json!(true)));
}
params
}
impl ModuleRule {
pub(crate) fn label(&self) -> &'static str {
match self {
ModuleRule::MustNotImport { .. } => "module must not import",
ModuleRule::RestrictImportsTo { .. } => "restrict imports to",
ModuleRule::MustNotBeImportedBy { .. } => "module must not be imported by",
ModuleRule::MustOnlyBeImportedBy { .. } => "module may only be imported by",
ModuleRule::ConfineExternalCrate { .. } => "external crate confined to module",
ModuleRule::ConfineInlineSymbolPath { .. } => "inline symbol path confined to module",
}
}
pub(crate) fn inline_payload(&self) -> Option<(&str, Option<&[String]>, bool, bool)> {
match self {
ModuleRule::ConfineInlineSymbolPath {
prefix,
ending_with,
strict,
strict_external,
} => Some((prefix, ending_with.as_deref(), *strict, *strict_external)),
_ => None,
}
}
pub(crate) fn polarity(&self) -> Polarity {
match self {
ModuleRule::MustNotImport { .. } | ModuleRule::MustNotBeImportedBy { .. } => {
Polarity::DenyBreach
}
ModuleRule::RestrictImportsTo { .. }
| ModuleRule::MustOnlyBeImportedBy { .. }
| ModuleRule::ConfineExternalCrate { .. } => Polarity::AllowlistGap,
ModuleRule::ConfineInlineSymbolPath { .. } => Polarity::DenyBreach,
}
}
pub(crate) fn text(&self) -> String {
match self {
ModuleRule::MustNotImport { module } => format!("must not import {module}"),
ModuleRule::RestrictImportsTo { allowed } if allowed.is_empty() => {
"restrict imports to nothing".to_string()
}
ModuleRule::RestrictImportsTo { allowed } => {
format!("restrict imports to: {}", allowed.join(", "))
}
ModuleRule::MustNotBeImportedBy { importer } => {
format!("must not be imported by {importer}")
}
ModuleRule::MustOnlyBeImportedBy { allowed } if allowed.is_empty() => {
"may only be imported by nothing".to_string()
}
ModuleRule::MustOnlyBeImportedBy { allowed } => {
format!("may only be imported by: {}", allowed.join(", "))
}
ModuleRule::ConfineExternalCrate { crate_name } => {
format!("confines external crate {crate_name} to this module's subtree")
}
ModuleRule::ConfineInlineSymbolPath {
prefix,
ending_with,
strict,
strict_external,
} => {
let text = inline_confinement_text(prefix, ending_with, *strict);
if *strict_external {
format!("{text} (strict-external)")
} else {
text
}
}
}
}
pub(crate) fn json_params(&self) -> Vec<(&'static str, Value)> {
match self {
ModuleRule::MustNotImport { module } => {
vec![("forbidden", serde_json::json!(module))]
}
ModuleRule::RestrictImportsTo { allowed } => {
vec![("only", serde_json::json!(allowed))]
}
ModuleRule::MustNotBeImportedBy { importer } => {
vec![("importer", serde_json::json!(importer))]
}
ModuleRule::MustOnlyBeImportedBy { allowed } => {
vec![("only_importers", serde_json::json!(allowed))]
}
ModuleRule::ConfineExternalCrate { crate_name } => {
vec![("external_crate", serde_json::json!(crate_name))]
}
ModuleRule::ConfineInlineSymbolPath {
prefix,
ending_with,
strict,
strict_external,
} => inline_confinement_json(prefix, ending_with, *strict, *strict_external),
}
}
}
pub struct ModuleBoundaryBuilder {
crate_package: String,
}
impl ModuleBoundaryBuilder {
pub fn module(self, module: &str) -> ModuleTargetDraft {
ModuleTargetDraft {
crate_package: self.crate_package,
module: module.to_string(),
}
}
}
pub struct ModuleTargetDraft {
crate_package: String,
module: String,
}
impl ModuleTargetDraft {
pub fn must_not_import(self, module: &str) -> ModuleBoundaryDraft {
self.with_rule(ModuleRule::MustNotImport {
module: module.to_string(),
})
}
pub fn restrict_imports_to<I, S>(self, allowed: I) -> ModuleBoundaryDraft
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.with_rule(ModuleRule::RestrictImportsTo {
allowed: allowed.into_iter().map(Into::into).collect(),
})
}
pub fn must_not_be_imported_by(self, importer: &str) -> ModuleBoundaryDraft {
self.with_rule(ModuleRule::MustNotBeImportedBy {
importer: importer.to_string(),
})
}
pub fn must_only_be_imported_by<I, S>(self, allowed: I) -> ModuleBoundaryDraft
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.with_rule(ModuleRule::MustOnlyBeImportedBy {
allowed: allowed.into_iter().map(Into::into).collect(),
})
}
pub fn confine_external_crate(self, crate_name: &str) -> ModuleBoundaryDraft {
self.with_rule(ModuleRule::ConfineExternalCrate {
crate_name: crate_name.to_string(),
})
}
pub fn must_not_call_inline(self, prefix: &str) -> InlineConfinementDraft {
InlineConfinementDraft {
crate_package: self.crate_package,
module: self.module,
prefix: prefix.to_string(),
ending_with: None,
strict: false,
external: false,
severity: Severity::Enforce,
}
}
fn with_rule(self, rule: ModuleRule) -> ModuleBoundaryDraft {
ModuleBoundaryDraft {
crate_package: self.crate_package,
module: self.module,
rule,
severity: Severity::Enforce,
}
}
}
pub struct ModuleBoundaryDraft {
crate_package: String,
module: String,
rule: ModuleRule,
severity: Severity,
}
impl ModuleBoundaryDraft {
pub fn warn(mut self) -> Self {
self.severity = Severity::Warn;
self
}
pub fn because(self, reason: &str) -> ModuleBoundary {
ModuleBoundary {
crate_package: self.crate_package,
module: self.module,
rule: self.rule,
reason: reason.to_string(),
severity: self.severity,
anchor: None,
}
}
}
pub struct InlineConfinementDraft {
crate_package: String,
module: String,
prefix: String,
ending_with: Option<Vec<String>>,
strict: bool,
external: bool,
severity: Severity,
}
impl InlineConfinementDraft {
pub fn ending_with<I, S>(mut self, verbs: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.ending_with = Some(verbs.into_iter().map(Into::into).collect());
self
}
pub fn strict_prefix_only(mut self) -> Self {
self.strict = true;
self
}
pub fn strict_external(mut self) -> Self {
self.external = true;
self
}
pub fn warn(mut self) -> Self {
self.severity = Severity::Warn;
self
}
pub fn because(self, reason: &str) -> ModuleBoundary {
let rule = ModuleRule::ConfineInlineSymbolPath {
prefix: self.prefix,
ending_with: self.ending_with,
strict: self.strict,
strict_external: self.external,
};
ModuleBoundary {
crate_package: self.crate_package,
module: self.module,
rule,
reason: reason.to_string(),
severity: self.severity,
anchor: None,
}
}
}