1use crate::{Spec, SpecCommand};
2use once_cell::sync::Lazy;
3use tera::Tera;
4
5pub fn render_help(spec: &Spec, cmd: &SpecCommand, long: bool) -> String {
6 let mut ctx = tera::Context::new();
7 ctx.insert("spec", spec);
8 ctx.insert("cmd", cmd);
9 ctx.insert("long", &long);
10 let template = if long {
11 "spec_template_long.tera"
12 } else {
13 "spec_template_short.tera"
14 };
15 TERA.render(template, &ctx).unwrap().trim().to_string() + "\n"
16}
17
18static TERA: Lazy<Tera> = Lazy::new(|| {
19 let mut tera = Tera::default();
20
21 #[rustfmt::skip]
22 tera.add_raw_templates([
23 ("spec_template_short.tera", include_str!("templates/spec_template_short.tera")),
24 ("spec_template_long.tera", include_str!("templates/spec_template_long.tera")),
25 ]).unwrap();
26
27 tera
37});
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42 use insta::assert_snapshot;
43
44 #[test]
45 fn test_render_help_with_env() {
46 let spec = crate::spec! { r#"
47bin "testcli"
48flag "--color" env="MYCLI_COLOR" help="Enable color output"
49flag "--verbose" env="MYCLI_VERBOSE" help="Verbose output"
50flag "--debug" help="Debug mode"
51 "# }
52 .unwrap();
53
54 assert_snapshot!(render_help(&spec, &spec.cmd, false), @r"
55 Usage: testcli [FLAGS]
56
57 Flags:
58 --color Enable color output [env: MYCLI_COLOR]
59 --verbose Verbose output [env: MYCLI_VERBOSE]
60 --debug Debug mode
61 ");
62
63 assert_snapshot!(render_help(&spec, &spec.cmd, true), @r"
64 Usage: testcli [FLAGS]
65
66 Flags:
67 --color
68 Enable color output
69 [env: MYCLI_COLOR]
70 --verbose
71 Verbose output
72 [env: MYCLI_VERBOSE]
73 --debug
74 Debug mode
75 ");
76 }
77
78 #[test]
79 fn test_render_help_with_arg_env() {
80 let spec = crate::spec! { r#"
81bin "testcli"
82arg "<input>" env="MY_INPUT" help="Input file"
83arg "<output>" env="MY_OUTPUT" help="Output file"
84arg "<extra>" help="Extra arg without env"
85arg "[default]" help="Arg with default value" default="default value"
86 "# }
87 .unwrap();
88
89 assert_snapshot!(render_help(&spec, &spec.cmd, false), @r"
90 Usage: testcli <ARGS>…
91
92 Arguments:
93 <input> Input file [env: MY_INPUT]
94 <output> Output file [env: MY_OUTPUT]
95 <extra> Extra arg without env
96 [default] Arg with default value (default: default value)
97 ");
98
99 assert_snapshot!(render_help(&spec, &spec.cmd, true), @r"
100 Usage: testcli <ARGS>…
101
102 Arguments:
103 <input>
104 Input file
105 [env: MY_INPUT]
106 <output>
107 Output file
108 [env: MY_OUTPUT]
109 <extra>
110 Extra arg without env
111 [default]
112 Arg with default value
113 (default: default value)
114 ");
115 }
116}