1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
trait FixStyle {
    fn fix_style(&self) -> String;
    fn fix_style_left(&self) -> String;
    fn fix_style_right(&self) -> String;
}
impl<'a, S: AsRef<str>> FixStyle for S {
    fn fix_style(&self) -> String {
        let msg = self.as_ref();
        if msg.trim().is_empty() {
            String::new()
        } else {
            format!("\n{}\n", msg.trim())
        }
    }
    fn fix_style_left(&self) -> String {
        let msg = self.as_ref();
        if msg.trim().is_empty() {
            String::new()
        } else {
            format!("\n{}", msg.trim())
        }
    }
    fn fix_style_right(&self) -> String {
        let msg = self.as_ref();
        if msg.trim().is_empty() {
            String::new()
        } else {
            format!("{}\n", msg.trim())
        }
    }
}

impl Helps {
    /// `-h/--help`
    pub fn version(&self) -> &str {
        self.version.as_str()
    }
    /// `Main`
    pub fn help(&self) -> String {
        self.help_cmd(&None)
    }
    /// `Cmd`
    pub fn help_cmd(&self, cmd_name: &Option<String>) -> String {
        dbln!(
            "{:?}\n{:?}\n\n{:?},\n\n{:?}\n\n{:?}",
            cmd_name,
            self.cmd_infos,
            self.cmd_usages,
            self.cmd_options,
            self.cmd_args
        );
        let info = &self.cmd_infos[cmd_name];
        let usages = &self.cmd_usages[cmd_name];
        let options = &self.cmd_options[cmd_name];
        let args = self.cmd_args.get(cmd_name).map(|s| s.as_str()).unwrap_or(
            "",
        );
        let main_sub_cmds = if cmd_name.is_some() {
            ""
        } else {
            &self.sub_cmds
        };
        format!(
            r#"{}{}{}{}{}{}{}"#,
            info.fix_style(),
            self.author.fix_style_right(),
            self.addrs.fix_style_right(),
            usages.fix_style(),
            options.fix_style(),
            args.fix_style(),
            main_sub_cmds.fix_style()
        )
    }
}

///**`Helps`**
#[derive(Debug, Default)]
pub struct Helps {
    /// `-v/--version`  "name version"
    pub version: String,
    /// `INFO`
    pub cmd_infos: Map<Option<String>, String>,
    /// `AUTHOR`
    pub author: String,
    /// `ADDRESS`
    pub addrs: String,
    /// `USAGE`
    pub cmd_usages: Map<Option<String>, String>,
    /// `OPTIONS`
    pub cmd_options: Map<Option<String>, String>,
    /// `ARGS`
    pub cmd_args: Map<Option<String>, String>,
    pub sub_cmds: String,
}

/// **`Helper`**
#[derive(Debug, Default)]
pub struct Helper {
    is_built: bool,
    // info
    name: String,
    version: String,
    authors: Vec<(String, String)>, // (name,email)
    addrs: Vec<(String, String)>, // (addr_name,addr)
    desc: String,
    // env_vars
    current_exe: Option<String>,
    current_dir: Option<String>,
    home_dir: Option<String>,
    temp_dir: String,
    //  current_cmd
    current_cmd: Option<String>, //main is None
    current_cmd_sort_key: Option<String>,
    // args_len
    args_len:usize,
    helps: Helps,
}

impl Helper {
    /// name
    pub fn name(&self) -> &String {
        &self.name
    }
    /// version
    pub fn version(&self) -> &String {
        &self.version
    }
    /// description
    pub fn desc(&self) -> &String {
        &self.desc
    }
    /// name, email
    pub fn authors(&self) -> &Vec<(String, String)> {
        &self.authors
    }
    /// url_name, url
    pub fn addrs(&self) -> &Vec<(String, String)> {
        &self.addrs
    }
}

impl Helper {
    pub fn current_cmd(&self) -> Option<&String> {
        self.current_cmd.as_ref()
    }
    pub fn current_cmd_str(&self) -> Option<&str> {
        self.current_cmd.as_ref().map(|s| s.as_str())
    }
    pub fn current_cmd_ref(&self) -> &Option<String> {
        &self.current_cmd
    }
    pub fn current_exe(&self) -> Option<&String> {
        self.current_exe.as_ref()
    }
    pub fn current_dir(&self) -> Option<&String> {
        self.current_dir.as_ref()
    }
    pub fn home_dir(&self) -> Option<&String> {
        self.home_dir.as_ref()
    }
    pub fn temp_dir(&self) -> &String {
        &self.temp_dir
    }
    /**
    You can do something if the length of arguments satisfys a condition.
    
    Example: Print the help message when args.len() is 0.

    ```none
    let helper= {
        ...
    };
    if helper.args_len() == 0 
    {
        helper.help_exit(0);
    }
    ```
    */
    pub fn args_len(&self)->&usize {
        &self.args_len
    }
    pub fn as_helps(&self) -> &Helps {
        &self.helps
    }
    pub fn as_mut_helps(&mut self) -> &mut Helps {
        &mut self.helps
    }
}

impl Helper {
    /// exit with the `status`
    pub fn exit(&self, status: i32) {
        exit(status);
    }
    /// `format!("{}  {}", self.name(), self.version())`
    pub fn ver(&self) -> &String {
        &self.helps.version
    }
    /// print ver(`self.ver`) message and exit with the `status`
    pub fn ver_exit(&self, status: i32) {
        println!("{}", self.ver().trim());
        exit(status);
    }
    /// `format!("ERROR:\n  {}\n\n", error)`
    pub fn err<E>(&self, error: E) -> String
    where
        E: AsRef<str> + Display,
    {
        format!("ERROR:\n   {}\n\n", error)
    }
    /// print error(`self.err(error)`) message to `stderr` and exit with the `status`
    pub fn err_exit<E>(&self, error: E, status: i32)
    where
        E: AsRef<str> + Display,
    {
        self.err_line_print(&self.err(error), statics::error_line_color_get());
        exit(status);
    }
    /// print error message line(2) with Red color(fg)
    #[inline]
    pub fn err_line_print(&self, msg: &str, line_color: u16) {
        for (i, line) in msg.trim().lines().enumerate() {
            if i == 1 {
                let mut t = term::stderr().unwrap();
                t.fg(line_color).unwrap();
                write!(t, "{}", line).unwrap();
                t.reset().unwrap();
            } else {
                errln!("{}", line);
            }
        }
    }
    /// main's help mesage
    pub fn help(&self) -> String {
        self.helps.help()
    }
    /// print main's help message and exit with the `status`
    pub fn help_exit(&self, status: i32) {
        println!("{}", self.help().trim());
        exit(status);
    }
    /// `self.err(error) + self.help()`
    pub fn help_err<E>(&self, error: E) -> String
    where
        E: AsRef<str> + Display,
    {
        self.err(error) + &self.help()
    }
    /// print error and help message(`self.help_err(error)`) to `stderr` and exit with the `status`
    pub fn help_err_exit<E>(&self, error: E, status: i32)
    where
        E: AsRef<str> + Display,
    {
        self.err_line_print(&self.help_err(error), statics::error_line_color_get());
        exit(status);
    }
    /// get sub_command's help message
    pub fn help_cmd(&self, cmd_name: &Option<String>) -> String {
        self.helps.help_cmd(cmd_name)
    }
    /// print sub_command's help message and exit with the `status`
    pub fn help_cmd_exit(&self, cmd_name: &Option<String>, status: i32) {
        println!("{}", self.helps.help_cmd(cmd_name).trim());
        exit(status);
    }
    /// `self.err(error) + self.help_cmd(cmd_name)`
    pub fn help_cmd_err<E>(&self, cmd_name: &Option<String>, error: E) -> String
    where
        E: AsRef<str> + Display,
    {
        self.err(error) + &self.helps.help_cmd(cmd_name)
    }
    /// print error and sub_command's help message to `stderr`,s exit with the `status`
    pub fn help_cmd_err_exit<E>(&self, cmd_name: &Option<String>, error: E, status: i32)
    where
        E: AsRef<str> + Display,
    {
        self.err_line_print(
            &self.help_cmd_err(cmd_name, error),
            statics::error_line_color_get(),
        );
        exit(status);
    }
}