layers reads cargo metadata and rejects upward, sideways and tool-crate dependencies and any path to Tauri below L6. assets checks ASSETS.md rows and rejects committed fonts. cleanroom rejects JetBrains copyright notices, exported IDE configuration and .idea/.jar/.icls files. deny.toml mirrors the licence allow list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
420 lines
14 KiB
Rust
420 lines
14 KiB
Rust
//! `cargo xtask layers`: enforces the crate layering of docs/architecture.md.
|
|
//!
|
|
//! Every workspace crate declares `[package.metadata.lutra] layer = N` (or
|
|
//! `"tool"`). A crate may depend only on workspace crates of a lower layer,
|
|
//! must not depend on tool crates outside dev-dependencies, and nothing below
|
|
//! layer 6 may reach a Tauri package through its normal dependencies.
|
|
|
|
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
|
|
|
use serde_json::Value;
|
|
|
|
use crate::util::{TaskResult, capture, repo_root};
|
|
|
|
/// The layer at and above which crates may depend on Tauri.
|
|
const UI_LAYER: u8 = 6;
|
|
|
|
/// Layer of a workspace crate.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Layer {
|
|
/// A shipped crate in layer `N`.
|
|
Level(u8),
|
|
/// A development tool (`testkit`, `xtask`), outside the layering.
|
|
Tool,
|
|
}
|
|
|
|
/// Kind of a dependency edge.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum DepKind {
|
|
/// A `[dependencies]` entry.
|
|
Normal,
|
|
/// A `[build-dependencies]` entry.
|
|
Build,
|
|
/// A `[dev-dependencies]` entry.
|
|
Dev,
|
|
}
|
|
|
|
/// A workspace crate and its direct dependencies on other workspace crates.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Crate {
|
|
/// Package id from `cargo metadata`, the key into [`Workspace::graph`].
|
|
pub id: String,
|
|
/// Package name.
|
|
pub name: String,
|
|
/// Declared layer, `None` if the manifest has none or an invalid one.
|
|
pub layer: Option<Layer>,
|
|
/// Direct dependencies on workspace crates, by package name.
|
|
pub deps: Vec<(String, DepKind)>,
|
|
}
|
|
|
|
/// The facts the layer check needs from `cargo metadata`.
|
|
#[derive(Debug, Clone, Default)]
|
|
pub struct Workspace {
|
|
/// The workspace members.
|
|
pub crates: Vec<Crate>,
|
|
/// Normal-dependency edges of the whole resolved graph, by package id.
|
|
pub graph: BTreeMap<String, Vec<String>>,
|
|
/// Package name of every package id in the graph.
|
|
pub names: BTreeMap<String, String>,
|
|
}
|
|
|
|
/// Runs the check on the current workspace.
|
|
///
|
|
/// # Errors
|
|
/// Fails with one line per violation, or if `cargo metadata` fails.
|
|
pub fn check_workspace() -> TaskResult {
|
|
let root = repo_root()?;
|
|
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
|
|
let json = capture(&root, &cargo, &["metadata", "--format-version", "1"])?;
|
|
let metadata: Value =
|
|
serde_json::from_str(&json).map_err(|e| format!("cargo metadata: {e}"))?;
|
|
let workspace = parse_metadata(&metadata)?;
|
|
let violations = check(&workspace);
|
|
if violations.is_empty() {
|
|
println!("layers: {} crates OK", workspace.crates.len());
|
|
Ok(())
|
|
} else {
|
|
Err(format!("layer violations:\n {}", violations.join("\n ")))
|
|
}
|
|
}
|
|
|
|
/// Extracts a [`Workspace`] from `cargo metadata --format-version 1` output.
|
|
///
|
|
/// # Errors
|
|
/// Fails if the JSON lacks the `packages`, `workspace_members` or `resolve`
|
|
/// fields.
|
|
pub fn parse_metadata(metadata: &Value) -> TaskResult<Workspace> {
|
|
let packages = metadata
|
|
.get("packages")
|
|
.and_then(Value::as_array)
|
|
.ok_or("cargo metadata: no packages")?;
|
|
let members: BTreeSet<&str> = metadata
|
|
.get("workspace_members")
|
|
.and_then(Value::as_array)
|
|
.ok_or("cargo metadata: no workspace_members")?
|
|
.iter()
|
|
.filter_map(Value::as_str)
|
|
.collect();
|
|
let member_names: BTreeSet<&str> = packages
|
|
.iter()
|
|
.filter(|p| {
|
|
p.get("id")
|
|
.and_then(Value::as_str)
|
|
.is_some_and(|id| members.contains(id))
|
|
})
|
|
.filter_map(|p| p.get("name").and_then(Value::as_str))
|
|
.collect();
|
|
|
|
let mut workspace = Workspace::default();
|
|
for package in packages {
|
|
let id = str_field(package, "id");
|
|
let name = str_field(package, "name");
|
|
workspace.names.insert(id.clone(), name.clone());
|
|
if !members.contains(id.as_str()) {
|
|
continue;
|
|
}
|
|
let layer = package
|
|
.get("metadata")
|
|
.and_then(|m| m.get("lutra"))
|
|
.and_then(|l| l.get("layer"))
|
|
.and_then(|l| match l {
|
|
Value::String(s) if s == "tool" => Some(Layer::Tool),
|
|
Value::Number(n) => n
|
|
.as_u64()
|
|
.and_then(|n| u8::try_from(n).ok())
|
|
.map(Layer::Level),
|
|
_ => None,
|
|
});
|
|
let deps = package
|
|
.get("dependencies")
|
|
.and_then(Value::as_array)
|
|
.map(|deps| {
|
|
deps.iter()
|
|
.filter_map(|d| {
|
|
let dep_name = d.get("name").and_then(Value::as_str)?;
|
|
if !member_names.contains(dep_name) {
|
|
return None;
|
|
}
|
|
let kind = match d.get("kind").and_then(Value::as_str) {
|
|
Some("dev") => DepKind::Dev,
|
|
Some("build") => DepKind::Build,
|
|
_ => DepKind::Normal,
|
|
};
|
|
Some((dep_name.to_string(), kind))
|
|
})
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
workspace.crates.push(Crate {
|
|
id,
|
|
name,
|
|
layer,
|
|
deps,
|
|
});
|
|
}
|
|
|
|
let nodes = metadata
|
|
.get("resolve")
|
|
.and_then(|r| r.get("nodes"))
|
|
.and_then(Value::as_array)
|
|
.ok_or("cargo metadata: no resolve graph")?;
|
|
for node in nodes {
|
|
let id = str_field(node, "id");
|
|
let deps = node
|
|
.get("deps")
|
|
.and_then(Value::as_array)
|
|
.map(|deps| {
|
|
deps.iter()
|
|
.filter(|d| {
|
|
d.get("dep_kinds")
|
|
.and_then(Value::as_array)
|
|
.is_some_and(|kinds| {
|
|
kinds
|
|
.iter()
|
|
.any(|k| k.get("kind").is_none_or(Value::is_null))
|
|
})
|
|
})
|
|
.map(|d| str_field(d, "pkg"))
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
workspace.graph.insert(id, deps);
|
|
}
|
|
Ok(workspace)
|
|
}
|
|
|
|
/// Returns a string field of a JSON object, or an empty string.
|
|
fn str_field(value: &Value, key: &str) -> String {
|
|
value
|
|
.get(key)
|
|
.and_then(Value::as_str)
|
|
.unwrap_or_default()
|
|
.to_string()
|
|
}
|
|
|
|
/// Checks the layering rules and returns one message per violation.
|
|
pub fn check(workspace: &Workspace) -> Vec<String> {
|
|
let layers: BTreeMap<&str, Option<Layer>> = workspace
|
|
.crates
|
|
.iter()
|
|
.map(|c| (c.name.as_str(), c.layer))
|
|
.collect();
|
|
let mut violations = Vec::new();
|
|
for krate in &workspace.crates {
|
|
let Some(layer) = krate.layer else {
|
|
violations.push(format!(
|
|
"{} has no [package.metadata.lutra] layer (a number or \"tool\")",
|
|
krate.name
|
|
));
|
|
continue;
|
|
};
|
|
let Layer::Level(own) = layer else {
|
|
continue;
|
|
};
|
|
for (dep, kind) in &krate.deps {
|
|
if *kind == DepKind::Dev {
|
|
continue;
|
|
}
|
|
match layers.get(dep.as_str()).copied().flatten() {
|
|
Some(Layer::Level(other)) if other >= own => violations.push(format!(
|
|
"{} (L{own}) depends on {dep} (L{other}); dependencies must be in a lower layer",
|
|
krate.name
|
|
)),
|
|
Some(Layer::Tool) => violations.push(format!(
|
|
"{} depends on the tool crate {dep} outside dev-dependencies",
|
|
krate.name
|
|
)),
|
|
_ => {}
|
|
}
|
|
}
|
|
if own < UI_LAYER
|
|
&& let Some(path) = tauri_path(workspace, &krate.id)
|
|
{
|
|
violations.push(format!(
|
|
"{} (L{own}) reaches Tauri: {}",
|
|
krate.name,
|
|
path.join(" -> ")
|
|
));
|
|
}
|
|
}
|
|
violations
|
|
}
|
|
|
|
/// Finds a chain of normal dependencies from `start` to a `tauri` or
|
|
/// `tauri-*` package, returned as package names.
|
|
fn tauri_path(workspace: &Workspace, start: &str) -> Option<Vec<String>> {
|
|
let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
|
|
let mut queue = VecDeque::from([start]);
|
|
let mut seen = BTreeSet::from([start]);
|
|
while let Some(id) = queue.pop_front() {
|
|
let name = workspace.names.get(id).map(String::as_str).unwrap_or(id);
|
|
if id != start && (name == "tauri" || name.starts_with("tauri-")) {
|
|
let mut chain = vec![name.to_string()];
|
|
let mut cur = id;
|
|
while let Some(prev) = parent.get(cur) {
|
|
chain.push(
|
|
workspace
|
|
.names
|
|
.get(*prev)
|
|
.cloned()
|
|
.unwrap_or_else(|| (*prev).to_string()),
|
|
);
|
|
cur = prev;
|
|
}
|
|
chain.reverse();
|
|
return Some(chain);
|
|
}
|
|
for next in workspace.graph.get(id).into_iter().flatten() {
|
|
if seen.insert(next.as_str()) {
|
|
parent.insert(next.as_str(), id);
|
|
queue.push_back(next.as_str());
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn krate(name: &str, layer: Option<Layer>, deps: &[(&str, DepKind)]) -> Crate {
|
|
Crate {
|
|
id: name.into(),
|
|
name: name.into(),
|
|
layer,
|
|
deps: deps.iter().map(|(n, k)| (n.to_string(), *k)).collect(),
|
|
}
|
|
}
|
|
|
|
fn workspace(crates: Vec<Crate>, edges: &[(&str, &str)]) -> Workspace {
|
|
let mut ws = Workspace {
|
|
crates,
|
|
..Default::default()
|
|
};
|
|
for c in &ws.crates {
|
|
ws.names.insert(c.id.clone(), c.name.clone());
|
|
ws.graph.entry(c.id.clone()).or_default();
|
|
}
|
|
for (from, to) in edges {
|
|
ws.names
|
|
.entry(to.to_string())
|
|
.or_insert_with(|| to.to_string());
|
|
ws.graph
|
|
.entry(from.to_string())
|
|
.or_default()
|
|
.push(to.to_string());
|
|
}
|
|
ws
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_downward_dependencies() {
|
|
let ws = workspace(
|
|
vec![
|
|
krate("text", Some(Layer::Level(0)), &[]),
|
|
krate(
|
|
"engine",
|
|
Some(Layer::Level(4)),
|
|
&[("text", DepKind::Normal), ("testkit", DepKind::Dev)],
|
|
),
|
|
krate("testkit", Some(Layer::Tool), &[("engine", DepKind::Normal)]),
|
|
],
|
|
&[("engine", "text")],
|
|
);
|
|
assert!(check(&ws).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_upward_and_sideways_dependencies() {
|
|
let ws = workspace(
|
|
vec![
|
|
krate(
|
|
"text",
|
|
Some(Layer::Level(0)),
|
|
&[("engine", DepKind::Normal)],
|
|
),
|
|
krate("vfs", Some(Layer::Level(2)), &[("index", DepKind::Build)]),
|
|
krate("index", Some(Layer::Level(2)), &[]),
|
|
krate("engine", Some(Layer::Level(4)), &[]),
|
|
],
|
|
&[],
|
|
);
|
|
let v = check(&ws);
|
|
assert_eq!(v.len(), 2, "{v:?}");
|
|
assert!(v[0].contains("text (L0) depends on engine (L4)"));
|
|
assert!(v[1].contains("vfs (L2) depends on index (L2)"));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_tool_crates_as_normal_dependencies() {
|
|
let ws = workspace(
|
|
vec![
|
|
krate(
|
|
"engine",
|
|
Some(Layer::Level(4)),
|
|
&[("testkit", DepKind::Normal)],
|
|
),
|
|
krate("testkit", Some(Layer::Tool), &[]),
|
|
],
|
|
&[],
|
|
);
|
|
assert!(check(&ws)[0].contains("tool crate testkit"));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_missing_layer() {
|
|
let ws = workspace(vec![krate("stray", None, &[])], &[]);
|
|
assert!(check(&ws)[0].contains("stray has no"));
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_transitive_tauri_below_ui_layer() {
|
|
let ws = workspace(
|
|
vec![
|
|
krate("engine", Some(Layer::Level(4)), &[]),
|
|
krate("desktop", Some(Layer::Level(6)), &[]),
|
|
],
|
|
&[
|
|
("engine", "helper"),
|
|
("helper", "tauri-runtime"),
|
|
("desktop", "tauri"),
|
|
],
|
|
);
|
|
let v = check(&ws);
|
|
assert_eq!(v.len(), 1, "{v:?}");
|
|
assert!(v[0].contains("engine -> helper -> tauri-runtime"));
|
|
}
|
|
|
|
#[test]
|
|
fn parses_cargo_metadata() {
|
|
let json = serde_json::json!({
|
|
"packages": [
|
|
{"id": "a 0.0.0", "name": "a", "metadata": {"lutra": {"layer": 1}},
|
|
"dependencies": [{"name": "b", "kind": null}, {"name": "serde", "kind": null}, {"name": "t", "kind": "dev"}]},
|
|
{"id": "b 0.0.0", "name": "b", "metadata": {"lutra": {"layer": 0}}, "dependencies": []},
|
|
{"id": "t 0.0.0", "name": "t", "metadata": {"lutra": {"layer": "tool"}}, "dependencies": []},
|
|
{"id": "serde 1.0.0", "name": "serde", "metadata": null, "dependencies": []}
|
|
],
|
|
"workspace_members": ["a 0.0.0", "b 0.0.0", "t 0.0.0"],
|
|
"resolve": {"nodes": [
|
|
{"id": "a 0.0.0", "deps": [
|
|
{"pkg": "b 0.0.0", "dep_kinds": [{"kind": null}]},
|
|
{"pkg": "t 0.0.0", "dep_kinds": [{"kind": "dev"}]}
|
|
]}
|
|
]}
|
|
});
|
|
let ws = parse_metadata(&json).unwrap();
|
|
assert_eq!(ws.crates.len(), 3);
|
|
assert_eq!(
|
|
ws.crates[0].deps,
|
|
vec![
|
|
("b".to_string(), DepKind::Normal),
|
|
("t".to_string(), DepKind::Dev)
|
|
]
|
|
);
|
|
assert_eq!(ws.crates[2].layer, Some(Layer::Tool));
|
|
assert_eq!(ws.graph["a 0.0.0"], vec!["b 0.0.0".to_string()]);
|
|
assert!(check(&ws).is_empty());
|
|
}
|
|
}
|