Merge feature/rules-toml (Workstream E)
This commit is contained in:
commit
3c70c7a823
7 changed files with 904 additions and 6 deletions
|
|
@ -282,6 +282,19 @@ fn config_path() -> PathBuf {
|
|||
expand_home("~/.config/bread/breadd.toml")
|
||||
}
|
||||
|
||||
/// Location of the optional `rules.toml` — declarative automation rules
|
||||
/// (see `crate::core::rules`). Resolved with the exact same
|
||||
/// `XDG_CONFIG_HOME`-vs-`HOME` precedence as `config_path()` above; see the
|
||||
/// `expand_home` doc comment for why every config-adjacent path the daemon
|
||||
/// resolves has to agree on that precedence.
|
||||
pub fn rules_path() -> PathBuf {
|
||||
if let Ok(xdg) = env::var("XDG_CONFIG_HOME") {
|
||||
return Path::new(&xdg).join("bread").join("rules.toml");
|
||||
}
|
||||
|
||||
expand_home("~/.config/bread/rules.toml")
|
||||
}
|
||||
|
||||
/// Expands a leading `~/`. `~/.config/...` paths specifically prefer
|
||||
/// `$XDG_CONFIG_HOME` when it's set, consistent with `config_path()`'s own
|
||||
/// resolution of `breadd.toml` itself — otherwise the default `lua.entry_point`
|
||||
|
|
@ -290,7 +303,7 @@ fn config_path() -> PathBuf {
|
|||
/// though the config file that sets them was found via that same variable,
|
||||
/// which is exactly the kind of inconsistency that made init.lua/module
|
||||
/// loading silently no-op for a XDG_CONFIG_HOME-only test setup.
|
||||
fn expand_home(input: &str) -> PathBuf {
|
||||
pub(crate) fn expand_home(input: &str) -> PathBuf {
|
||||
if let Some(stripped) = input.strip_prefix("~/.config/") {
|
||||
if let Ok(xdg_config) = env::var("XDG_CONFIG_HOME") {
|
||||
return Path::new(&xdg_config).join(stripped);
|
||||
|
|
@ -635,4 +648,25 @@ legacy_hyprland_event_names = false
|
|||
PathBuf::from("/synthetic/home/.config/bread/breadd.toml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_path_respects_xdg_config_home() {
|
||||
let _g = EnvGuard::new(&["XDG_CONFIG_HOME", "HOME"]);
|
||||
std::env::set_var("XDG_CONFIG_HOME", "/synthetic/xdg-config");
|
||||
assert_eq!(
|
||||
rules_path(),
|
||||
PathBuf::from("/synthetic/xdg-config/bread/rules.toml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_path_falls_back_to_home_when_no_xdg() {
|
||||
let _g = EnvGuard::new(&["XDG_CONFIG_HOME", "HOME"]);
|
||||
std::env::remove_var("XDG_CONFIG_HOME");
|
||||
std::env::set_var("HOME", "/synthetic/home");
|
||||
assert_eq!(
|
||||
rules_path(),
|
||||
PathBuf::from("/synthetic/home/.config/bread/rules.toml")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
pub mod config;
|
||||
pub mod normalizer;
|
||||
pub mod rules;
|
||||
pub mod state_engine;
|
||||
pub mod subscriptions;
|
||||
pub mod supervisor;
|
||||
|
|
|
|||
410
breadd/src/core/rules.rs
Normal file
410
breadd/src/core/rules.rs
Normal file
|
|
@ -0,0 +1,410 @@
|
|||
//! `rules.toml` — a declarative shortcut for the common "when event X
|
||||
//! happens, do Y" case that otherwise requires hand-written Lua
|
||||
//! (`bread.on(...)`, `bread.exec(...)`, etc).
|
||||
//!
|
||||
//! This module owns TOML parsing and validation only; it has no `mlua`
|
||||
//! dependency so it can be unit-tested in isolation. The `bread.rules`
|
||||
//! built-in Lua module (`breadd/src/lua/mod.rs`, `BUILTIN_RULES`) is the
|
||||
//! other half — it takes the [`ParsedRule`]s this module produces and turns
|
||||
//! each one into a real `bread.on()` subscription.
|
||||
//!
|
||||
//! Schema:
|
||||
//!
|
||||
//! ```toml
|
||||
//! [[rule]]
|
||||
//! on = "device.dock.connected" # matched against "bread." .. on, wildcards allowed
|
||||
//! run = "~/.config/bread/scripts/dock-connected.sh"
|
||||
//!
|
||||
//! [[rule]]
|
||||
//! on = "power.ac.disconnected"
|
||||
//! notify = "Unplugged"
|
||||
//!
|
||||
//! [[rule]]
|
||||
//! on = "device.keyboard.connected"
|
||||
//! exec = "xset r rate 200 40"
|
||||
//! ```
|
||||
//!
|
||||
//! Exactly one of `run` / `notify` / `exec` must be set per rule. `run` and
|
||||
//! `exec` both ultimately shell out via `bread.exec()`, but with distinct
|
||||
//! semantics documented on [`RuleAction`].
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
struct RulesFile {
|
||||
#[serde(default, rename = "rule")]
|
||||
rule: Vec<RawRule>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
struct RawRule {
|
||||
on: Option<String>,
|
||||
run: Option<String>,
|
||||
notify: Option<String>,
|
||||
exec: Option<String>,
|
||||
}
|
||||
|
||||
/// The action a validated rule fires when its event matches.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RuleAction {
|
||||
/// Path to a single script/executable. Treated as exactly one program —
|
||||
/// tilde-expanded and shell-quoted as a whole before being handed to
|
||||
/// `bread.exec()`, so a path containing spaces still runs as one file
|
||||
/// rather than being word-split into a command plus arguments.
|
||||
Run(String),
|
||||
/// A raw shell command line, passed to `bread.exec()` verbatim (same as
|
||||
/// calling `bread.exec()` from hand-written Lua) — you're responsible
|
||||
/// for quoting/escaping exactly as if you'd typed it in a shell.
|
||||
Exec(String),
|
||||
/// A desktop notification message, passed to `bread.notify()`.
|
||||
Notify(String),
|
||||
}
|
||||
|
||||
/// A `[[rule]]` entry that passed validation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ParsedRule {
|
||||
/// Event-name suffix, e.g. `"device.dock.connected"`. The real
|
||||
/// subscription is `"bread." .. on` — wildcards (`*`, `**`, `?`) are
|
||||
/// whatever `bread.on()` itself supports, since this is handed straight
|
||||
/// through.
|
||||
pub on: String,
|
||||
pub action: RuleAction,
|
||||
}
|
||||
|
||||
/// A `[[rule]]` entry that failed validation — reported, not silently
|
||||
/// dropped, so it shows up via `bread doctor` the same way a broken Lua
|
||||
/// module would.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RuleIssue {
|
||||
/// Zero-based position of the `[[rule]]` table in the file.
|
||||
pub index: usize,
|
||||
/// The rule's `on` value, if it had one (helps identify *which* rule in
|
||||
/// a large file when `on` itself isn't the problem).
|
||||
pub on: Option<String>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RuleIssue {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self.on {
|
||||
Some(on) => write!(f, "rule #{} (on = \"{}\"): {}", self.index, on, self.message),
|
||||
None => write!(f, "rule #{}: {}", self.index, self.message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of attempting to load `rules.toml`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RulesLoadOutcome {
|
||||
/// The file doesn't exist. Not an error — `rules.toml` is entirely
|
||||
/// optional and purely additive alongside `init.lua`.
|
||||
Absent,
|
||||
/// The file exists but couldn't be read, or doesn't parse as TOML at
|
||||
/// all — no rules could be recovered from it.
|
||||
Fatal(String),
|
||||
/// The file parsed as TOML. `rules` are the entries that passed
|
||||
/// validation (register these); `issues` describes any `[[rule]]`
|
||||
/// entries that didn't (report these, but they don't block the rest of
|
||||
/// the file from working).
|
||||
Loaded {
|
||||
rules: Vec<ParsedRule>,
|
||||
issues: Vec<RuleIssue>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Location of `rules.toml` — re-exported from `core::config` (single
|
||||
/// source of truth, colocated with `config_path()`'s identical
|
||||
/// `XDG_CONFIG_HOME`-vs-`HOME` resolution for `breadd.toml`) so callers that
|
||||
/// only care about rules loading can reach it as `rules::rules_path()`.
|
||||
pub use crate::core::config::rules_path;
|
||||
|
||||
/// Reads and validates `rules.toml` at `path`. Never panics — every failure
|
||||
/// mode (missing file, unreadable file, invalid TOML, invalid individual
|
||||
/// rules) is represented in the returned [`RulesLoadOutcome`].
|
||||
pub fn load_rules(path: &Path) -> RulesLoadOutcome {
|
||||
if !path.exists() {
|
||||
return RulesLoadOutcome::Absent;
|
||||
}
|
||||
|
||||
let raw = match std::fs::read_to_string(path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return RulesLoadOutcome::Fatal(format!("failed to read rules.toml: {e}")),
|
||||
};
|
||||
|
||||
let parsed: RulesFile = match toml::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return RulesLoadOutcome::Fatal(format!("failed to parse rules.toml: {e}")),
|
||||
};
|
||||
|
||||
let mut rules = Vec::new();
|
||||
let mut issues = Vec::new();
|
||||
for (index, raw_rule) in parsed.rule.into_iter().enumerate() {
|
||||
match validate_rule(index, raw_rule) {
|
||||
Ok(rule) => rules.push(rule),
|
||||
Err(issue) => issues.push(issue),
|
||||
}
|
||||
}
|
||||
|
||||
RulesLoadOutcome::Loaded { rules, issues }
|
||||
}
|
||||
|
||||
fn validate_rule(index: usize, raw: RawRule) -> Result<ParsedRule, RuleIssue> {
|
||||
let on = raw.on.filter(|s| !s.trim().is_empty());
|
||||
|
||||
let mut present = Vec::new();
|
||||
if raw.run.is_some() {
|
||||
present.push("run");
|
||||
}
|
||||
if raw.notify.is_some() {
|
||||
present.push("notify");
|
||||
}
|
||||
if raw.exec.is_some() {
|
||||
present.push("exec");
|
||||
}
|
||||
|
||||
let Some(on) = on else {
|
||||
return Err(RuleIssue {
|
||||
index,
|
||||
on: None,
|
||||
message: "missing or empty `on`".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
if present.is_empty() {
|
||||
return Err(RuleIssue {
|
||||
index,
|
||||
on: Some(on),
|
||||
message: "must set exactly one of `run`, `notify`, `exec` (none set)".to_string(),
|
||||
});
|
||||
}
|
||||
if present.len() > 1 {
|
||||
return Err(RuleIssue {
|
||||
index,
|
||||
on: Some(on),
|
||||
message: format!(
|
||||
"must set exactly one of `run`, `notify`, `exec` (found: {})",
|
||||
present.join(", ")
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let action = if let Some(v) = raw.run {
|
||||
RuleAction::Run(v)
|
||||
} else if let Some(v) = raw.notify {
|
||||
RuleAction::Notify(v)
|
||||
} else {
|
||||
RuleAction::Exec(raw.exec.expect("exactly one action present"))
|
||||
};
|
||||
|
||||
Ok(ParsedRule { on, action })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn write_temp(contents: &str) -> (tempfile::TempDir, PathBuf) {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("rules.toml");
|
||||
let mut f = std::fs::File::create(&path).expect("create rules.toml");
|
||||
f.write_all(contents.as_bytes()).expect("write rules.toml");
|
||||
(dir, path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_file_is_not_an_error() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().join("does-not-exist.toml");
|
||||
assert_eq!(load_rules(&path), RulesLoadOutcome::Absent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_toml_is_fatal() {
|
||||
let (_dir, path) = write_temp("[[rule\nbroken");
|
||||
match load_rules(&path) {
|
||||
RulesLoadOutcome::Fatal(msg) => assert!(msg.contains("failed to parse")),
|
||||
other => panic!("expected Fatal, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_file_loads_with_no_rules() {
|
||||
let (_dir, path) = write_temp("");
|
||||
assert_eq!(
|
||||
load_rules(&path),
|
||||
RulesLoadOutcome::Loaded {
|
||||
rules: vec![],
|
||||
issues: vec![],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn well_formed_rules_all_three_action_kinds_parse() {
|
||||
let (_dir, path) = write_temp(
|
||||
r#"
|
||||
[[rule]]
|
||||
on = "device.dock.connected"
|
||||
run = "~/.config/bread/scripts/dock-connected.sh"
|
||||
|
||||
[[rule]]
|
||||
on = "power.ac.disconnected"
|
||||
notify = "Unplugged"
|
||||
|
||||
[[rule]]
|
||||
on = "device.keyboard.connected"
|
||||
exec = "xset r rate 200 40"
|
||||
"#,
|
||||
);
|
||||
let RulesLoadOutcome::Loaded { rules, issues } = load_rules(&path) else {
|
||||
panic!("expected Loaded");
|
||||
};
|
||||
assert!(issues.is_empty());
|
||||
assert_eq!(
|
||||
rules,
|
||||
vec![
|
||||
ParsedRule {
|
||||
on: "device.dock.connected".to_string(),
|
||||
action: RuleAction::Run(
|
||||
"~/.config/bread/scripts/dock-connected.sh".to_string()
|
||||
),
|
||||
},
|
||||
ParsedRule {
|
||||
on: "power.ac.disconnected".to_string(),
|
||||
action: RuleAction::Notify("Unplugged".to_string()),
|
||||
},
|
||||
ParsedRule {
|
||||
on: "device.keyboard.connected".to_string(),
|
||||
action: RuleAction::Exec("xset r rate 200 40".to_string()),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcard_on_is_passed_through_unvalidated() {
|
||||
let (_dir, path) = write_temp(
|
||||
r#"
|
||||
[[rule]]
|
||||
on = "device.*.connected"
|
||||
exec = "true"
|
||||
"#,
|
||||
);
|
||||
let RulesLoadOutcome::Loaded { rules, issues } = load_rules(&path) else {
|
||||
panic!("expected Loaded");
|
||||
};
|
||||
assert!(issues.is_empty());
|
||||
assert_eq!(rules[0].on, "device.*.connected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_on_is_reported_with_index_and_no_on() {
|
||||
let (_dir, path) = write_temp(
|
||||
r#"
|
||||
[[rule]]
|
||||
exec = "true"
|
||||
"#,
|
||||
);
|
||||
let RulesLoadOutcome::Loaded { rules, issues } = load_rules(&path) else {
|
||||
panic!("expected Loaded");
|
||||
};
|
||||
assert!(rules.is_empty());
|
||||
assert_eq!(issues.len(), 1);
|
||||
assert_eq!(issues[0].index, 0);
|
||||
assert_eq!(issues[0].on, None);
|
||||
assert!(issues[0].message.contains("missing or empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_on_is_treated_as_missing() {
|
||||
let (_dir, path) = write_temp(
|
||||
r#"
|
||||
[[rule]]
|
||||
on = " "
|
||||
exec = "true"
|
||||
"#,
|
||||
);
|
||||
let RulesLoadOutcome::Loaded { issues, .. } = load_rules(&path) else {
|
||||
panic!("expected Loaded");
|
||||
};
|
||||
assert_eq!(issues.len(), 1);
|
||||
assert!(issues[0].message.contains("missing or empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_action_keys_is_reported() {
|
||||
let (_dir, path) = write_temp(
|
||||
r#"
|
||||
[[rule]]
|
||||
on = "power.ac.disconnected"
|
||||
"#,
|
||||
);
|
||||
let RulesLoadOutcome::Loaded { rules, issues } = load_rules(&path) else {
|
||||
panic!("expected Loaded");
|
||||
};
|
||||
assert!(rules.is_empty());
|
||||
assert_eq!(issues.len(), 1);
|
||||
assert_eq!(issues[0].on.as_deref(), Some("power.ac.disconnected"));
|
||||
assert!(issues[0].message.contains("none set"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_action_keys_is_reported() {
|
||||
let (_dir, path) = write_temp(
|
||||
r#"
|
||||
[[rule]]
|
||||
on = "power.ac.disconnected"
|
||||
notify = "Unplugged"
|
||||
exec = "true"
|
||||
"#,
|
||||
);
|
||||
let RulesLoadOutcome::Loaded { rules, issues } = load_rules(&path) else {
|
||||
panic!("expected Loaded");
|
||||
};
|
||||
assert!(rules.is_empty());
|
||||
assert_eq!(issues.len(), 1);
|
||||
assert!(issues[0].message.contains("notify"));
|
||||
assert!(issues[0].message.contains("exec"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_bad_rule_does_not_block_other_valid_rules() {
|
||||
let (_dir, path) = write_temp(
|
||||
r#"
|
||||
[[rule]]
|
||||
on = "device.dock.connected"
|
||||
exec = "true"
|
||||
|
||||
[[rule]]
|
||||
notify = "no on here"
|
||||
|
||||
[[rule]]
|
||||
on = "power.ac.disconnected"
|
||||
notify = "Unplugged"
|
||||
"#,
|
||||
);
|
||||
let RulesLoadOutcome::Loaded { rules, issues } = load_rules(&path) else {
|
||||
panic!("expected Loaded");
|
||||
};
|
||||
assert_eq!(rules.len(), 2);
|
||||
assert_eq!(issues.len(), 1);
|
||||
assert_eq!(issues[0].index, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_issue_display_includes_index_and_on() {
|
||||
let issue = RuleIssue {
|
||||
index: 2,
|
||||
on: Some("power.ac.disconnected".to_string()),
|
||||
message: "must set exactly one of `run`, `notify`, `exec` (none set)".to_string(),
|
||||
};
|
||||
assert_eq!(
|
||||
issue.to_string(),
|
||||
"rule #2 (on = \"power.ac.disconnected\"): must set exactly one of `run`, `notify`, `exec` (none set)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ use tokio::time::{interval_at, sleep, Instant};
|
|||
use tracing::{error, info, warn};
|
||||
|
||||
use crate::core::config::{Config, ModulesConfig, NotificationsConfig};
|
||||
use crate::core::rules::{self, RuleAction, RulesLoadOutcome};
|
||||
use crate::core::state_engine::StateHandle;
|
||||
use crate::core::subscriptions::SubscriptionId;
|
||||
use crate::core::types::{
|
||||
|
|
@ -299,6 +300,7 @@ impl LuaEngine {
|
|||
self.install_api()?;
|
||||
self.load_device_rules()?;
|
||||
self.load_profiles()?;
|
||||
self.load_rules_toml()?;
|
||||
self.load_init_and_modules()?;
|
||||
self.run_on_reload();
|
||||
|
||||
|
|
@ -1345,6 +1347,70 @@ impl LuaEngine {
|
|||
.map_err(|e| anyhow!("profiles.lua error: {e}"))
|
||||
}
|
||||
|
||||
/// Reads and validates `rules.toml` (if present) and stashes the result
|
||||
/// in Lua globals for `bread.rules`'s `on_load()` to pick up once
|
||||
/// `load_init_and_modules()` loads that built-in module. See the
|
||||
/// `BUILTIN_RULES` doc comment for why globals rather than generating
|
||||
/// Lua source text: the rule data is dynamic (comes from a config file
|
||||
/// parsed fresh each reload) while `ModuleDecl::source` is a
|
||||
/// `&'static str`, so passing it as real Lua values via `mlua`'s Table
|
||||
/// API sidesteps ever having to hand-escape a path or shell command
|
||||
/// into a Lua string literal.
|
||||
fn load_rules_toml(&self) -> Result<()> {
|
||||
let path = rules::rules_path();
|
||||
match rules::load_rules(&path) {
|
||||
RulesLoadOutcome::Absent => Ok(()),
|
||||
RulesLoadOutcome::Fatal(msg) => {
|
||||
self.lua.globals().set("__rules_fatal", msg)?;
|
||||
Ok(())
|
||||
}
|
||||
RulesLoadOutcome::Loaded { rules, issues } => {
|
||||
let data = self.lua.create_table()?;
|
||||
for (i, rule) in rules.iter().enumerate() {
|
||||
let tbl = self.lua.create_table()?;
|
||||
tbl.set("on", rule.on.clone())?;
|
||||
match &rule.action {
|
||||
// `run` names exactly one program: tilde-expand it
|
||||
// the same way `bread.fs.*`/`bread.exec` callers
|
||||
// would, then shell-quote the whole thing so a path
|
||||
// containing spaces still runs as one file rather
|
||||
// than being word-split by the `sh -c` that
|
||||
// `bread.exec()` runs it through.
|
||||
RuleAction::Run(path) => {
|
||||
let expanded = lua_expand_path(path);
|
||||
let quoted = shell_quote(&expanded.to_string_lossy());
|
||||
tbl.set("run", quoted)?;
|
||||
}
|
||||
// `exec` is a full shell command line — pass it
|
||||
// through to `bread.exec()` verbatim, exactly like
|
||||
// hand-written Lua calling `bread.exec()` directly.
|
||||
RuleAction::Exec(cmd) => {
|
||||
tbl.set("exec", cmd.clone())?;
|
||||
}
|
||||
RuleAction::Notify(message) => {
|
||||
tbl.set("notify", message.clone())?;
|
||||
}
|
||||
}
|
||||
data.set(i + 1, tbl)?;
|
||||
}
|
||||
self.lua.globals().set("__rules_data", data)?;
|
||||
|
||||
if !issues.is_empty() {
|
||||
let combined = issues
|
||||
.iter()
|
||||
.map(|issue| issue.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
self.lua
|
||||
.globals()
|
||||
.set("__rules_warning", format!("rules.toml: {combined}"))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_init_and_modules(&self) -> Result<()> {
|
||||
self.load_lua_file(&self.entry_point, "init", false)?;
|
||||
|
||||
|
|
@ -2648,6 +2714,15 @@ fn lua_expand_path(path: &str) -> std::path::PathBuf {
|
|||
std::path::PathBuf::from(path)
|
||||
}
|
||||
|
||||
/// POSIX single-quotes `s` for safe embedding as one token in a `sh -c`
|
||||
/// command line — used for `rules.toml`'s `run = "<script path>"` action
|
||||
/// (see `LuaEngine::load_rules_toml`), which is meant to name exactly one
|
||||
/// program regardless of spaces in its path, unlike `exec = "..."` which is
|
||||
/// a full command line handed to the shell as-is.
|
||||
fn shell_quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', r"'\''"))
|
||||
}
|
||||
|
||||
fn dirs_home() -> Option<std::path::PathBuf> {
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
return Some(std::path::PathBuf::from(home));
|
||||
|
|
@ -2936,6 +3011,68 @@ end
|
|||
return M
|
||||
"#;
|
||||
|
||||
// `bread.rules` — the Lua half of the `rules.toml` declarative automation
|
||||
// layer (see `crate::core::rules` for TOML parsing/validation). This module
|
||||
// itself is static like the other built-ins; the *data* it acts on is
|
||||
// dynamic (parsed from the user's rules.toml each reload), so it's threaded
|
||||
// through via `__rules_data` / `__rules_fatal` / `__rules_warning` globals
|
||||
// that `load_rules_toml()` sets just before `load_init_and_modules()` runs
|
||||
// this module's `on_load()` — the same "stash data in a global, consume it
|
||||
// from a lifecycle hook, then clear it" technique `load_profiles()` already
|
||||
// uses for `__profiles_path`.
|
||||
//
|
||||
// A fatal problem (rules.toml unreadable or not valid TOML) is surfaced by
|
||||
// calling Lua's `error()`, which `run_on_load()` propagates back to
|
||||
// `load_module()` exactly like any other module's `on_load` failure — so it
|
||||
// shows up in `bread doctor` / `modules.list` as `bread.rules` in
|
||||
// `load_error` state with a `last_error`, the same path a broken
|
||||
// hand-written Lua module's error already takes. A handful of individually
|
||||
// malformed `[[rule]]` entries (bad `on`, wrong number of action keys)
|
||||
// aren't fatal to the rest of the file: the valid rules register first (so
|
||||
// they keep working), then the collected issue list is raised the same way
|
||||
// so it's still doctor-visible rather than a silent no-op.
|
||||
const BUILTIN_RULES: &str = r#"
|
||||
local M = bread.module({ name = "bread.rules", version = "1.0.0" })
|
||||
|
||||
local function run_action(rule)
|
||||
if rule.run then
|
||||
bread.exec(rule.run)
|
||||
elseif rule.exec then
|
||||
bread.exec(rule.exec)
|
||||
elseif rule.notify then
|
||||
bread.notify(rule.notify)
|
||||
end
|
||||
end
|
||||
|
||||
function M.on_load()
|
||||
if __rules_fatal then
|
||||
local msg = __rules_fatal
|
||||
__rules_fatal = nil
|
||||
__rules_data = nil
|
||||
__rules_warning = nil
|
||||
error(msg)
|
||||
end
|
||||
|
||||
local data = __rules_data
|
||||
__rules_data = nil
|
||||
if data then
|
||||
for _, rule in ipairs(data) do
|
||||
bread.on("bread." .. rule.on, function(event)
|
||||
run_action(rule)
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
if __rules_warning then
|
||||
local msg = __rules_warning
|
||||
__rules_warning = nil
|
||||
error(msg)
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
"#;
|
||||
|
||||
fn builtin_module_decls(disabled: &HashSet<String>) -> Vec<ModuleDecl> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
|
|
@ -2949,6 +3086,7 @@ fn builtin_module_decls(disabled: &HashSet<String>) -> Vec<ModuleDecl> {
|
|||
BUILTIN_WORKSPACES,
|
||||
),
|
||||
("bread.binds", "1.0.0", Vec::new(), BUILTIN_BINDS),
|
||||
("bread.rules", "1.0.0", Vec::new(), BUILTIN_RULES),
|
||||
];
|
||||
|
||||
for (name, version, after, source) in entries {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue