Skip to main content

pitchfork_cli/
template.rs

1//! Tera template rendering for pitchfork.toml configuration fields.
2//!
3//! Allows `run`, `env` values, `hooks.*`, the readiness fields (`ready_cmd`,
4//! `ready_http`, `ready_port`, `ready_output`), and the health check fields
5//! (`health_cmd`, `health_http`, `health_port`) to use Tera templates like
6//! `{{ daemons.redis.ports[0] }}` to reference computed values from other daemons.
7//!
8//! Templates are resolved level-by-level along the dependency order: each level
9//! can reference daemons from previous levels (which have already started and
10//! had their ports resolved).
11
12use crate::daemon_id::DaemonId;
13use crate::pitchfork_toml::PitchforkTomlDaemon;
14use crate::settings::settings;
15use indexmap::IndexMap;
16use std::collections::HashMap;
17use std::path::PathBuf;
18
19// ---------------------------------------------------------------------------
20// DaemonTemplateState
21// ---------------------------------------------------------------------------
22
23/// Resolved state of a daemon available for template rendering.
24#[derive(Debug, Clone)]
25pub struct DaemonTemplateState {
26    pub ports: Vec<u16>,
27    pub id: String,
28    pub name: String,
29    pub namespace: String,
30    pub slug: Option<String>,
31    /// Hostname the proxy routes to this daemon, without the TLD.
32    pub host: Option<String>,
33    pub dir: PathBuf,
34    /// The `url` the daemon declares, still a template.
35    pub declared_url: Option<String>,
36}
37
38impl DaemonTemplateState {
39    fn port(&self) -> Option<u16> {
40        self.ports.first().copied()
41    }
42
43    /// The URL to hand out for this daemon: the proxy's when it serves the
44    /// daemon, otherwise the one the daemon declares, rendered with its own
45    /// port. `None` when neither exists or the declared one doesn't render.
46    fn url(&self) -> Option<String> {
47        self.url_with(&settings())
48    }
49
50    fn url_with(&self, settings: &crate::settings::Settings) -> Option<String> {
51        crate::proxy::build_proxy_url(self.host.as_deref(), settings)
52            .or_else(|| self.render_declared_url())
53    }
54
55    fn render_declared_url(&self) -> Option<String> {
56        let template = self.declared_url.as_deref()?;
57        let mut tera = new_tera();
58        let mut ctx = tera::Context::new();
59        ctx.insert("port", &self.port());
60        ctx.insert("ports", &self.ports);
61        ctx.insert("name", &self.name);
62        ctx.insert("namespace", &self.namespace);
63        ctx.insert("id", &self.id);
64        ctx.insert("slug", &self.slug);
65        ctx.insert("host", &self.host);
66        ctx.insert("dir", &self.dir.to_string_lossy());
67        let rendered = tera
68            .add_raw_template("url", template)
69            .and_then(|()| tera.render("url", &ctx));
70        match rendered {
71            Ok(url) => Some(url),
72            Err(_) => {
73                // Neither the template nor the error goes in the log: a declared
74                // url can carry credentials, and a render error may quote it.
75                log::warn!("daemon {}: cannot render its declared url", self.id);
76                None
77            }
78        }
79    }
80}
81
82// ---------------------------------------------------------------------------
83// TemplateContext
84// ---------------------------------------------------------------------------
85
86/// Context for rendering Tera templates in pitchfork.toml fields.
87pub struct TemplateContext {
88    self_state: DaemonTemplateState,
89    daemon_states: HashMap<String, DaemonTemplateState>,
90    /// Rendered environment variables for the current daemon, exposed as `env`
91    /// in templates (e.g. `{{ env.GRAM_HOST }}`). Set via [`set_env`] after env
92    /// values have been rendered, so it is `None` during env-value rendering
93    /// itself (preventing self-reference cycles).
94    env: Option<IndexMap<String, String>>,
95}
96
97impl TemplateContext {
98    /// Build a template context for a daemon.
99    ///
100    /// - `id`: the daemon being rendered
101    /// - `daemon_config`: its pitchfork.toml config
102    /// - `resolved_daemons`: map of daemon ID -> resolved ports from previous levels
103    /// - `daemon_configs`: the full PitchforkToml.daemons map for looking up dir/slug
104    pub fn new(
105        id: &DaemonId,
106        daemon_config: &PitchforkTomlDaemon,
107        resolved_daemons: &HashMap<DaemonId, Vec<u16>>,
108        daemon_configs: &IndexMap<DaemonId, PitchforkTomlDaemon>,
109    ) -> Self {
110        let global_slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
111        // Deriving a hostname reads configuration and walks the project's
112        // checkouts. With the proxy off there is no URL to render either way,
113        // so `{{ host }}` and `{{ url }}` are null and the work is skipped.
114        let proxy_enabled = settings().proxy.enable;
115        let host_of = |id: &DaemonId, config: &PitchforkTomlDaemon| {
116            proxy_enabled
117                .then(|| crate::proxy::hostname::host_for_daemon(id, Some(config), &global_slugs))
118                .flatten()
119        };
120        let effective_user = daemon_config.effective_user();
121        let dir = crate::ipc::batch::resolve_daemon_dir(
122            daemon_config.dir.as_deref(),
123            daemon_config.path.as_deref(),
124            effective_user.as_deref(),
125        );
126
127        // The port the daemon is configured for. The supervisor settles the final
128        // one after rendering, so it can differ when the port is bumped; `$PORT`
129        // always has the final one.
130        let self_ports = daemon_config
131            .port
132            .as_ref()
133            .map(|p| p.expect.clone())
134            .unwrap_or_default();
135        let self_state = DaemonTemplateState {
136            ports: self_ports,
137            id: id.qualified(),
138            name: id.name().to_string(),
139            namespace: id.namespace().to_string(),
140            slug: crate::pitchfork_toml::PitchforkToml::find_slug_for_daemon_in_registry(
141                id,
142                &global_slugs,
143            ),
144            host: host_of(id, daemon_config),
145            dir,
146            declared_url: daemon_config.url.clone(),
147        };
148
149        // A daemon that is configured without any port (none, or `port = []`) has no resolved ports to
150        // appear in `resolved_daemons`, yet a `url` it declares doesn't need
151        // one. A daemon that has a port but hasn't resolved it (not started, or
152        // in the same level) stays out, so referencing it still fails. Keep it
153        // referenceable, so a dependent renders the same however it was started.
154        let portless_with_url = daemon_configs
155            .iter()
156            .filter(|(dep_id, config)| {
157                config.url.is_some()
158                    && config.port.as_ref().is_none_or(|p| p.expect.is_empty())
159                    && !resolved_daemons.contains_key(*dep_id)
160            })
161            .map(|(dep_id, _)| (dep_id, Vec::new()));
162
163        let mut daemon_states = HashMap::new();
164        for (dep_id, ports) in resolved_daemons
165            .iter()
166            .map(|(dep_id, ports)| (dep_id, ports.clone()))
167            .chain(portless_with_url)
168        {
169            if let Some(config) = daemon_configs.get(dep_id) {
170                let dep_effective_user = config.effective_user();
171                let dep_dir = crate::ipc::batch::resolve_daemon_dir(
172                    config.dir.as_deref(),
173                    config.path.as_deref(),
174                    dep_effective_user.as_deref(),
175                );
176                let state = DaemonTemplateState {
177                    ports,
178                    id: dep_id.qualified(),
179                    name: dep_id.name().to_string(),
180                    namespace: dep_id.namespace().to_string(),
181                    slug: crate::pitchfork_toml::PitchforkToml::find_slug_for_daemon_in_registry(
182                        dep_id,
183                        &global_slugs,
184                    ),
185                    host: host_of(dep_id, config),
186                    dir: dep_dir,
187                    declared_url: config.url.clone(),
188                };
189
190                // Short names are only valid within the current namespace.
191                if dep_id.namespace() == id.namespace() {
192                    daemon_states.insert(dep_id.name().to_string(), state.clone());
193                }
194
195                // Register with qualified key (namespace.name) for all namespaces.
196                daemon_states.insert(qualified_key(dep_id), state);
197            }
198        }
199
200        // Names the daemon chose for its dependencies with `depends = [{ id, as }]`.
201        for (alias, dep_id) in &daemon_config.depends_as {
202            if let Some(state) = daemon_states.get(&qualified_key(dep_id)).cloned() {
203                daemon_states.insert(alias.clone(), state);
204            }
205        }
206
207        Self {
208            self_state,
209            daemon_states,
210            env: None,
211        }
212    }
213
214    /// Set the rendered environment variables to expose as `env` in templates.
215    ///
216    /// Call this **after** rendering env values so that other fields (`run`,
217    /// `hooks`, `ready_*`) can reference `{{ env.X }}` with the final value.
218    pub fn set_env(&mut self, env: IndexMap<String, String>) {
219        self.env = Some(env);
220    }
221
222    /// Convert this context into a Tera Context for rendering.
223    pub fn to_tera_context(&self) -> tera::Context {
224        let mut ctx = tera::Context::new();
225        for (key, value) in self.to_json_map() {
226            ctx.insert(key, &value);
227        }
228        ctx
229    }
230
231    /// The variables templates can reference, as JSON.
232    fn to_json_map(&self) -> serde_json::Map<String, serde_json::Value> {
233        let mut map = serde_json::Map::new();
234        let mut insert = |key: &str, value: serde_json::Value| {
235            map.insert(key.to_string(), value);
236        };
237
238        // Self variables
239        insert("name", self.self_state.name.clone().into());
240        insert("namespace", self.self_state.namespace.clone().into());
241        insert("id", self.self_state.id.clone().into());
242        insert("slug", serde_json::json!(self.self_state.slug));
243        insert("host", serde_json::json!(self.self_state.host));
244        insert("port", serde_json::json!(self.self_state.port()));
245        insert("ports", serde_json::json!(self.self_state.ports));
246        insert(
247            "dir",
248            self.self_state.dir.to_string_lossy().to_string().into(),
249        );
250
251        // Daemons
252        let mut daemons_map = serde_json::Map::new();
253        for (name, state) in &self.daemon_states {
254            if daemons_map.contains_key(name) {
255                continue;
256            }
257            daemons_map.insert(name.clone(), daemon_state_to_json(state));
258        }
259        insert("daemons", serde_json::Value::Object(daemons_map));
260
261        // Settings
262        let s = settings();
263        insert(
264            "settings",
265            serde_json::json!({
266                "proxy": {
267                    "enable": s.proxy.enable,
268                    "tld": s.proxy.tld,
269                    "port": s.proxy.port,
270                    "https": s.proxy.https,
271                }
272            }),
273        );
274
275        // Always expose proxy_url so templates can distinguish an unroutable daemon
276        // via a strict null value instead of an undefined-variable error.
277        let proxy_url = crate::proxy::build_proxy_url(self.self_state.host.as_deref(), &s);
278        insert("proxy_url", serde_json::json!(proxy_url));
279        // `url` is the proxy URL, or the one the daemon declares when the proxy
280        // doesn't serve it. `proxy_url` stays the proxy's alone.
281        insert("url", serde_json::json!(self.self_state.url()));
282
283        // Rendered env for this daemon (set via set_env after env rendering)
284        if let Some(ref env) = self.env {
285            let env: serde_json::Map<String, serde_json::Value> = env
286                .iter()
287                .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
288                .collect();
289            insert("env", serde_json::Value::Object(env));
290        }
291
292        map
293    }
294}
295
296fn daemon_state_to_json(state: &DaemonTemplateState) -> serde_json::Value {
297    serde_json::json!({
298        "port": state.port(),
299        "ports": state.ports,
300        "id": state.id,
301        "name": state.name,
302        "namespace": state.namespace,
303        "slug": state.slug,
304        "host": state.host,
305        "url": state.url(),
306        "dir": state.dir.to_string_lossy(),
307    })
308}
309
310/// Convert a DaemonId into a template key using `namespace.name` format.
311/// E.g. `myproj/redis` -> `myproj.redis`
312fn qualified_key(id: &DaemonId) -> String {
313    format!("{}.{}", id.namespace(), id.name())
314}
315
316// ---------------------------------------------------------------------------
317// Env merge + render helpers
318// ---------------------------------------------------------------------------
319
320/// Merge top-level env with per-daemon env. Per-daemon values win on conflicts.
321pub(crate) fn merge_env(
322    top: Option<&IndexMap<String, String>>,
323    daemon: Option<&IndexMap<String, String>>,
324) -> Option<IndexMap<String, String>> {
325    match (top, daemon) {
326        (None, None) => None,
327        (Some(t), None) => Some(t.clone()),
328        (None, Some(d)) => Some(d.clone()),
329        (Some(t), Some(d)) => {
330            let mut merged = t.clone();
331            for (k, v) in d {
332                merged.insert(k.clone(), v.clone());
333            }
334            Some(merged)
335        }
336    }
337}
338
339/// The daemon's own env with its `env_file` variables underneath: inline `env`
340/// wins over the files, and later files win over earlier ones. Relative paths
341/// resolve from the project directory (the same base as `dir`), and
342/// missing files are skipped so a git-ignored `.env.local` stays optional.
343pub fn daemon_env_with_files(
344    daemon: &PitchforkTomlDaemon,
345) -> Result<Option<IndexMap<String, String>>, RenderError> {
346    if daemon.env_file.is_empty() {
347        return Ok(daemon.env.clone());
348    }
349    let base = daemon
350        .path
351        .as_deref()
352        .and_then(crate::pitchfork_toml::project_dir_for_config);
353    let inline = daemon.env.clone().unwrap_or_default();
354    // Same user as `dir`: the daemon's own, else `settings.supervisor.user`.
355    let user = daemon.effective_user();
356    let mut merged = IndexMap::new();
357    for file in &daemon.env_file {
358        let expanded = crate::env::expand_tilde_for_user(file, user.as_deref());
359        let path = match base.as_deref() {
360            Some(base) => base.join(expanded),
361            None => expanded,
362        };
363        let content = match std::fs::read_to_string(&path) {
364            Ok(content) => content,
365            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
366            Err(e) => {
367                return Err(RenderError::EnvFile {
368                    path,
369                    message: e.to_string(),
370                });
371            }
372        };
373        // `${VAR}` sees everything loaded from earlier files and the inline env, which wins.
374        // Inline goes last because the parser keeps the last value for a repeated key.
375        let outer = merged
376            .iter()
377            .chain(inline.iter())
378            .map(|(k, v)| (k.clone(), v.clone()))
379            .collect::<Vec<_>>();
380        let vars = mise_dotenv::parse(
381            content.strip_prefix('\u{feff}').unwrap_or(&content),
382            true,
383            outer,
384        )
385        .map_err(|e| RenderError::EnvFile {
386            path: path.clone(),
387            message: e.to_string(),
388        })?;
389        merged.extend(vars);
390    }
391    merged.extend(inline);
392    Ok(Some(merged))
393}
394
395/// Merge top-level and per-daemon env, render template values, and return the
396/// rendered env. Used by hook rendering where the daemon config is not mutated.
397///
398/// Env values are rendered with a context that does **not** include `env`
399/// itself, preventing self-reference cycles. Callers that want `{{ env.X }}`
400/// available in subsequent rendering should set the result on the context via
401/// [`TemplateContext::set_env`].
402pub fn render_env(
403    top_env: Option<&IndexMap<String, String>>,
404    daemon_env: Option<&IndexMap<String, String>>,
405    context: &TemplateContext,
406) -> Result<Option<IndexMap<String, String>>, RenderError> {
407    let Some(merged) = merge_env(top_env, daemon_env) else {
408        return Ok(None);
409    };
410    let mut renderer = TemplateRenderer::new(context);
411    let rendered: IndexMap<String, String> = merged
412        .iter()
413        .map(|(k, v)| Ok((k.clone(), renderer.render(v)?)))
414        .collect::<Result<_, _>>()?;
415    Ok(Some(rendered))
416}
417
418// ---------------------------------------------------------------------------
419// Rendering
420// ---------------------------------------------------------------------------
421
422/// Render a Tera template string with the given context.
423///
424/// Returns the rendered string, or an error describing what went wrong.
425/// Fast path: strings without `{{` or `{%` are returned as-is.
426pub fn render_template(template: &str, context: &TemplateContext) -> Result<String, RenderError> {
427    TemplateRenderer::new(context).render(template)
428}
429
430/// Render all template-enabled fields of a daemon config.
431///
432/// Top-level `env` (from `[env]` in pitchfork.toml) is merged into the daemon's
433/// own `env` as defaults — per-daemon values win on key conflicts. Env values
434/// are rendered first (with a context that excludes `env` itself, preventing
435/// self-reference cycles), then the rendered env is exposed as `{{ env.X }}`
436/// for the remaining fields (`run`, `hooks`, `ready_*`).
437///
438/// Modifies the config in place. Returns the first error encountered from
439/// non-hook fields (`run`, `env`, `ready_*`). Hook template errors are
440/// logged as warnings and the hook is set to `None` — hooks are re-rendered
441/// at fire time via `fire_hook`, so pre-rendered hook strings are unused.
442pub fn render_daemon_templates(
443    config: &mut PitchforkTomlDaemon,
444    context: &mut TemplateContext,
445    top_env: Option<&IndexMap<String, String>>,
446) -> Result<(), RenderError> {
447    render_daemon_templates_with(config, context, top_env, runs_under_mise)
448}
449
450/// [`render_daemon_templates`] with the decision whether `mise x` will wrap the
451/// daemon given, so a test does not depend on a mise installation.
452fn render_daemon_templates_with(
453    config: &mut PitchforkTomlDaemon,
454    context: &mut TemplateContext,
455    top_env: Option<&IndexMap<String, String>>,
456    runs_under_mise: impl Fn(&PitchforkTomlDaemon) -> bool,
457) -> Result<(), RenderError> {
458    // Phase 1: merge top-level env into the daemon's env (per-daemon wins) and
459    // render env values. `env` is NOT yet in the context, so env values cannot
460    // reference {{ env.* }} (preventing cycles). render_env builds its own
461    // short-lived renderer without env in scope.
462    let daemon_env = daemon_env_with_files(config)?;
463    let rendered_env = render_env(top_env, daemon_env.as_ref(), context)?;
464    config.env = rendered_env;
465    // Phase 2: expose the rendered env on the context as the authoritative
466    // state, so to_tera_context() (used by TemplateRenderer::new) includes it.
467    if let Some(ref env) = config.env {
468        context.set_env(env.clone());
469    }
470
471    let mut renderer = TemplateRenderer::new(context);
472
473    // In the argv form each argument is rendered on its own, so a rendered
474    // value with spaces stays one argument.
475    //
476    // A command that `mise x` wraps can reference variables only mise knows, such
477    // as `{{ vars.name }}` from mise.toml. When this context cannot render such a
478    // command it is passed through unrendered, and `mise x` renders it with this
479    // context plus its own, or reports the error itself.
480    let mut defers_to_mise = None;
481    let mut deferred = false;
482    config.run = config.run.try_map(|arg| match renderer.render(arg) {
483        Ok(rendered) => Ok(rendered),
484        Err(err) => {
485            if *defers_to_mise.get_or_insert_with(|| runs_under_mise(config)) {
486                deferred = true;
487                Ok(arg.to_string())
488            } else {
489                Err(err)
490            }
491        }
492    })?;
493    config.deferred_template_context =
494        deferred.then(|| serde_json::Value::Object(context.to_json_map()).to_string());
495
496    if let Some(ref hooks) = config.hooks {
497        let rendered = crate::config_types::PitchforkTomlHooks {
498            on_ready: hooks
499                .on_ready
500                .as_deref()
501                .and_then(|t| renderer.render(t).ok()),
502            on_fail: hooks
503                .on_fail
504                .as_deref()
505                .and_then(|t| renderer.render(t).ok()),
506            on_retry: hooks
507                .on_retry
508                .as_deref()
509                .and_then(|t| renderer.render(t).ok()),
510            on_stop: hooks
511                .on_stop
512                .as_deref()
513                .and_then(|t| renderer.render(t).ok()),
514            on_exit: hooks
515                .on_exit
516                .as_deref()
517                .and_then(|t| renderer.render(t).ok()),
518            on_output: hooks.on_output.as_ref().and_then(|hook| {
519                renderer
520                    .render(&hook.run)
521                    .ok()
522                    .map(|run| crate::config_types::OnOutputHook {
523                        run,
524                        filter: hook.filter.clone(),
525                        regex: hook.regex.clone(),
526                        debounce: hook.debounce.clone(),
527                    })
528            }),
529        };
530        config.hooks = Some(rendered);
531    }
532
533    if let Some(ref cmd) = config.ready_cmd {
534        config.ready_cmd = Some(crate::pitchfork_toml::ReadyCmd {
535            // Each argument of the argv form is rendered on its own and stays
536            // one argument, as for `run`.
537            run: cmd.run.try_map(|arg| renderer.render(arg))?,
538            timeout: cmd.timeout,
539        });
540    }
541
542    if let Some(ref hc) = config.health_cmd {
543        config.health_cmd = Some(crate::pitchfork_toml::HealthCmd {
544            // As for `ready_cmd`, each argument of the argv form is rendered
545            // on its own and stays one argument.
546            run: hc.run.try_map(|arg| renderer.render(arg))?,
547            interval: hc.interval,
548            timeout: hc.timeout,
549            retries: hc.retries,
550        });
551    }
552
553    if let Some(ref http) = config.health_http {
554        let mut http = http.clone();
555        http.url = renderer.render(&http.url)?;
556        config.health_http = Some(http);
557    }
558
559    if let Some(ref health_port) = config.health_port
560        && let Some(ref template) = health_port.template
561    {
562        let rendered = renderer.render(template)?;
563        let port = rendered
564            .trim()
565            .parse::<u16>()
566            .ok()
567            .filter(|&p| p > 0)
568            .ok_or_else(|| RenderError::InvalidPort {
569                field: "health_port",
570                template: template.clone(),
571                rendered: rendered.clone(),
572            })?;
573        config.health_port = Some(crate::config_types::HealthPort {
574            port: Some(port),
575            template: None,
576            interval: health_port.interval,
577            retries: health_port.retries,
578            timeout: health_port.timeout,
579        });
580    }
581
582    if let Some(ref output) = config.ready_output {
583        let pattern = renderer.render(&output.pattern)?;
584        config.ready_output = Some(crate::config_types::ReadyOutput {
585            pattern,
586            timeout: output.timeout,
587        });
588    }
589
590    if let Some(ref http) = config.ready_http {
591        let mut http = http.clone();
592        http.url = renderer.render(&http.url)?;
593        config.ready_http = Some(http);
594    }
595
596    if let Some(ref ready_port) = config.ready_port
597        && let Some(ref template) = ready_port.template
598    {
599        let rendered = renderer.render(template)?;
600        let port = rendered
601            .trim()
602            .parse::<u16>()
603            .ok()
604            .filter(|&p| p > 0)
605            .ok_or_else(|| RenderError::InvalidPort {
606                field: "ready_port",
607                template: template.clone(),
608                rendered: rendered.clone(),
609            })?;
610        config.ready_port = Some(crate::config_types::ReadyPort {
611            port: Some(port),
612            template: None,
613            timeout: ready_port.timeout,
614        });
615    }
616
617    Ok(())
618}
619
620/// Environment variable carrying the template context to the `mise x` wrapper of a
621/// daemon whose command it has to finish rendering.
622pub const TEMPLATE_CONTEXT_ENV: &str = "PITCHFORK_TEMPLATE_CONTEXT";
623
624/// Whether `mise x` is meant to wrap this daemon's command, which is what can finish
625/// rendering a command this context could not. Whether the binary can be found is
626/// decided at launch, by the supervisor that looks for it: a client rendering the
627/// command may not see the same installation.
628fn runs_under_mise(config: &PitchforkTomlDaemon) -> bool {
629    mise_enabled(config)
630}
631
632/// Whether the daemon asks for `mise x`: its own `mise`, else `general.mise` as set
633/// for the daemon's project. A start that does not go through a client's request
634/// must use this same answer, or it would launch without the wrapper that a
635/// deferred command needs.
636pub(crate) fn mise_enabled(config: &PitchforkTomlDaemon) -> bool {
637    config.mise.unwrap_or_else(|| {
638        let dir = crate::ipc::batch::resolve_config_base_dir(config.path.as_deref());
639        crate::settings::Settings::load_from_dir(&dir).general.mise
640    })
641}
642
643fn contains_template_syntax(template: &str) -> bool {
644    template.contains("{{") || template.contains("{%") || template.contains("{#")
645}
646
647fn new_tera() -> tera::Tera {
648    let mut tera = tera::Tera::default();
649    tera.register_filter(
650        "default",
651        |value: &tera::Value,
652         kwargs: tera::Kwargs,
653         _: &tera::State|
654         -> tera::TeraResult<tera::Value> {
655            let default_val = kwargs.must_get::<tera::Value>("value")?;
656            let boolean = kwargs.get::<bool>("boolean")?.unwrap_or_default();
657            if value.is_undefined() || value.is_none() || (boolean && !value.is_truthy()) {
658                Ok(default_val)
659            } else {
660                Ok(value.clone())
661            }
662        },
663    );
664    tera
665}
666
667struct TemplateRenderer {
668    tera: tera::Tera,
669    context: tera::Context,
670    next_template_id: usize,
671}
672
673impl TemplateRenderer {
674    fn new(context: &TemplateContext) -> Self {
675        Self {
676            tera: new_tera(),
677            context: context.to_tera_context(),
678            next_template_id: 0,
679        }
680    }
681
682    fn add_template(&mut self, template: &str) -> Result<String, RenderError> {
683        let template_name = format!("config_{}", self.next_template_id);
684        self.next_template_id += 1;
685        self.tera
686            .add_raw_template(&template_name, template)
687            .map_err(|e| RenderError::TemplateSyntax {
688                template: template.to_string(),
689                source: e,
690            })?;
691        Ok(template_name)
692    }
693
694    fn render(&mut self, template: &str) -> Result<String, RenderError> {
695        if !contains_template_syntax(template) {
696            return Ok(template.to_string());
697        }
698
699        let template_name = self.add_template(template)?;
700
701        self.tera
702            .render(&template_name, &self.context)
703            .map_err(|e| RenderError::RenderFailed {
704                template: template.to_string(),
705                source: e,
706            })
707    }
708}
709
710// ---------------------------------------------------------------------------
711// RenderError
712// ---------------------------------------------------------------------------
713
714#[derive(Debug, thiserror::Error)]
715pub enum RenderError {
716    #[error("template syntax error in {template:?}: {source}")]
717    TemplateSyntax {
718        template: String,
719        source: tera::Error,
720    },
721    #[error("template render failed for {template:?}: {source}")]
722    RenderFailed {
723        template: String,
724        source: tera::Error,
725    },
726    #[error("failed to load env_file {}: {message}", path.display())]
727    EnvFile {
728        path: std::path::PathBuf,
729        message: String,
730    },
731    #[error(
732        "{field} template {template:?} rendered to {rendered:?}, expected a port number (1-65535)"
733    )]
734    InvalidPort {
735        field: &'static str,
736        template: String,
737        rendered: String,
738    },
739}
740
741// ---------------------------------------------------------------------------
742// Tests
743// ---------------------------------------------------------------------------
744
745#[cfg(test)]
746mod tests {
747    use super::*;
748
749    fn make_daemon_config(run: &str) -> PitchforkTomlDaemon {
750        PitchforkTomlDaemon {
751            run: run.into(),
752            ..Default::default()
753        }
754    }
755
756    fn make_context_with_daemon(name: &str, ports: Vec<u16>) -> TemplateContext {
757        let id = DaemonId::new("myproj", name);
758        let config = make_daemon_config("echo");
759        let mut resolved = HashMap::new();
760        resolved.insert(id.clone(), ports);
761        let mut configs = IndexMap::new();
762        configs.insert(id.clone(), make_daemon_config("echo"));
763        TemplateContext::new(
764            &DaemonId::new("myproj", "self"),
765            &config,
766            &resolved,
767            &configs,
768        )
769    }
770
771    #[test]
772    fn test_no_template_passthrough() {
773        let ctx = make_context_with_daemon("redis", vec![6379]);
774        assert_eq!(render_template("hello world", &ctx).unwrap(), "hello world");
775    }
776
777    #[test]
778    fn test_self_variables() {
779        let id = DaemonId::new("myproj", "api");
780        let config = make_daemon_config("echo");
781        let ctx = TemplateContext::new(&id, &config, &HashMap::new(), &IndexMap::new());
782
783        assert_eq!(render_template("{{ name }}", &ctx).unwrap(), "api");
784        assert_eq!(render_template("{{ namespace }}", &ctx).unwrap(), "myproj");
785        assert_eq!(render_template("{{ id }}", &ctx).unwrap(), "myproj/api");
786    }
787
788    #[test]
789    fn test_daemon_port_reference() {
790        let ctx = make_context_with_daemon("redis", vec![6379]);
791        assert_eq!(
792            render_template("{{ daemons.redis.port }}", &ctx).unwrap(),
793            "6379"
794        );
795    }
796
797    #[test]
798    fn test_daemon_ports_array() {
799        let ctx = make_context_with_daemon("redis", vec![6379, 6380]);
800        assert_eq!(
801            render_template("{{ daemons.redis.ports[0] }}", &ctx).unwrap(),
802            "6379"
803        );
804        assert_eq!(
805            render_template("{{ daemons.redis.ports[1] }}", &ctx).unwrap(),
806            "6380"
807        );
808    }
809
810    #[test]
811    fn test_daemon_qualified_name() {
812        let ctx = make_context_with_daemon("redis", vec![6379]);
813        assert_eq!(
814            render_template("{{ daemons[\"myproj.redis\"].port }}", &ctx).unwrap(),
815            "6379"
816        );
817    }
818
819    #[test]
820    fn test_depends_as_gives_local_name() {
821        let self_id = DaemonId::new("app", "api");
822        let other_id = DaemonId::new("search-bd9126f3bbca47d", "app");
823        let mut self_config = make_daemon_config("echo");
824        self_config.depends = vec![other_id.clone()];
825        self_config
826            .depends_as
827            .insert("search".to_string(), other_id.clone());
828
829        let mut resolved = HashMap::new();
830        resolved.insert(other_id.clone(), vec![8080]);
831        let mut configs = IndexMap::new();
832        configs.insert(other_id.clone(), make_daemon_config("echo"));
833
834        let ctx = TemplateContext::new(&self_id, &self_config, &resolved, &configs);
835
836        assert_eq!(
837            render_template("{{ daemons.search.port }}", &ctx).unwrap(),
838            "8080"
839        );
840        assert_eq!(
841            render_template("{{ daemons[\"search-bd9126f3bbca47d.app\"].port }}", &ctx).unwrap(),
842            "8080"
843        );
844    }
845
846    #[test]
847    fn test_short_name_only_matches_current_namespace() {
848        let self_id = DaemonId::new("app", "api");
849        let self_config = make_daemon_config("echo");
850        let other_id = DaemonId::new("infra", "redis");
851
852        let mut resolved = HashMap::new();
853        resolved.insert(other_id.clone(), vec![6379]);
854
855        let mut configs = IndexMap::new();
856        configs.insert(other_id.clone(), make_daemon_config("echo"));
857
858        let ctx = TemplateContext::new(&self_id, &self_config, &resolved, &configs);
859
860        assert!(render_template("{{ daemons.redis.port }}", &ctx).is_err());
861        assert_eq!(
862            render_template("{{ daemons[\"infra.redis\"].port }}", &ctx).unwrap(),
863            "6379"
864        );
865    }
866
867    #[test]
868    fn test_settings_reference() {
869        let ctx = make_context_with_daemon("redis", vec![6379]);
870        let result = render_template("{{ settings.proxy.tld }}", &ctx).unwrap();
871        // Default TLD is "localhost"
872        assert_eq!(result, "localhost");
873    }
874
875    #[test]
876    fn test_undefined_variable_error() {
877        let ctx = make_context_with_daemon("redis", vec![6379]);
878        let result = render_template("{{ nonexistent }}", &ctx);
879        assert!(result.is_err());
880    }
881
882    #[test]
883    fn test_comment_only_template_is_parsed() {
884        let ctx = make_context_with_daemon("redis", vec![6379]);
885        assert_eq!(
886            render_template("before{# hidden #}after", &ctx).unwrap(),
887            "beforeafter"
888        );
889    }
890
891    #[test]
892    fn test_proxy_url_is_present_as_null_when_slug_is_missing() {
893        let id = DaemonId::new("myproj", "api");
894        let config = make_daemon_config("echo");
895        let ctx = TemplateContext::new(&id, &config, &HashMap::new(), &IndexMap::new());
896
897        assert_eq!(
898            render_template("{{ proxy_url | default(value=\"none\") }}", &ctx).unwrap(),
899            "none"
900        );
901    }
902
903    /// The daemon being rendered and a daemon it references resolve their
904    /// hostnames the same way, so `{{ host }}` is never populated while
905    /// `{{ daemons.*.host }}` is null — whether or not the proxy is enabled.
906    #[test]
907    fn test_self_and_referenced_hosts_agree() {
908        let id = DaemonId::try_new("myproj", "api").unwrap();
909        let config = PitchforkTomlDaemon {
910            run: "server".into(),
911            port: Some(crate::config_types::PortConfig {
912                expect: vec![3000],
913                ..Default::default()
914            }),
915            ..PitchforkTomlDaemon::default()
916        };
917        let mut configs = IndexMap::new();
918        configs.insert(id.clone(), config.clone());
919        let mut resolved = HashMap::new();
920        resolved.insert(id.clone(), vec![3000]);
921
922        let ctx = TemplateContext::new(&id, &config, &resolved, &configs);
923        assert_eq!(
924            ctx.self_state.host,
925            ctx.daemon_states.get("api").unwrap().host
926        );
927    }
928
929    fn unproxied_with_url(url: &str, expect: Vec<u16>) -> PitchforkTomlDaemon {
930        PitchforkTomlDaemon {
931            run: "server".into(),
932            proxy: Some(crate::config_types::ProxyConfig::Disabled),
933            url: Some(url.to_string()),
934            port: Some(crate::config_types::PortConfig {
935                expect,
936                ..Default::default()
937            }),
938            ..PitchforkTomlDaemon::default()
939        }
940    }
941
942    #[test]
943    fn test_self_port_and_ports() {
944        let id = DaemonId::new("myproj", "api");
945        let config = unproxied_with_url("x", vec![4300, 4301]);
946        let ctx = TemplateContext::new(&id, &config, &HashMap::new(), &IndexMap::new());
947        assert_eq!(render_template("{{ port }}", &ctx).unwrap(), "4300");
948        assert_eq!(render_template("{{ ports[1] }}", &ctx).unwrap(), "4301");
949    }
950
951    #[test]
952    fn test_declared_url_is_used_without_the_proxy() {
953        let id = DaemonId::new("myproj", "cache");
954        let config = unproxied_with_url("redis://127.0.0.1:{{ port }}/0", vec![6380]);
955        let ctx = TemplateContext::new(&id, &config, &HashMap::new(), &IndexMap::new());
956        assert_eq!(
957            render_template("{{ url }}", &ctx).unwrap(),
958            "redis://127.0.0.1:6380/0"
959        );
960        // `proxy_url` stays the proxy's alone.
961        assert_eq!(
962            render_template("{{ proxy_url | default(value=\"none\") }}", &ctx).unwrap(),
963            "none"
964        );
965    }
966
967    #[test]
968    fn test_referenced_declared_url_uses_the_resolved_port() {
969        let me = DaemonId::new("myproj", "web");
970        let cache = DaemonId::new("myproj", "cache");
971        let cache_config = unproxied_with_url("redis://127.0.0.1:{{ port }}/0", vec![6380]);
972        let mut configs = IndexMap::new();
973        configs.insert(cache.clone(), cache_config);
974        // The port was bumped from the configured 6380.
975        let mut resolved = HashMap::new();
976        resolved.insert(cache, vec![6381]);
977
978        let ctx = TemplateContext::new(&me, &make_daemon_config("echo"), &resolved, &configs);
979        assert_eq!(
980            render_template("{{ daemons.cache.url }}", &ctx).unwrap(),
981            "redis://127.0.0.1:6381/0"
982        );
983    }
984
985    #[test]
986    fn test_portless_daemon_with_declared_url_is_referenceable() {
987        let me = DaemonId::new("myproj", "web");
988        let db = DaemonId::new("myproj", "db");
989        let mut db_config = unproxied_with_url("postgres://db.internal/app", vec![]);
990        db_config.port = None;
991        let mut configs = IndexMap::new();
992        configs.insert(db, db_config);
993
994        // Nothing resolved for `db`, as when boot startup drops portless records.
995        let ctx = TemplateContext::new(&me, &make_daemon_config("echo"), &HashMap::new(), &configs);
996        assert_eq!(
997            render_template("{{ daemons.db.url }}", &ctx).unwrap(),
998            "postgres://db.internal/app"
999        );
1000    }
1001
1002    #[test]
1003    fn test_daemon_with_an_empty_port_list_keeps_its_declared_url() {
1004        let me = DaemonId::new("myproj", "web");
1005        let db = DaemonId::new("myproj", "db");
1006        let mut configs = IndexMap::new();
1007        configs.insert(db, unproxied_with_url("postgres://db.internal/app", vec![]));
1008
1009        let ctx = TemplateContext::new(&me, &make_daemon_config("echo"), &HashMap::new(), &configs);
1010        assert_eq!(
1011            render_template("{{ daemons.db.url }}", &ctx).unwrap(),
1012            "postgres://db.internal/app"
1013        );
1014    }
1015
1016    #[test]
1017    fn test_proxy_url_wins_over_a_declared_url() {
1018        let state = DaemonTemplateState {
1019            ports: vec![4300],
1020            id: "myproj/api".into(),
1021            name: "api".into(),
1022            namespace: "myproj".into(),
1023            slug: None,
1024            host: Some("api.myproj".into()),
1025            dir: PathBuf::new(),
1026            declared_url: Some("http://127.0.0.1:{{ port }}".into()),
1027        };
1028        let mut on = (*settings()).clone();
1029        on.proxy.enable = true;
1030        on.proxy.https = false;
1031        on.proxy.port = 7777;
1032        // Pin what the host's config or environment could otherwise change.
1033        on.proxy.tld = "localhost".into();
1034        on.proxy.lan = false;
1035        on.proxy.lan_ip = String::new();
1036        assert_eq!(
1037            state.url_with(&on).as_deref(),
1038            Some("http://api.myproj.localhost:7777")
1039        );
1040        let mut off = on.clone();
1041        off.proxy.enable = false;
1042        assert_eq!(
1043            state.url_with(&off).as_deref(),
1044            Some("http://127.0.0.1:4300")
1045        );
1046    }
1047
1048    #[test]
1049    fn test_unresolved_daemon_with_a_port_stays_undefined() {
1050        let me = DaemonId::new("myproj", "web");
1051        let api = DaemonId::new("myproj", "api");
1052        let mut configs = IndexMap::new();
1053        configs.insert(
1054            api,
1055            unproxied_with_url("http://127.0.0.1:{{ port }}", vec![4300]),
1056        );
1057
1058        let ctx = TemplateContext::new(&me, &make_daemon_config("echo"), &HashMap::new(), &configs);
1059        assert!(render_template("{{ daemons.api.url }}", &ctx).is_err());
1060    }
1061
1062    #[test]
1063    fn test_unrenderable_declared_url_is_null() {
1064        let id = DaemonId::new("myproj", "api");
1065        let config = unproxied_with_url("{{ nope }}", vec![4300]);
1066        let ctx = TemplateContext::new(&id, &config, &HashMap::new(), &IndexMap::new());
1067        assert_eq!(
1068            render_template("{{ url | default(value=\"none\") }}", &ctx).unwrap(),
1069            "none"
1070        );
1071    }
1072
1073    #[test]
1074    fn test_mixed_template_and_literal() {
1075        let ctx = make_context_with_daemon("redis", vec![6379]);
1076        assert_eq!(
1077            render_template("redis://localhost:{{ daemons.redis.port }}/0", &ctx).unwrap(),
1078            "redis://localhost:6379/0"
1079        );
1080    }
1081
1082    #[test]
1083    fn test_render_daemon_templates_run() {
1084        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1085        let mut config = PitchforkTomlDaemon {
1086            run: "redis-cli -p {{ daemons.redis.port }}".into(),
1087            ..Default::default()
1088        };
1089        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1090        assert_eq!(config.run, "redis-cli -p 6379");
1091    }
1092
1093    #[test]
1094    fn test_run_with_unknown_variable_is_deferred_to_mise() {
1095        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1096        let mut config = PitchforkTomlDaemon {
1097            run: "redis-cli -p {{ daemons.redis.port }} {{ vars.greeting | quote }}".into(),
1098            ..Default::default()
1099        };
1100        render_daemon_templates_with(&mut config, &mut ctx, None, |_| true).unwrap();
1101        // The whole command is left for `mise x`, which receives the context.
1102        assert_eq!(
1103            config.run,
1104            "redis-cli -p {{ daemons.redis.port }} {{ vars.greeting | quote }}"
1105        );
1106        let json: serde_json::Value =
1107            serde_json::from_str(config.deferred_template_context.as_ref().unwrap()).unwrap();
1108        assert_eq!(json["daemons"]["redis"]["port"], 6379);
1109        assert_eq!(json["name"], "self");
1110    }
1111
1112    #[test]
1113    fn test_unknown_variable_is_an_error_without_mise() {
1114        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1115        let mut config = PitchforkTomlDaemon {
1116            run: "echo {{ vars.greeting }}".into(),
1117            ..Default::default()
1118        };
1119        // mise is off, so nothing could finish it.
1120        assert!(render_daemon_templates_with(&mut config, &mut ctx, None, |_| false).is_err());
1121        assert!(config.deferred_template_context.is_none());
1122    }
1123
1124    #[test]
1125    fn test_user_declared_context_variable_is_left_alone() {
1126        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1127        let mut config = PitchforkTomlDaemon {
1128            run: "redis-cli -p {{ daemons.redis.port }}".into(),
1129            env: Some(IndexMap::from([(
1130                TEMPLATE_CONTEXT_ENV.to_string(),
1131                "mine".to_string(),
1132            )])),
1133            ..Default::default()
1134        };
1135        render_daemon_templates_with(&mut config, &mut ctx, None, |_| true).unwrap();
1136        // Not a deferral, and the user's own value is untouched.
1137        assert!(config.deferred_template_context.is_none());
1138        assert_eq!(config.env.as_ref().unwrap()[TEMPLATE_CONTEXT_ENV], "mine");
1139    }
1140
1141    #[test]
1142    fn test_known_variables_are_not_deferred() {
1143        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1144        let mut config = PitchforkTomlDaemon {
1145            run: "redis-cli -p {{ daemons.redis.port }}".into(),
1146            ..Default::default()
1147        };
1148        render_daemon_templates_with(&mut config, &mut ctx, None, |_| true).unwrap();
1149        assert_eq!(config.run, "redis-cli -p 6379");
1150        assert!(config.deferred_template_context.is_none());
1151    }
1152
1153    #[test]
1154    fn test_missing_nested_variable_is_deferred_when_env_is_defined() {
1155        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1156        let mut config = PitchforkTomlDaemon {
1157            run: "echo {{ env.MISE_ONLY }}".into(),
1158            env: Some(IndexMap::from([("OWN".to_string(), "x".to_string())])),
1159            ..Default::default()
1160        };
1161        render_daemon_templates_with(&mut config, &mut ctx, None, |_| true).unwrap();
1162        assert_eq!(config.run, "echo {{ env.MISE_ONLY }}");
1163        let json: serde_json::Value =
1164            serde_json::from_str(config.deferred_template_context.as_ref().unwrap()).unwrap();
1165        assert_eq!(json["env"]["OWN"], "x");
1166    }
1167
1168    #[test]
1169    fn test_render_daemon_templates_run_array() {
1170        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1171        let mut config = PitchforkTomlDaemon {
1172            run: crate::pitchfork_toml::RunCommand::Argv(vec![
1173                "redis-cli".into(),
1174                "-p".into(),
1175                "{{ daemons.redis.port }}".into(),
1176                "a b".into(),
1177            ]),
1178            ..Default::default()
1179        };
1180        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1181        // Each argument is rendered on its own and stays one argument.
1182        assert_eq!(
1183            config.run,
1184            crate::pitchfork_toml::RunCommand::Argv(vec![
1185                "redis-cli".into(),
1186                "-p".into(),
1187                "6379".into(),
1188                "a b".into(),
1189            ])
1190        );
1191    }
1192
1193    #[test]
1194    fn test_render_daemon_templates_env() {
1195        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1196        let mut config = PitchforkTomlDaemon {
1197            run: "echo".into(),
1198            env: Some(IndexMap::from([
1199                (
1200                    "DATABASE_URL".to_string(),
1201                    "redis://localhost:{{ daemons.redis.port }}/0".to_string(),
1202                ),
1203                ("STATIC_VAR".to_string(), "unchanged".to_string()),
1204            ])),
1205            ..Default::default()
1206        };
1207        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1208        let env = config.env.unwrap();
1209        assert_eq!(env["DATABASE_URL"], "redis://localhost:6379/0");
1210        assert_eq!(env["STATIC_VAR"], "unchanged");
1211    }
1212
1213    #[test]
1214    fn test_top_level_env_merged_as_defaults() {
1215        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1216        let top_env = IndexMap::from([
1217            ("GRAM_HOST".to_string(), "localhost".to_string()),
1218            (
1219                "GRAM_URL".to_string(),
1220                "redis://{{ daemons.redis.port }}".to_string(),
1221            ),
1222        ]);
1223        let mut config = PitchforkTomlDaemon {
1224            run: "echo".into(),
1225            env: Some(IndexMap::from([(
1226                "GRAM_HOST".to_string(),
1227                "0.0.0.0".to_string(),
1228            )])),
1229            ..Default::default()
1230        };
1231        render_daemon_templates(&mut config, &mut ctx, Some(&top_env)).unwrap();
1232        let env = config.env.unwrap();
1233        // per-daemon wins
1234        assert_eq!(env["GRAM_HOST"], "0.0.0.0");
1235        // top-level default with template rendered
1236        assert_eq!(env["GRAM_URL"], "redis://6379");
1237    }
1238
1239    #[test]
1240    fn test_env_exposed_in_context_for_other_fields() {
1241        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1242        let top_env = IndexMap::from([("GRAM_HOST".to_string(), "localhost".to_string())]);
1243        let mut config = PitchforkTomlDaemon {
1244            run: "echo {{ env.GRAM_HOST }}".into(),
1245            ..Default::default()
1246        };
1247        render_daemon_templates(&mut config, &mut ctx, Some(&top_env)).unwrap();
1248        assert_eq!(config.run, "echo localhost");
1249    }
1250
1251    #[test]
1252    fn test_env_values_cannot_self_reference() {
1253        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1254        let top_env = IndexMap::from([
1255            ("A".to_string(), "value-a".to_string()),
1256            // env is not available while env values are rendered
1257            ("B".to_string(), "{{ env.A }}".to_string()),
1258        ]);
1259        let mut config = PitchforkTomlDaemon {
1260            run: "echo".into(),
1261            ..Default::default()
1262        };
1263        // Rendering env.B references {{ env.A }} which is undefined during
1264        // env-value rendering -> error propagates.
1265        assert!(render_daemon_templates(&mut config, &mut ctx, Some(&top_env)).is_err());
1266    }
1267
1268    #[test]
1269    fn test_render_daemon_templates_on_output_run() {
1270        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1271        let mut config = PitchforkTomlDaemon {
1272            run: "echo".into(),
1273            hooks: Some(crate::config_types::PitchforkTomlHooks {
1274                on_ready: None,
1275                on_fail: None,
1276                on_retry: None,
1277                on_stop: None,
1278                on_exit: None,
1279                on_output: Some(crate::config_types::OnOutputHook {
1280                    run: "curl http://localhost:{{ daemons.redis.port }}".into(),
1281                    filter: Some("ready".to_string()),
1282                    regex: None,
1283                    debounce: None,
1284                }),
1285            }),
1286            ..Default::default()
1287        };
1288
1289        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1290
1291        let hooks = config.hooks.unwrap();
1292        let on_output = hooks.on_output.unwrap();
1293        assert_eq!(on_output.run, "curl http://localhost:6379");
1294        assert_eq!(on_output.filter.as_deref(), Some("ready"));
1295    }
1296
1297    #[test]
1298    fn test_render_daemon_templates_ready_cmd_array_per_argument() {
1299        use crate::config_types::ReadyCmd;
1300        use crate::pitchfork_toml::RunCommand;
1301
1302        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1303        let mut config = PitchforkTomlDaemon {
1304            run: "echo".into(),
1305            ready_cmd: Some(ReadyCmd::new(vec![
1306                "redis-cli".to_string(),
1307                "-p".to_string(),
1308                "{{ daemons.redis.port }}".to_string(),
1309                "ping {{ daemons.redis.port }}".to_string(),
1310            ])),
1311            ..Default::default()
1312        };
1313
1314        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1315
1316        // Each argument is rendered on its own, and a rendered value with a
1317        // space stays one argument.
1318        assert_eq!(
1319            config.ready_cmd.unwrap().run,
1320            RunCommand::Argv(vec![
1321                "redis-cli".to_string(),
1322                "-p".to_string(),
1323                "6379".to_string(),
1324                "ping 6379".to_string(),
1325            ])
1326        );
1327    }
1328
1329    #[test]
1330    fn test_render_daemon_templates_health_cmd_array_per_argument() {
1331        use crate::config_types::HealthCmd;
1332        use crate::pitchfork_toml::RunCommand;
1333
1334        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1335        let mut config = PitchforkTomlDaemon {
1336            run: "echo".into(),
1337            health_cmd: Some(HealthCmd {
1338                run: RunCommand::Argv(vec![
1339                    "redis-cli".to_string(),
1340                    "-p".to_string(),
1341                    "{{ daemons.redis.port }}".to_string(),
1342                    "ping {{ daemons.redis.port }}".to_string(),
1343                ]),
1344                interval: Some(std::time::Duration::from_secs(5)),
1345                ..HealthCmd::default()
1346            }),
1347            ..Default::default()
1348        };
1349
1350        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1351
1352        let health_cmd = config.health_cmd.unwrap();
1353        assert_eq!(
1354            health_cmd.run,
1355            RunCommand::Argv(vec![
1356                "redis-cli".to_string(),
1357                "-p".to_string(),
1358                "6379".to_string(),
1359                "ping 6379".to_string(),
1360            ])
1361        );
1362        assert_eq!(health_cmd.interval, Some(std::time::Duration::from_secs(5)));
1363    }
1364
1365    #[test]
1366    fn test_render_daemon_templates_ready_fields() {
1367        use crate::config_types::{ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort};
1368
1369        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1370        let mut config = PitchforkTomlDaemon {
1371            run: "echo".into(),
1372            ready_cmd: Some(ReadyCmd::new("redis-cli -p {{ daemons.redis.port }} ping")),
1373            ready_output: Some(ReadyOutput::new("listening on {{ daemons.redis.port }}")),
1374            ready_http: Some(ReadyHttp {
1375                url: "http://localhost:{{ daemons.redis.port }}/health".to_string(),
1376                status: vec![200, 401],
1377                timeout: None,
1378            }),
1379            ready_port: Some(ReadyPort::from_template("{{ daemons.redis.port }}")),
1380            ..Default::default()
1381        };
1382
1383        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1384
1385        assert_eq!(
1386            config.ready_cmd.as_ref().unwrap().run,
1387            "redis-cli -p 6379 ping"
1388        );
1389        assert_eq!(
1390            config.ready_output.as_ref().unwrap().pattern,
1391            "listening on 6379"
1392        );
1393        let http = config.ready_http.unwrap();
1394        assert_eq!(http.url, "http://localhost:6379/health");
1395        assert_eq!(http.status, vec![200, 401]);
1396        assert_eq!(config.ready_port, Some(ReadyPort::new(6379)));
1397    }
1398
1399    #[test]
1400    fn test_render_daemon_templates_health_fields() {
1401        use crate::config_types::{HealthCmd, HealthHttp};
1402        use std::time::Duration;
1403
1404        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1405        let mut config = PitchforkTomlDaemon {
1406            run: "echo".into(),
1407            health_cmd: Some(HealthCmd {
1408                run: "redis-cli -p {{ daemons.redis.port }} ping".into(),
1409                interval: Some(Duration::from_secs(10)),
1410                timeout: None,
1411                retries: Some(3),
1412            }),
1413            health_http: Some(HealthHttp {
1414                url: "http://localhost:{{ daemons.redis.port }}/health".to_string(),
1415                status: vec![200],
1416                interval: None,
1417                timeout: Some(Duration::from_secs(5)),
1418                retries: None,
1419            }),
1420            ..Default::default()
1421        };
1422
1423        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1424
1425        let hc = config.health_cmd.unwrap();
1426        assert_eq!(hc.run, "redis-cli -p 6379 ping");
1427        assert_eq!(hc.interval, Some(Duration::from_secs(10)));
1428        assert_eq!(hc.retries, Some(3));
1429        let hh = config.health_http.unwrap();
1430        assert_eq!(hh.url, "http://localhost:6379/health");
1431        assert_eq!(hh.status, vec![200]);
1432        assert_eq!(hh.timeout, Some(Duration::from_secs(5)));
1433    }
1434
1435    #[test]
1436    fn test_render_daemon_templates_ready_port_invalid() {
1437        use crate::config_types::ReadyPort;
1438
1439        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1440        let mut config = PitchforkTomlDaemon {
1441            run: "echo".into(),
1442            ready_port: Some(ReadyPort::from_template("{{ name }}")),
1443            ..Default::default()
1444        };
1445
1446        let err = render_daemon_templates(&mut config, &mut ctx, None).unwrap_err();
1447        assert!(matches!(err, RenderError::InvalidPort { .. }));
1448    }
1449
1450    #[test]
1451    fn test_render_daemon_templates_ready_port_literal_untouched() {
1452        use crate::config_types::ReadyPort;
1453
1454        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1455        let mut config = PitchforkTomlDaemon {
1456            run: "echo".into(),
1457            ready_port: Some(ReadyPort::new(8080)),
1458            ..Default::default()
1459        };
1460
1461        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1462        assert_eq!(config.ready_port, Some(ReadyPort::new(8080)));
1463    }
1464
1465    #[test]
1466    fn test_render_daemon_templates_health_port() {
1467        use crate::config_types::HealthPort;
1468        use std::time::Duration;
1469
1470        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1471        let mut config = PitchforkTomlDaemon {
1472            run: "echo".into(),
1473            health_port: Some(HealthPort {
1474                port: None,
1475                template: Some("{{ daemons.redis.port }}".to_string()),
1476                interval: Some(Duration::from_secs(10)),
1477                retries: Some(3),
1478                timeout: Some(Duration::from_secs(5)),
1479            }),
1480            ..Default::default()
1481        };
1482
1483        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1484        let hp = config.health_port.unwrap();
1485        assert_eq!(hp.port, Some(6379));
1486        assert!(hp.template.is_none());
1487        assert_eq!(hp.interval, Some(Duration::from_secs(10)));
1488        assert_eq!(hp.retries, Some(3));
1489        assert_eq!(hp.timeout, Some(Duration::from_secs(5)));
1490    }
1491
1492    #[test]
1493    fn test_render_daemon_templates_health_port_invalid() {
1494        use crate::config_types::HealthPort;
1495
1496        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1497        let mut config = PitchforkTomlDaemon {
1498            run: "echo".into(),
1499            health_port: Some(HealthPort::from_template("{{ name }}")),
1500            ..Default::default()
1501        };
1502
1503        let err = render_daemon_templates(&mut config, &mut ctx, None).unwrap_err();
1504        assert!(matches!(err, RenderError::InvalidPort { .. }));
1505    }
1506
1507    #[test]
1508    fn test_render_daemon_templates_health_port_literal_untouched() {
1509        use crate::config_types::HealthPort;
1510
1511        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1512        let mut config = PitchforkTomlDaemon {
1513            run: "echo".into(),
1514            health_port: Some(HealthPort::new(8080)),
1515            ..Default::default()
1516        };
1517
1518        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1519        assert_eq!(config.health_port, Some(HealthPort::new(8080)));
1520    }
1521
1522    #[test]
1523    fn test_render_daemon_templates_hook_error_does_not_fail() {
1524        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1525        let mut config = PitchforkTomlDaemon {
1526            run: "echo".into(),
1527            hooks: Some(crate::config_types::PitchforkTomlHooks {
1528                on_ready: Some("{{ nonexistent }}".to_string()),
1529                on_fail: None,
1530                on_retry: None,
1531                on_stop: None,
1532                on_exit: None,
1533                on_output: None,
1534            }),
1535            ..Default::default()
1536        };
1537
1538        // Hook template errors are silently converted to None — daemon still starts
1539        render_daemon_templates(&mut config, &mut ctx, None).unwrap();
1540        let hooks = config.hooks.unwrap();
1541        assert!(hooks.on_ready.is_none());
1542    }
1543
1544    #[test]
1545    fn test_render_daemon_templates_run_error_still_fails() {
1546        let mut ctx = make_context_with_daemon("redis", vec![6379]);
1547        let mut config = PitchforkTomlDaemon {
1548            run: "{{ nonexistent }}".into(),
1549            ..Default::default()
1550        };
1551
1552        // Non-hook template errors still propagate as Err
1553        assert!(render_daemon_templates(&mut config, &mut ctx, None).is_err());
1554    }
1555
1556    #[test]
1557    fn env_file_layers_under_inline_env_and_skips_missing() {
1558        let dir = tempfile::tempdir().unwrap();
1559        std::fs::write(dir.path().join(".env"), "A=file\nB=file\n").unwrap();
1560        std::fs::write(
1561            dir.path().join(".env.local"),
1562            "B=local\nexport C=\"${B}-x\"\n",
1563        )
1564        .unwrap();
1565        let config = PitchforkTomlDaemon {
1566            run: "echo".into(),
1567            env_file: vec![".env".into(), ".env.local".into(), "missing".into()],
1568            env: Some(IndexMap::from([("A".to_string(), "inline".to_string())])),
1569            path: Some(dir.path().join("pitchfork.toml")),
1570            ..Default::default()
1571        };
1572        let env = daemon_env_with_files(&config).unwrap().unwrap();
1573        assert_eq!(env["A"], "inline");
1574        assert_eq!(env["B"], "local");
1575        assert_eq!(env["C"], "local-x");
1576    }
1577
1578    #[test]
1579    fn env_file_later_files_interpolate_earlier_ones() {
1580        let dir = tempfile::tempdir().unwrap();
1581        std::fs::write(dir.path().join("a.env"), "HOST=db\n").unwrap();
1582        std::fs::write(dir.path().join("b.env"), "URL=pg://${HOST}/x\n").unwrap();
1583        let config = PitchforkTomlDaemon {
1584            run: "echo".into(),
1585            env_file: vec!["a.env".into(), "b.env".into()],
1586            path: Some(dir.path().join("pitchfork.toml")),
1587            ..Default::default()
1588        };
1589        let env = daemon_env_with_files(&config).unwrap().unwrap();
1590        assert_eq!(env["URL"], "pg://db/x");
1591    }
1592
1593    #[test]
1594    fn env_file_substitution_prefers_inline_env() {
1595        let dir = tempfile::tempdir().unwrap();
1596        std::fs::write(dir.path().join("a.env"), "HOST=file\n").unwrap();
1597        std::fs::write(dir.path().join("b.env"), "URL=pg://${HOST}\n").unwrap();
1598        let config = PitchforkTomlDaemon {
1599            run: "echo".into(),
1600            env_file: vec!["a.env".into(), "b.env".into()],
1601            env: Some(IndexMap::from([("HOST".to_string(), "inline".to_string())])),
1602            path: Some(dir.path().join("pitchfork.toml")),
1603            ..Default::default()
1604        };
1605        let env = daemon_env_with_files(&config).unwrap().unwrap();
1606        assert_eq!(env["URL"], "pg://inline");
1607    }
1608
1609    #[test]
1610    fn env_file_syntax_error_names_the_file() {
1611        let dir = tempfile::tempdir().unwrap();
1612        std::fs::write(dir.path().join(".env"), "not valid = = =\n").unwrap();
1613        let config = PitchforkTomlDaemon {
1614            run: "echo".into(),
1615            env_file: vec![".env".into()],
1616            path: Some(dir.path().join("pitchfork.toml")),
1617            ..Default::default()
1618        };
1619        let err = daemon_env_with_files(&config).unwrap_err().to_string();
1620        assert!(err.contains(".env"), "{err}");
1621    }
1622}