Skip to main content

dodot_lib/render/
mod.rs

1//! Rendering infrastructure for dodot output.
2//!
3//! Wraps standout-render to provide a consistent rendering pipeline
4//! across all commands. The theme and templates are defined here;
5//! the CLI layer just picks an [`OutputMode`].
6
7use standout_render::{render_with_output, OutputMode, Renderer, Theme};
8
9use crate::Result;
10
11/// The dodot colour theme, defined in YAML for readability.
12///
13/// Style names are semantic — templates reference them by name,
14/// and the theme adapts to terminal capabilities automatically.
15const THEME_YAML: &str = r#"
16pack-name:
17  bold: true
18  fg: blue
19
20filename:
21  fg: white
22
23handler-symbol:
24  bold: true
25  fg: yellow
26
27description:
28  dim: true
29
30deployed:
31  fg: green
32
33pending:
34  fg: magenta
35
36error:
37  fg: red
38  bold: true
39
40broken:
41  fg: red
42
43stale:
44  fg: yellow
45
46warning:
47  fg: yellow
48
49message:
50  fg: cyan
51
52dim:
53  dim: true
54
55header:
56  bold: true
57
58dry-run:
59  fg: yellow
60  italic: true
61
62conflict-banner:
63  fg: white
64  bg: red
65  bold: true
66
67conflict-header:
68  fg: white
69  bg: red
70  bold: true
71
72conflict-target:
73  fg: red
74  bold: true
75
76conflict-pack:
77  fg: red
78
79conflict-hint:
80  dim: true
81
82ignored-pack:
83  dim: true
84  italic: true
85
86group-banner-deployed:
87  fg: green
88  bold: true
89
90group-banner-pending:
91  fg: yellow
92  bold: true
93
94group-banner-error:
95  fg: red
96  bold: true
97
98group-banner-ignored:
99  dim: true
100  bold: true
101
102# Tutorial prompt question text. The interactive `dodot tutorial`
103# uses inquire for the prompt UI; this style is mirrored by hand into
104# its `RenderConfig` (see `tutorial.rs::tutorial_render_config`). Keep
105# attributes here in sync with that function so users have one place
106# to change the look.
107tutorial-prompt:
108  italic: true
109
110# CLI help tags. The hand-written --help text in `dodot-cli/src/help/`
111# uses these alongside the semantic tags above. Mirror standout's
112# default help theme so the look matches the rest of dodot's output:
113#   item    — bold (command names, option flags)
114#   desc    — plain (descriptions next to items)
115#   usage   — plain (the usage line)
116#   example — plain (example blocks)
117#   about   — plain (intro / about text)
118item:
119  bold: true
120desc: {}
121usage: {}
122example: {}
123about: {}
124"#;
125
126// ── Templates ───────────────────────────────────────────────────
127
128/// Status / up / down — pack-level output with file listings.
129///
130/// Per-item errors are surfaced as `[N]` markers next to the status label;
131/// their bodies render in a dedicated `Errors:` section at the bottom so
132/// the per-file columns stay single-line and aligned regardless of how
133/// long an individual error message is.
134pub const TEMPLATE_PACK_STATUS: &str = include_str!("../templates/pack-status.jinja");
135
136/// List — just pack names.
137pub const TEMPLATE_LIST: &str = include_str!("../templates/list.jinja");
138
139/// Simple message output (init, fill, adopt, addignore).
140pub const TEMPLATE_MESSAGE: &str = include_str!("../templates/message.jinja");
141
142/// Probe — deployment map, data-dir tree, summary. Branches on the
143/// `kind` field of the serialized result.
144pub const TEMPLATE_PROBE: &str = include_str!("../templates/probe.jinja");
145
146// ── Tutorial step templates ─────────────────────────────────────
147//
148// One per step of the interactive tutorial. The CLI driver renders
149// the appropriate template before each prompt.
150
151pub const TEMPLATE_TUTORIAL_INTRO: &str = include_str!("../templates/tutorial/intro.jinja");
152pub const TEMPLATE_TUTORIAL_CHECK_ROOT: &str =
153    include_str!("../templates/tutorial/check_root.jinja");
154pub const TEMPLATE_TUTORIAL_PICK_PACK: &str = include_str!("../templates/tutorial/pick_pack.jinja");
155pub const TEMPLATE_TUTORIAL_NO_PACKS: &str = include_str!("../templates/tutorial/no_packs.jinja");
156pub const TEMPLATE_TUTORIAL_SHOW_STATUS: &str =
157    include_str!("../templates/tutorial/show_status.jinja");
158pub const TEMPLATE_TUTORIAL_ANNOTATE_STATUS: &str =
159    include_str!("../templates/tutorial/annotate_status.jinja");
160pub const TEMPLATE_TUTORIAL_CONCEPT_TARGETS: &str =
161    include_str!("../templates/tutorial/concept_targets.jinja");
162pub const TEMPLATE_TUTORIAL_CONCEPT_SHELL: &str =
163    include_str!("../templates/tutorial/concept_shell.jinja");
164pub const TEMPLATE_TUTORIAL_DRY_RUN: &str = include_str!("../templates/tutorial/dry_run.jinja");
165pub const TEMPLATE_TUTORIAL_REAL_UP: &str = include_str!("../templates/tutorial/real_up.jinja");
166pub const TEMPLATE_TUTORIAL_OUTRO: &str = include_str!("../templates/tutorial/outro.jinja");
167
168/// Pairs of `(name, body)` for every tutorial step template.
169///
170/// `render_tutorial_step` looks up the body by name and renders
171/// against a fresh theme each call — no shared `Renderer` is
172/// retained, since each tutorial run renders fewer than a dozen
173/// templates and the per-call cost is negligible.
174pub const TUTORIAL_STEP_TEMPLATES: &[(&str, &str)] = &[
175    ("tutorial.intro", TEMPLATE_TUTORIAL_INTRO),
176    ("tutorial.check_root", TEMPLATE_TUTORIAL_CHECK_ROOT),
177    ("tutorial.pick_pack", TEMPLATE_TUTORIAL_PICK_PACK),
178    ("tutorial.no_packs", TEMPLATE_TUTORIAL_NO_PACKS),
179    ("tutorial.show_status", TEMPLATE_TUTORIAL_SHOW_STATUS),
180    (
181        "tutorial.annotate_status",
182        TEMPLATE_TUTORIAL_ANNOTATE_STATUS,
183    ),
184    (
185        "tutorial.concept_targets",
186        TEMPLATE_TUTORIAL_CONCEPT_TARGETS,
187    ),
188    ("tutorial.concept_shell", TEMPLATE_TUTORIAL_CONCEPT_SHELL),
189    ("tutorial.dry_run", TEMPLATE_TUTORIAL_DRY_RUN),
190    ("tutorial.real_up", TEMPLATE_TUTORIAL_REAL_UP),
191    ("tutorial.outro", TEMPLATE_TUTORIAL_OUTRO),
192];
193
194/// Render a tutorial step template with the dodot theme.
195///
196/// `mode` controls colour output: `OutputMode::Term` for ANSI in a
197/// real terminal, `OutputMode::Text` for tests / non-TTY.
198pub fn render_tutorial_step<T: serde::Serialize>(
199    step: &str,
200    data: &T,
201    mode: OutputMode,
202) -> Result<String> {
203    let body = TUTORIAL_STEP_TEMPLATES
204        .iter()
205        .find_map(|(name, body)| (*name == step).then_some(*body))
206        .ok_or_else(|| crate::DodotError::Other(format!("unknown tutorial template: {step}")))?;
207
208    let theme = create_theme();
209    render_with_output(body, data, &theme, mode)
210        .map_err(|e| crate::DodotError::Other(format!("tutorial render: {e}")))
211}
212
213// ── Renderer ────────────────────────────────────────────────────
214
215/// Create the dodot theme from the embedded YAML definition.
216pub fn create_theme() -> Theme {
217    Theme::from_yaml(THEME_YAML).expect("built-in theme YAML must be valid")
218}
219
220/// Create a pre-compiled renderer with all dodot templates registered.
221pub fn create_renderer() -> Renderer {
222    let theme = create_theme();
223    let mut renderer = Renderer::new(theme).expect("renderer creation must succeed");
224    renderer
225        .add_template("pack-status", TEMPLATE_PACK_STATUS)
226        .unwrap();
227    renderer.add_template("list", TEMPLATE_LIST).unwrap();
228    renderer.add_template("message", TEMPLATE_MESSAGE).unwrap();
229    renderer.add_template("probe", TEMPLATE_PROBE).unwrap();
230    renderer
231}
232
233/// Render a template with the given data and output mode.
234///
235/// For JSON mode, serializes the data directly (not through the
236/// template) to produce machine-readable output.
237pub fn render<T: serde::Serialize>(
238    template_name: &str,
239    data: &T,
240    mode: OutputMode,
241) -> Result<String> {
242    if matches!(mode, OutputMode::Json) {
243        return serde_json::to_string_pretty(data)
244            .map_err(|e| crate::DodotError::Other(format!("JSON serialization failed: {e}")));
245    }
246
247    let theme = create_theme();
248    let template = match template_name {
249        "pack-status" => TEMPLATE_PACK_STATUS,
250        "list" => TEMPLATE_LIST,
251        "message" => TEMPLATE_MESSAGE,
252        "probe" => TEMPLATE_PROBE,
253        other => {
254            return Err(crate::DodotError::Other(format!(
255                "unknown template: {other}"
256            )))
257        }
258    };
259
260    render_with_output(template, data, &theme, mode)
261        .map_err(|e| crate::DodotError::Other(format!("render failed: {e}")))
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn theme_parses_without_error() {
270        let _theme = create_theme();
271    }
272
273    #[test]
274    fn renderer_creates_with_all_templates() {
275        let _renderer = create_renderer();
276    }
277
278    #[test]
279    fn render_pack_status_text_mode() {
280        use serde::Serialize;
281
282        #[derive(Serialize)]
283        struct Data {
284            message: Option<String>,
285            dry_run: bool,
286            packs: Vec<Pack>,
287        }
288        #[derive(Serialize)]
289        struct Pack {
290            name: String,
291            files: Vec<File>,
292        }
293        #[derive(Serialize)]
294        struct File {
295            name: String,
296            symbol: String,
297            description: String,
298            status: String,
299            status_label: String,
300        }
301
302        let data = Data {
303            message: None,
304            dry_run: false,
305            packs: vec![Pack {
306                name: "vim".into(),
307                files: vec![File {
308                    name: "vimrc".into(),
309                    symbol: "➞".into(),
310                    description: "~/.vimrc".into(),
311                    status: "deployed".into(),
312                    status_label: "deployed".into(),
313                }],
314            }],
315        };
316
317        let output = render("pack-status", &data, OutputMode::Text).unwrap();
318        assert!(output.contains("vim"));
319        assert!(output.contains("vimrc"));
320        assert!(output.contains("deployed"));
321    }
322
323    #[test]
324    fn all_tutorial_templates_render_in_text_mode() {
325        // Every tutorial step template must parse and render with a
326        // populated context — this catches Jinja-syntax mistakes at
327        // build time rather than mid-tutorial.
328        use crate::commands::tutorial::{TutorialCtx, TutorialPack};
329
330        let ctx = TutorialCtx {
331            dotfiles_root: "/home/example/dotfiles".into(),
332            via: "DOTFILES_ROOT env var".into(),
333            packs: vec![
334                TutorialPack {
335                    name: "vim".into(),
336                    kind: "config only".into(),
337                    recommended: true,
338                },
339                TutorialPack {
340                    name: "zsh".into(),
341                    kind: "config + shell".into(),
342                    recommended: false,
343                },
344            ],
345            chosen_pack: Some("vim".into()),
346            chosen_pack_kind: Some("config only".into()),
347            status_output: Some("(rendered status would go here)".into()),
348            dry_run_output: Some("(dry-run output)".into()),
349            up_output: Some("(up output)".into()),
350            shell_integration: Some(crate::commands::tutorial::ShellIntegration {
351                shell_kind: "zsh".into(),
352                rc_path: "~/.zshrc".into(),
353                rc_path_abs: std::path::PathBuf::new(),
354                line_present: false,
355                eval_line: r#"eval "$(dodot init-sh)""#.into(),
356            }),
357            eval_line: r#"eval "$(dodot init-sh)""#.into(),
358            ..Default::default()
359        };
360
361        for (name, _) in TUTORIAL_STEP_TEMPLATES {
362            let out = render_tutorial_step(name, &ctx, OutputMode::Text)
363                .unwrap_or_else(|e| panic!("template {name} failed: {e}"));
364            assert!(!out.is_empty(), "template {name} produced empty output");
365        }
366    }
367
368    #[test]
369    fn json_mode_produces_json() {
370        use serde::Serialize;
371
372        #[derive(Serialize)]
373        struct Data {
374            name: String,
375        }
376
377        let data = Data {
378            name: "test".into(),
379        };
380
381        let output = render("list", &data, OutputMode::Json).unwrap();
382        assert!(output.contains("\"name\""));
383        assert!(output.contains("\"test\""));
384    }
385}