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/// Git filter installation snippets (`dodot git-show-filters`).
147pub const TEMPLATE_GIT_FILTERS: &str = include_str!("../templates/git-filters.jinja");
148
149/// Dismissed-prompt registry listing (`dodot prompts list`).
150pub const TEMPLATE_PROMPTS_LIST: &str = include_str!("../templates/prompts-list.jinja");
151
152// ── Tutorial step templates ─────────────────────────────────────
153//
154// One per step of the interactive tutorial. The CLI driver renders
155// the appropriate template before each prompt.
156
157pub const TEMPLATE_TUTORIAL_INTRO: &str = include_str!("../templates/tutorial/intro.jinja");
158pub const TEMPLATE_TUTORIAL_CHECK_ROOT: &str =
159    include_str!("../templates/tutorial/check_root.jinja");
160pub const TEMPLATE_TUTORIAL_PICK_PACK: &str = include_str!("../templates/tutorial/pick_pack.jinja");
161pub const TEMPLATE_TUTORIAL_NO_PACKS: &str = include_str!("../templates/tutorial/no_packs.jinja");
162pub const TEMPLATE_TUTORIAL_SHOW_STATUS: &str =
163    include_str!("../templates/tutorial/show_status.jinja");
164pub const TEMPLATE_TUTORIAL_ANNOTATE_STATUS: &str =
165    include_str!("../templates/tutorial/annotate_status.jinja");
166pub const TEMPLATE_TUTORIAL_CONCEPT_TARGETS: &str =
167    include_str!("../templates/tutorial/concept_targets.jinja");
168pub const TEMPLATE_TUTORIAL_CONCEPT_SHELL: &str =
169    include_str!("../templates/tutorial/concept_shell.jinja");
170pub const TEMPLATE_TUTORIAL_DRY_RUN: &str = include_str!("../templates/tutorial/dry_run.jinja");
171pub const TEMPLATE_TUTORIAL_REAL_UP: &str = include_str!("../templates/tutorial/real_up.jinja");
172pub const TEMPLATE_TUTORIAL_OUTRO: &str = include_str!("../templates/tutorial/outro.jinja");
173
174/// Pairs of `(name, body)` for every tutorial step template.
175///
176/// `render_tutorial_step` looks up the body by name and renders
177/// against a fresh theme each call — no shared `Renderer` is
178/// retained, since each tutorial run renders fewer than a dozen
179/// templates and the per-call cost is negligible.
180pub const TUTORIAL_STEP_TEMPLATES: &[(&str, &str)] = &[
181    ("tutorial.intro", TEMPLATE_TUTORIAL_INTRO),
182    ("tutorial.check_root", TEMPLATE_TUTORIAL_CHECK_ROOT),
183    ("tutorial.pick_pack", TEMPLATE_TUTORIAL_PICK_PACK),
184    ("tutorial.no_packs", TEMPLATE_TUTORIAL_NO_PACKS),
185    ("tutorial.show_status", TEMPLATE_TUTORIAL_SHOW_STATUS),
186    (
187        "tutorial.annotate_status",
188        TEMPLATE_TUTORIAL_ANNOTATE_STATUS,
189    ),
190    (
191        "tutorial.concept_targets",
192        TEMPLATE_TUTORIAL_CONCEPT_TARGETS,
193    ),
194    ("tutorial.concept_shell", TEMPLATE_TUTORIAL_CONCEPT_SHELL),
195    ("tutorial.dry_run", TEMPLATE_TUTORIAL_DRY_RUN),
196    ("tutorial.real_up", TEMPLATE_TUTORIAL_REAL_UP),
197    ("tutorial.outro", TEMPLATE_TUTORIAL_OUTRO),
198];
199
200/// Render a tutorial step template with the dodot theme.
201///
202/// `mode` controls colour output: `OutputMode::Term` for ANSI in a
203/// real terminal, `OutputMode::Text` for tests / non-TTY.
204pub fn render_tutorial_step<T: serde::Serialize>(
205    step: &str,
206    data: &T,
207    mode: OutputMode,
208) -> Result<String> {
209    let body = TUTORIAL_STEP_TEMPLATES
210        .iter()
211        .find_map(|(name, body)| (*name == step).then_some(*body))
212        .ok_or_else(|| crate::DodotError::Other(format!("unknown tutorial template: {step}")))?;
213
214    let theme = create_theme();
215    render_with_output(body, data, &theme, mode)
216        .map_err(|e| crate::DodotError::Other(format!("tutorial render: {e}")))
217}
218
219// ── Renderer ────────────────────────────────────────────────────
220
221/// Create the dodot theme from the embedded YAML definition.
222pub fn create_theme() -> Theme {
223    Theme::from_yaml(THEME_YAML).expect("built-in theme YAML must be valid")
224}
225
226/// Create a pre-compiled renderer with all dodot templates registered.
227pub fn create_renderer() -> Renderer {
228    let theme = create_theme();
229    let mut renderer = Renderer::new(theme).expect("renderer creation must succeed");
230    renderer
231        .add_template("pack-status", TEMPLATE_PACK_STATUS)
232        .unwrap();
233    renderer.add_template("list", TEMPLATE_LIST).unwrap();
234    renderer.add_template("message", TEMPLATE_MESSAGE).unwrap();
235    renderer.add_template("probe", TEMPLATE_PROBE).unwrap();
236    renderer
237        .add_template("git-filters", TEMPLATE_GIT_FILTERS)
238        .unwrap();
239    renderer
240        .add_template("prompts-list", TEMPLATE_PROMPTS_LIST)
241        .unwrap();
242    renderer
243}
244
245/// Render a template with the given data and output mode.
246///
247/// For JSON mode, serializes the data directly (not through the
248/// template) to produce machine-readable output.
249pub fn render<T: serde::Serialize>(
250    template_name: &str,
251    data: &T,
252    mode: OutputMode,
253) -> Result<String> {
254    if matches!(mode, OutputMode::Json) {
255        return serde_json::to_string_pretty(data)
256            .map_err(|e| crate::DodotError::Other(format!("JSON serialization failed: {e}")));
257    }
258
259    let theme = create_theme();
260    let template = match template_name {
261        "pack-status" => TEMPLATE_PACK_STATUS,
262        "list" => TEMPLATE_LIST,
263        "message" => TEMPLATE_MESSAGE,
264        "probe" => TEMPLATE_PROBE,
265        "git-filters" => TEMPLATE_GIT_FILTERS,
266        "prompts-list" => TEMPLATE_PROMPTS_LIST,
267        other => {
268            return Err(crate::DodotError::Other(format!(
269                "unknown template: {other}"
270            )))
271        }
272    };
273
274    render_with_output(template, data, &theme, mode)
275        .map_err(|e| crate::DodotError::Other(format!("render failed: {e}")))
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn theme_parses_without_error() {
284        let _theme = create_theme();
285    }
286
287    #[test]
288    fn renderer_creates_with_all_templates() {
289        let _renderer = create_renderer();
290    }
291
292    #[test]
293    fn render_pack_status_text_mode() {
294        use serde::Serialize;
295
296        #[derive(Serialize)]
297        struct Data {
298            message: Option<String>,
299            dry_run: bool,
300            packs: Vec<Pack>,
301        }
302        #[derive(Serialize)]
303        struct Pack {
304            name: String,
305            files: Vec<File>,
306        }
307        #[derive(Serialize)]
308        struct File {
309            name: String,
310            symbol: String,
311            description: String,
312            status: String,
313            status_label: String,
314        }
315
316        let data = Data {
317            message: None,
318            dry_run: false,
319            packs: vec![Pack {
320                name: "vim".into(),
321                files: vec![File {
322                    name: "vimrc".into(),
323                    symbol: "➞".into(),
324                    description: "~/.vimrc".into(),
325                    status: "deployed".into(),
326                    status_label: "deployed".into(),
327                }],
328            }],
329        };
330
331        let output = render("pack-status", &data, OutputMode::Text).unwrap();
332        assert!(output.contains("vim"));
333        assert!(output.contains("vimrc"));
334        assert!(output.contains("deployed"));
335    }
336
337    #[test]
338    fn all_tutorial_templates_render_in_text_mode() {
339        // Every tutorial step template must parse and render with a
340        // populated context — this catches Jinja-syntax mistakes at
341        // build time rather than mid-tutorial.
342        use crate::commands::tutorial::{TutorialCtx, TutorialPack};
343
344        let ctx = TutorialCtx {
345            dotfiles_root: "/home/example/dotfiles".into(),
346            via: "DOTFILES_ROOT env var".into(),
347            packs: vec![
348                TutorialPack {
349                    name: "vim".into(),
350                    kind: "config only".into(),
351                    recommended: true,
352                },
353                TutorialPack {
354                    name: "zsh".into(),
355                    kind: "config + shell".into(),
356                    recommended: false,
357                },
358            ],
359            chosen_pack: Some("vim".into()),
360            chosen_pack_kind: Some("config only".into()),
361            status_output: Some("(rendered status would go here)".into()),
362            dry_run_output: Some("(dry-run output)".into()),
363            up_output: Some("(up output)".into()),
364            shell_integration: Some(crate::commands::tutorial::ShellIntegration {
365                shell_kind: "zsh".into(),
366                rc_path: "~/.zshrc".into(),
367                rc_path_abs: std::path::PathBuf::new(),
368                line_present: false,
369                eval_line: r#"eval "$(dodot init-sh)""#.into(),
370            }),
371            eval_line: r#"eval "$(dodot init-sh)""#.into(),
372            ..Default::default()
373        };
374
375        for (name, _) in TUTORIAL_STEP_TEMPLATES {
376            let out = render_tutorial_step(name, &ctx, OutputMode::Text)
377                .unwrap_or_else(|e| panic!("template {name} failed: {e}"));
378            assert!(!out.is_empty(), "template {name} produced empty output");
379        }
380    }
381
382    #[test]
383    fn json_mode_produces_json() {
384        use serde::Serialize;
385
386        #[derive(Serialize)]
387        struct Data {
388            name: String,
389        }
390
391        let data = Data {
392            name: "test".into(),
393        };
394
395        let output = render("list", &data, OutputMode::Json).unwrap();
396        assert!(output.contains("\"name\""));
397        assert!(output.contains("\"test\""));
398    }
399}