refactor(config): move the matching types into komorebi-config

MatchingRule, WorkspaceMatchingRule, IdWithIdentifier, MatchingStrategy and IdWithIdentifierAndComment (with the From impl) are byte-identical, docs included, in config_generation.rs of the three trees apart from imports. The crate takes the KDE copy (module docs and its four tests) with ApplicationIdentifier from komorebi-protocol. The trees still carry their own copies; they switch in the next revisions.

The oracle test gains a check that the generated definitions of MatchingRule, IdWithIdentifier and MatchingStrategy equal the $defs of all three checked-in schema.json files (ApplicationIdentifier is the protocol crate's and differs per platform by design).

Verified: native cargo test -p komorebi-config: 4 unit + 3 schemas passed, 0 failed (tier 1).
This commit is contained in:
LGUG2Z committed 2026-10-31 01:37:53 -07:00
1 parent 06436c98fe
commit 504290e5a8
3 files changed
+222

No files matched your search

+2
View File
@@ -9,3 +9,5 @@
#[cfg(feature = "schemars")]
pub mod schema;
pub mod matching;
+161
View File
@@ -0,0 +1,161 @@
//! Rules that match an application by how it identifies itself.
//!
//! A [`MatchingRule`] is the form every list of rules in the configuration takes: a single
//! [`IdWithIdentifier`], or a list of them that must all match.
use serde::Deserialize;
use serde::Serialize;
use strum::Display;
use komorebi_protocol::types::ApplicationIdentifier;
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(untagged)]
/// Rule for matching applications
pub enum MatchingRule {
/// Simple matching rule which must evaluate to true
Simple(IdWithIdentifier),
/// Composite matching rule where all conditions must evaluate to true
Composite(Vec<IdWithIdentifier>),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
/// Rule for assigning applications to a workspace
pub struct WorkspaceMatchingRule {
/// Target monitor index
pub monitor_index: usize,
/// Target workspace index
pub workspace_index: usize,
/// Matching rule for the application
pub matching_rule: MatchingRule,
/// Whether to apply the rule only when the application is initially launched
pub initial_only: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
/// Rule for matching applications
pub struct IdWithIdentifier {
/// Kind of identifier to target
pub kind: ApplicationIdentifier,
/// Target identifier
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
/// Matching strategy to use
pub matching_strategy: Option<MatchingStrategy>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
/// Strategy for matching identifiers
pub enum MatchingStrategy {
/// Should not be used, only kept for backward compatibility
Legacy,
/// Equals
Equals,
/// Starts With
StartsWith,
/// Ends With
EndsWith,
/// Contains
Contains,
/// Regex
Regex,
/// Does not end with
DoesNotEndWith,
/// Does not start with
DoesNotStartWith,
/// Does not equal
DoesNotEqual,
/// Does not contain
DoesNotContain,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct IdWithIdentifierAndComment {
pub kind: ApplicationIdentifier,
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub matching_strategy: Option<MatchingStrategy>,
}
impl From<IdWithIdentifierAndComment> for IdWithIdentifier {
fn from(value: IdWithIdentifierAndComment) -> Self {
Self {
kind: value.kind,
id: value.id.clone(),
matching_strategy: value.matching_strategy,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_rule_that_is_an_object_is_simple() {
let rule: MatchingRule = serde_json::from_str(
r#"{ "kind": "Exe", "id": "foot", "matching_strategy": "Equals" }"#,
)
.expect("parses");
assert_eq!(
rule,
MatchingRule::Simple(IdWithIdentifier {
kind: ApplicationIdentifier::Exe,
id: "foot".to_string(),
matching_strategy: Some(MatchingStrategy::Equals),
})
);
}
#[test]
fn a_rule_that_is_a_list_is_composite() {
let rule: MatchingRule = serde_json::from_str(
r#"[{ "kind": "Exe", "id": "foot" }, { "kind": "Title", "id": "scratch", "matching_strategy": "StartsWith" }]"#,
)
.expect("parses");
let MatchingRule::Composite(parts) = rule else {
panic!("a list of objects is a composite rule");
};
assert_eq!(parts.len(), 2);
assert_eq!(
parts[1].matching_strategy,
Some(MatchingStrategy::StartsWith)
);
}
#[test]
fn the_matching_strategy_is_left_out_when_there_is_none() {
let rule = IdWithIdentifier {
kind: ApplicationIdentifier::Class,
id: "firefox".to_string(),
matching_strategy: None,
};
let json = serde_json::to_string(&rule).expect("serializes");
assert_eq!(json, r#"{"kind":"Class","id":"firefox"}"#);
}
#[test]
fn a_commented_rule_becomes_a_plain_one() {
let commented: IdWithIdentifierAndComment = serde_json::from_str(
r#"{ "kind": "Path", "id": "/usr/bin/kcalc", "comment": "a calculator" }"#,
)
.expect("parses");
let plain = IdWithIdentifier::from(commented);
assert_eq!(plain.kind, ApplicationIdentifier::Path);
assert_eq!(plain.id, "/usr/bin/kcalc");
assert_eq!(plain.matching_strategy, None);
}
}
+59
View File
@@ -109,3 +109,62 @@ fn the_checked_in_schemas_have_the_keys_of_each_platform() {
);
}
}
/// The definitions schemars generates for `T` and for everything `T` refers to, by name.
fn generated<T: schemars::JsonSchema>() -> serde_json::Map<String, Value> {
let mut generator = schemars::generate::SchemaSettings::draft2020_12().into_generator();
let _ = generator.subschema_for::<T>();
let defs = generator.take_definitions(true);
match serde_json::to_value(&defs).expect("definitions are JSON") {
Value::Object(map) => map,
other => panic!("definitions are an object, not {other}"),
}
}
/// The definitions `owned` by this crate (the others come with `T` but live in the layouts,
/// themes or protocol crates and have their own checks) must be in each of the `trees`'
/// `schema.json` and equal to what is generated for `T`.
fn assert_same_definitions<T: schemars::JsonSchema>(trees: &[&Tree], owned: &[&str]) {
let generated = generated::<T>();
for tree in trees {
let schema: Value = serde_json::from_str(&checked_in(tree, "schema.json")).unwrap();
let defs = schema["$defs"].as_object().unwrap();
for name in owned {
assert!(
defs.contains_key(*name),
"{} schema.json has no {name}",
tree.name
);
assert!(generated.contains_key(*name), "{name} was not generated");
}
for name in owned {
let def = &generated[*name];
if let Some(checked) = defs.get(*name) {
assert!(
checked == def,
"{} schema.json: the definition of {name} differs from the generated one:\n{}\n---\n{}",
tree.name,
serde_json::to_string_pretty(checked).unwrap(),
serde_json::to_string_pretty(def).unwrap(),
);
}
}
}
}
fn all() -> Vec<&'static Tree> {
TREES.iter().collect()
}
#[test]
fn the_matching_types_are_the_definitions_of_every_tree() {
use komorebi_config::matching::MatchingRule;
use komorebi_config::matching::WorkspaceMatchingRule;
assert_same_definitions::<MatchingRule>(
&all(),
&["MatchingRule", "IdWithIdentifier", "MatchingStrategy"],
);
// The workspace rules are an input of the daemons only: no schema carries them.
let _ = generated::<WorkspaceMatchingRule>();
}