Skip to main content

sim_cli/
help.rs

1//! The help text: one translation key per line (`cli-help-<command>-<n>`, see `i18n/en.ftl`), so that a line of the file
2//! is a line of the text, and the commands' parts can be printed alone.
3
4use sim_core::Translations;
5
6/// Where a line is wrapped, in characters.
7const WIDTH: usize = 100;
8/// The column an option's description starts in.
9const COLUMN: usize = 30;
10
11/// The commands, in the order of the overview.
12pub(super) const COMMANDS: [&str; 27] = [
13    "list",
14    "run",
15    "analyze",
16    "sweep",
17    "optimise",
18    "search",
19    "transmission",
20    "compare-kinematics",
21    "verdicts",
22    "sensitivity",
23    "step",
24    "bode",
25    "tuning",
26    "margins",
27    "tune",
28    "modes",
29    "workspace",
30    "replay",
31    "fit",
32    "identify",
33    "check-dataset",
34    "compare",
35    "stop",
36    "accuracy",
37    "report",
38    "fmu",
39    "parameters",
40];
41
42/// The topics beside the commands: the options every command takes, the path formats and the units.
43const TOPICS: [&str; 3] = ["options", "paths", "units"];
44
45/// `text` in lines of at most `WIDTH` characters, the first behind `first`, the others behind blanks as wide.
46fn wrap(first: &str, text: &str) -> Vec<String> {
47    // What fits stays as written: a line may be aligned by hand.
48    if first.chars().count() + text.chars().count() <= WIDTH {
49        return vec![format!("{first}{text}")];
50    }
51    let rest = " ".repeat(first.chars().count());
52    let mut lines: Vec<String> = Vec::new();
53    for word in text.split_whitespace() {
54        match lines.last_mut() {
55            Some(line) if line.chars().count() + 1 + word.chars().count() <= WIDTH => {
56                line.push(' ');
57                line.push_str(word);
58            }
59            Some(_) => lines.push(format!("{rest}{word}")),
60            None => lines.push(format!("{first}{word}")),
61        }
62    }
63    lines
64}
65
66/// The lines `prefix-1`, `prefix-2`, ... of the translation. An option line (`--option ARG  what it does`) comes in two
67/// columns, any other line as it is, indented.
68fn lines(tr: &Translations, prefix: &str) -> Vec<String> {
69    let texts = (1..).map(|n| format!("{prefix}-{n}")).take_while(|key| tr.has(key));
70    let mut out = Vec::new();
71    for key in texts {
72        let text = tr.tr(&key);
73        match text.split_once("  ").filter(|_| text.starts_with("--")) {
74            Some((option, what)) if option.chars().count() < COLUMN - 2 => {
75                out.extend(wrap(&format!("  {option:<width$}", width = COLUMN - 2), what));
76            }
77            Some((option, what)) => {
78                out.push(format!("  {option}"));
79                out.extend(wrap(&" ".repeat(COLUMN), what));
80            }
81            None => out.extend(wrap("  ", text)),
82        }
83    }
84    out
85}
86
87/// The help of one command: its usage line, what it does and its options.
88fn command(tr: &Translations, name: &str) -> Vec<String> {
89    let mut out = lines(tr, &format!("cli-help-{name}"));
90    if !out.is_empty() {
91        // The usage line stands at the margin, what the command does under it.
92        out[0] = out[0].trim_start().to_string();
93        out.insert(1, format!("  {}", tr.tr(&format!("cli-help-brief-{name}"))));
94    }
95    out
96}
97
98/// Every command with a few words on what it does, and where to find more.
99fn overview(tr: &Translations) -> Vec<String> {
100    let mut out: Vec<String> = lines(tr, "cli-help-overview").iter().map(|l| l.trim_start().to_string()).collect();
101    for name in COMMANDS {
102        out.extend(wrap(&format!("  {name:<20}"), tr.tr(&format!("cli-help-brief-{name}"))));
103    }
104    out.push(String::new());
105    out.extend(lines(tr, "cli-help-more").iter().map(|l| l.trim_start().to_string()));
106    out
107}
108
109/// The help for `topic`: a command, one of `TOPICS`, or (none) the overview; `None` for a word that is none of these.
110pub(super) fn text(tr: &Translations, topic: Option<&str>) -> Option<String> {
111    let body = match topic {
112        None => overview(tr),
113        Some(name) if COMMANDS.contains(&name) => command(tr, name),
114        Some(name) if TOPICS.contains(&name) => lines(tr, &format!("cli-help-{name}")),
115        Some(_) => return None,
116    };
117    Some(body.join("\n"))
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use sim_machines::{LANGUAGES, MACHINES};
124
125    fn texts(lang: &str) -> Translations {
126        super::super::texts(lang, MACHINES[0])
127    }
128
129    /// Every command and topic has a help in both languages, no line is wider than 100 characters, and the German has
130    /// the lines of the English (a line of one without the other is a gap).
131    #[test]
132    fn every_command_has_help_in_both_languages_within_100_columns() {
133        for lang in LANGUAGES {
134            let tr = texts(lang);
135            for topic in COMMANDS.iter().chain(&TOPICS) {
136                let help = text(&tr, Some(topic)).unwrap_or_default();
137                assert!(help.lines().count() > 1, "{lang} {topic}: {help}");
138                assert!(!help.contains("cli-help"), "{lang} {topic}: a key without its text");
139                assert!(help.lines().all(|l| l.chars().count() <= WIDTH), "{lang} {topic}: {help}");
140            }
141            let overview = text(&tr, None).unwrap();
142            assert!(!overview.contains("cli-help"), "{lang}: {overview}");
143            assert!(overview.lines().all(|l| l.chars().count() <= WIDTH), "{lang}: {overview}");
144            assert!(COMMANDS.iter().all(|c| overview.contains(c)), "{lang}: every command is in the overview");
145        }
146        let (en, de) = (texts("en"), texts("de"));
147        // Per key, so that wrapping does not matter: as many lines, and the same option first on each option line.
148        let keys = |tr: &Translations, name: &str| -> Vec<String> {
149            (1..)
150                .map(|n| format!("cli-help-{name}-{n}"))
151                .take_while(|key| tr.has(key))
152                .map(|key| tr.tr(&key).split_whitespace().next().unwrap_or("").to_string())
153                .map(|word| if word.starts_with("--") { word } else { String::new() })
154                .collect()
155        };
156        for name in COMMANDS.iter().chain(&TOPICS) {
157            assert_eq!(keys(&en, name), keys(&de, name), "{name}: the same lines and options in both languages");
158        }
159        assert!(text(&en, Some("no-such-command")).is_none());
160    }
161
162    /// The help of a command names every option its parser accepts, and the help of the options every option all commands
163    /// take (a misspelt option is refused, so an option the help leaves out could not be found): the options of the
164    /// parser and the help cannot drift apart.
165    #[test]
166    fn the_help_names_every_option_the_parser_takes() {
167        let tr = texts("en");
168        for name in COMMANDS {
169            let help = text(&tr, Some(name)).unwrap();
170            for option in super::super::command_options(Some(name)) {
171                let named = help.split(|c: char| !(c.is_alphanumeric() || c == '-')).any(|word| word == *option);
172                assert!(named, "{name}: {option} is not in\n{help}");
173            }
174        }
175        let common = text(&tr, Some("options")).unwrap();
176        for option in super::super::COMMON {
177            assert!(common.contains(option), "{option} is not in\n{common}");
178        }
179    }
180}