Skip to main content

grex_core/execute/
plan.rs

1//! Dry-run executor.
2//!
3//! [`PlanExecutor`] implements [`super::ActionExecutor`] without mutating
4//! state. Every action string field is passed through
5//! [`crate::vars::expand`] and every filesystem idempotency check goes
6//! through read-only syscalls (`symlink_metadata`, `Path::exists`,
7//! `std::env::var`). No spawns, no writes, no registry probes.
8//!
9//! Errors distinguish three layers:
10//! 1. Variable expansion failure → [`ExecError::VarExpand`].
11//! 2. Expanded path is empty or otherwise unusable → [`ExecError::InvalidPath`].
12//! 3. A `require` predicate held false under `on_fail: error` →
13//!    [`ExecError::RequireFailed`].
14//!
15//! Anything else (`when.os` not matching, `require` skip/warn) emits an
16//! [`ExecStep`] with [`ExecResult::NoOp`] — "nothing to do here, carry on".
17
18use std::borrow::Cow;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21
22use crate::pack::{
23    Action, Combiner, EnvArgs, ExecOnFail, ExecSpec, MkdirArgs, RequireOnFail, RequireSpec,
24    RmdirArgs, SymlinkArgs, UnlinkArgs, WhenSpec,
25};
26use crate::plugin::Registry;
27use crate::vars::{expand, VarEnv};
28
29use super::ctx::ExecCtx;
30use super::error::ExecError;
31use super::predicate::{evaluate, evaluate_when_gate};
32use super::step::{
33    ExecResult, ExecStep, PredicateOutcome, StepKind, ACTION_ENV, ACTION_EXEC, ACTION_MKDIR,
34    ACTION_REQUIRE, ACTION_RMDIR, ACTION_SYMLINK, ACTION_UNLINK, ACTION_WHEN,
35};
36use super::ActionExecutor;
37
38/// Dry-run [`ActionExecutor`] — never mutates state.
39///
40/// Dispatch is registry-validated (M4-B S1): every action's
41/// [`Action::name`] is looked up in the embedded plugin [`Registry`] so
42/// unknown action kinds surface as [`ExecError::UnknownAction`] with the
43/// same taxonomy as [`crate::execute::FsExecutor`]. The planner keeps its
44/// own dry-run implementations (the Tier-1 [`crate::plugin::ActionPlugin`]
45/// set is wet-run only) and uses the registry purely as a name oracle.
46///
47/// Useful for `grex plan`, CI validation, and unit-testing pack semantics.
48/// Safe to call across threads; `Clone` bumps the inner [`Arc`] refcount.
49#[derive(Debug, Clone)]
50pub struct PlanExecutor {
51    registry: Arc<Registry>,
52}
53
54impl Default for PlanExecutor {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59
60impl PlanExecutor {
61    /// Construct a fresh planner backed by the full Tier-1 built-in
62    /// registry ([`Registry::bootstrap`]). Matches the pre-M4-B
63    /// constructor shape so existing test sites continue to compile.
64    #[must_use]
65    pub fn new() -> Self {
66        Self { registry: Arc::new(Registry::bootstrap()) }
67    }
68
69    /// Construct a planner backed by an explicit registry. Primarily for
70    /// tests that want to exercise [`ExecError::UnknownAction`] or share
71    /// a single registry instance with the wet-run executor.
72    #[must_use]
73    pub fn with_registry(registry: Arc<Registry>) -> Self {
74        Self { registry }
75    }
76}
77
78impl ActionExecutor for PlanExecutor {
79    fn name(&self) -> &'static str {
80        "plan"
81    }
82
83    fn execute(&self, action: &Action, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
84        let name = action.name();
85        // Registry membership gates dispatch so `PlanExecutor` surfaces
86        // the same `UnknownAction` taxonomy as `FsExecutor`. The planner
87        // then delegates to its own dry-run `plan_*` helpers — Tier-1
88        // plugins are wet-run only and would mutate state if invoked here,
89        // so the registry is used purely as a name oracle.
90        if self.registry.get(name).is_none() {
91            return Err(ExecError::UnknownAction(name.to_string()));
92        }
93        // Attach our registry to the ctx so nested dry-run dispatch
94        // (today: `when`) can perform the same name-oracle check and
95        // stays symmetric with `FsExecutor`.
96        let nested_ctx = ExecCtx {
97            vars: ctx.vars,
98            pack_root: ctx.pack_root,
99            workspace: ctx.workspace,
100            platform: ctx.platform,
101            registry: Some(&self.registry),
102            pack_type_registry: ctx.pack_type_registry,
103            visited_meta: ctx.visited_meta,
104            // feat-m6-1: propagate the scheduler handle unchanged.
105            scheduler: ctx.scheduler,
106        };
107        dispatch_plan(action, &nested_ctx)
108    }
109}
110
111/// Dry-run dispatch table keyed by [`Action`] variant. Kept as a free
112/// function (not a method) so the planner struct stays a thin registry
113/// wrapper and the per-variant logic remains colocated with the other
114/// `plan_*` helpers in this module. The `match` is exhaustive across the
115/// seven Tier-1 action kinds returned by [`Action::name`]; any unknown
116/// name has already been rejected by [`PlanExecutor::execute`], so no
117/// fallback arm is needed.
118fn dispatch_plan(action: &Action, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
119    match action {
120        Action::Symlink(s) => plan_symlink(s, ctx),
121        Action::Unlink(u) => plan_unlink(u, ctx),
122        Action::Env(e) => plan_env(e, ctx),
123        Action::Mkdir(m) => plan_mkdir(m, ctx),
124        Action::Rmdir(r) => plan_rmdir(r, ctx),
125        Action::Require(r) => plan_require(r, ctx),
126        Action::When(w) => plan_when(w, ctx),
127        Action::Exec(x) => plan_exec(x, ctx),
128    }
129}
130
131/// Expand a string field, wrapping expansion errors with field context.
132fn expand_field(raw: &str, env: &VarEnv, field: &'static str) -> Result<String, ExecError> {
133    expand(raw, env).map_err(|source| ExecError::VarExpand { field, source })
134}
135
136/// Convert an expanded string into a [`PathBuf`], rejecting empty paths.
137fn require_path(expanded: String) -> Result<PathBuf, ExecError> {
138    if expanded.is_empty() {
139        return Err(ExecError::InvalidPath(expanded));
140    }
141    Ok(PathBuf::from(expanded))
142}
143
144pub(crate) fn plan_symlink(args: &SymlinkArgs, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
145    let src = require_path(expand_field(&args.src, ctx.vars, "symlink.src")?)?;
146    let dst = require_path(expand_field(&args.dst, ctx.vars, "symlink.dst")?)?;
147    let result = classify_symlink(&src, &dst);
148    Ok(ExecStep {
149        action_name: Cow::Borrowed(ACTION_SYMLINK),
150        result,
151        details: StepKind::Symlink {
152            src,
153            dst,
154            kind: args.kind,
155            backup: args.backup,
156            normalize: args.normalize,
157        },
158    })
159}
160
161fn classify_symlink(src: &Path, dst: &Path) -> ExecResult {
162    match std::fs::symlink_metadata(dst) {
163        Ok(meta) if meta.file_type().is_symlink() => match std::fs::read_link(dst) {
164            Ok(target) if target == src => ExecResult::AlreadySatisfied,
165            _ => ExecResult::WouldPerformChange,
166        },
167        _ => ExecResult::WouldPerformChange,
168    }
169}
170
171pub(crate) fn plan_unlink(args: &UnlinkArgs, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
172    let dst = require_path(expand_field(&args.dst, ctx.vars, "unlink.dst")?)?;
173    // Only a symlink at `dst` is considered actionable — anything else
174    // (absent, regular file, directory) reports AlreadySatisfied so a
175    // misdirected teardown never destroys operator-managed content.
176    let result = match std::fs::symlink_metadata(&dst) {
177        Ok(meta) if meta.file_type().is_symlink() => ExecResult::WouldPerformChange,
178        _ => ExecResult::AlreadySatisfied,
179    };
180    Ok(ExecStep {
181        action_name: Cow::Borrowed(ACTION_UNLINK),
182        result,
183        details: StepKind::Unlink { dst },
184    })
185}
186
187pub(crate) fn plan_env(args: &EnvArgs, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
188    let value = expand_field(&args.value, ctx.vars, "env.value")?;
189    let result = classify_env(&args.name, &value, ctx.vars);
190    Ok(ExecStep {
191        action_name: Cow::Borrowed(ACTION_ENV),
192        result,
193        details: StepKind::Env { name: args.name.clone(), value, scope: args.scope },
194    })
195}
196
197fn classify_env(name: &str, value: &str, vars: &VarEnv) -> ExecResult {
198    match vars.get(name) {
199        Some(existing) if existing == value => ExecResult::AlreadySatisfied,
200        _ => ExecResult::WouldPerformChange,
201    }
202}
203
204pub(crate) fn plan_mkdir(args: &MkdirArgs, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
205    let path = require_path(expand_field(&args.path, ctx.vars, "mkdir.path")?)?;
206    let result =
207        if path.is_dir() { ExecResult::AlreadySatisfied } else { ExecResult::WouldPerformChange };
208    Ok(ExecStep {
209        action_name: Cow::Borrowed(ACTION_MKDIR),
210        result,
211        details: StepKind::Mkdir { path, mode: args.mode.clone() },
212    })
213}
214
215pub(crate) fn plan_rmdir(args: &RmdirArgs, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
216    let path = require_path(expand_field(&args.path, ctx.vars, "rmdir.path")?)?;
217    let result =
218        if path.exists() { ExecResult::WouldPerformChange } else { ExecResult::AlreadySatisfied };
219    Ok(ExecStep {
220        action_name: Cow::Borrowed(ACTION_RMDIR),
221        result,
222        details: StepKind::Rmdir { path, backup: args.backup, force: args.force },
223    })
224}
225
226pub(crate) fn plan_require(spec: &RequireSpec, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
227    let satisfied = evaluate_combiner(&spec.combiner, ctx)?;
228    let outcome =
229        if satisfied { PredicateOutcome::Satisfied } else { PredicateOutcome::Unsatisfied };
230    let result = classify_require(satisfied, spec.on_fail)?;
231    Ok(ExecStep {
232        action_name: Cow::Borrowed(ACTION_REQUIRE),
233        result,
234        details: StepKind::Require { outcome, on_fail: spec.on_fail },
235    })
236}
237
238/// Map a `(satisfied, on_fail)` pair to an [`ExecResult`].
239///
240/// `satisfied == true` always reports [`ExecResult::AlreadySatisfied`] — a
241/// require block performs no work; it asserts. An unsatisfied predicate
242/// under `on_fail: error` short-circuits to [`ExecError::RequireFailed`];
243/// `skip` and `warn` both yield [`ExecResult::NoOp`]. The warn/skip
244/// distinction is preserved in [`StepKind::Require::on_fail`] for audit.
245fn classify_require(satisfied: bool, on_fail: RequireOnFail) -> Result<ExecResult, ExecError> {
246    if satisfied {
247        return Ok(ExecResult::AlreadySatisfied);
248    }
249    match on_fail {
250        RequireOnFail::Error => {
251            Err(ExecError::RequireFailed { detail: "combiner evaluated to false".to_string() })
252        }
253        RequireOnFail::Skip | RequireOnFail::Warn => Ok(ExecResult::NoOp),
254    }
255}
256
257fn evaluate_combiner(combiner: &Combiner, ctx: &ExecCtx<'_>) -> Result<bool, ExecError> {
258    match combiner {
259        Combiner::AllOf(list) => {
260            for p in list {
261                if !evaluate(p, ctx)? {
262                    return Ok(false);
263                }
264            }
265            Ok(true)
266        }
267        Combiner::AnyOf(list) => {
268            for p in list {
269                if evaluate(p, ctx)? {
270                    return Ok(true);
271                }
272            }
273            Ok(false)
274        }
275        Combiner::NoneOf(list) => {
276            for p in list {
277                if evaluate(p, ctx)? {
278                    return Ok(false);
279                }
280            }
281            Ok(true)
282        }
283    }
284}
285
286pub(crate) fn plan_when(spec: &WhenSpec, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
287    let branch_taken = evaluate_when_gate(spec, ctx)?;
288    let nested_steps = if branch_taken { plan_nested(&spec.actions, ctx)? } else { Vec::new() };
289    let result = if branch_taken { ExecResult::WouldPerformChange } else { ExecResult::NoOp };
290    Ok(ExecStep {
291        action_name: Cow::Borrowed(ACTION_WHEN),
292        result,
293        details: StepKind::When { branch_taken, nested_steps },
294    })
295}
296
297pub(crate) fn plan_nested(
298    actions: &[Action],
299    ctx: &ExecCtx<'_>,
300) -> Result<Vec<ExecStep>, ExecError> {
301    // Nested planning re-applies the registry name-oracle check so nested
302    // actions receive the same `UnknownAction` taxonomy as the top-level
303    // dispatch. When `ctx.registry` is absent (direct helper invocation
304    // in tests that bypassed `PlanExecutor`), we skip the membership
305    // check — the call sites that construct `ExecCtx` without a registry
306    // are responsible for their own sanitisation.
307    actions
308        .iter()
309        .map(|a| {
310            if let Some(reg) = ctx.registry {
311                if reg.get(a.name()).is_none() {
312                    return Err(ExecError::UnknownAction(a.name().to_string()));
313                }
314            }
315            dispatch_plan(a, ctx)
316        })
317        .collect()
318}
319
320pub(crate) fn plan_exec(spec: &ExecSpec, ctx: &ExecCtx<'_>) -> Result<ExecStep, ExecError> {
321    let cwd = expand_optional_path(spec.cwd.as_deref(), ctx.vars, "exec.cwd")?;
322    let cmdline = build_exec_cmdline(spec, ctx.vars)?;
323    Ok(ExecStep {
324        action_name: Cow::Borrowed(ACTION_EXEC),
325        result: ExecResult::WouldPerformChange,
326        details: StepKind::Exec { cmdline, cwd, on_fail: spec.on_fail, shell: spec.shell },
327    })
328}
329
330fn expand_optional_path(
331    raw: Option<&str>,
332    env: &VarEnv,
333    field: &'static str,
334) -> Result<Option<PathBuf>, ExecError> {
335    match raw {
336        Some(s) => {
337            let expanded = expand_field(s, env, field)?;
338            Ok(Some(require_path(expanded)?))
339        }
340        None => Ok(None),
341    }
342}
343
344/// Build a display command line for an [`ExecSpec`], expanding every arg.
345///
346/// The returned string is informational only — the wet-run executor will
347/// reconstruct argv from the typed [`ExecSpec`] fields rather than parsing
348/// this back. Keeping the display separate means authors see the same
349/// quoted form regardless of platform shell quirks.
350fn build_exec_cmdline(spec: &ExecSpec, env: &VarEnv) -> Result<String, ExecError> {
351    match (spec.shell, &spec.cmd, &spec.cmd_shell) {
352        (false, Some(argv), None) => join_argv(argv, env),
353        (true, None, Some(line)) => expand_field(line, env, "exec.cmd_shell"),
354        _ => Err(ExecError::ExecInvalid(
355            "exec requires cmd (shell=false) XOR cmd_shell (shell=true)".to_string(),
356        )),
357    }
358}
359
360fn join_argv(argv: &[String], env: &VarEnv) -> Result<String, ExecError> {
361    let mut parts = Vec::with_capacity(argv.len());
362    for a in argv {
363        parts.push(expand_field(a, env, "exec.cmd")?);
364    }
365    Ok(parts.join(" "))
366}
367
368// Silence clippy about the `ExecOnFail` import being behind the ExecSpec re-
369// export path; kept explicit for readability of generated docs.
370#[allow(dead_code)]
371const _: Option<ExecOnFail> = None;