cliproc/
help.rs

1use crate::arg::{Arg, Flag, Raisable};
2
3mod tag {
4    pub const FLAG: &str = "help";
5    pub const SWITCH: char = 'h';
6}
7
8/// A special flag that can have priority over other arguments in command-line
9/// processing.
10#[derive(Debug, PartialEq, Clone)]
11pub struct Help {
12    arg: Flag,
13    text: String,
14}
15
16impl Help {
17    /// Create a new [Help] flag.
18    ///
19    /// By default, it sets the flag's name to "help" and the flag's switch to "h".
20    /// To use a custom flag, use [flag][Help::flag].
21    pub fn new() -> Self {
22        Self {
23            arg: Flag::new(tag::FLAG).switch(tag::SWITCH),
24            text: String::new(),
25        }
26    }
27
28    /// Create a new [Help] flag with informational text `text`.
29    ///
30    /// By default, it sets the flag's name to "help" and the flag's switch to "h".
31    /// To use a custom flag, use [flag][Help::flag].
32    pub fn with<T: AsRef<str>>(text: T) -> Self {
33        Self {
34            arg: Flag::new(tag::FLAG).switch(tag::SWITCH),
35            text: String::from(text.as_ref()),
36        }
37    }
38
39    /// Set the [Help] flag's name to `name`.
40    ///
41    /// Once this is set, any previous switch is removed. To add a switch, use
42    /// [switch][Help::switch].
43    pub fn flag<T: AsRef<str>>(mut self, name: T) -> Self {
44        self.arg = Flag::new(name);
45        self
46    }
47
48    /// Set the [Help] flag's switch to `c`.
49    pub fn switch(mut self, c: char) -> Self {
50        self.arg = self.arg.switch(c);
51        self
52    }
53
54    /// Set the [Help] flag's informational text to `t`.
55    pub fn text<T: AsRef<str>>(mut self, t: T) -> Self {
56        self.text = t.as_ref().to_string();
57        self
58    }
59
60    /// Transform the [Help] flag into its [Arg].
61    pub fn get_arg(&self) -> Arg<Raisable> {
62        match self.arg.get_switch() {
63            Some(c) => Arg::flag(self.arg.get_name()).switch(*c),
64            None => Arg::flag(self.arg.get_name()),
65        }
66    }
67
68    /// Access the [Help] flag's informational text.
69    pub fn get_text(&self) -> &str {
70        self.text.as_ref()
71    }
72}