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
crate::ix!();

pub const SCREEN_WIDTH: usize = 79;
pub const OPT_INDENT:   usize = 2;
pub const MSG_INDENT:   usize = 7;

/**
  | Format a string to be used as group of
  | options in help messages
  | 
  | -----------
  | @param message
  | 
  | Group name (e.g. "RPC server options:")
  | 
  | -----------
  | @return
  | 
  | the formatted string
  |
  */
pub fn help_message_group(message: &str) -> String {
    
    format!{"{}\n\n",message}
}

#[derive(Error, Debug)]
pub enum FormatParagraphError {

    #[error("received io::Error during write")]
    IoError(#[from] std::io::Error),

    #[error("bad utf8, got error: `{0:?}`")]
    FromUtf8Error(#[from] FromUtf8Error),

    #[error("could not convert BufWriter to bytes! got error: `{0:?}`")]
    IntoInnerError(#[from] std::io::IntoInnerError<BufWriter<Vec<u8>>>),
}

/**
  | Format a paragraph of text to a fixed
  | width, adding spaces for indentation
  | to any added line.
  |
  */
pub fn format_paragraph(
        in_:    &str,
        width:  Option<usize>,
        indent: Option<usize>) -> Result<String,FormatParagraphError> {

    let width:  usize = width.unwrap_or(79);
    let indent: usize = indent.unwrap_or(0);
    
    let mut out = BufWriter::new(Vec::new());
    let mut ptr:      usize = 0;
    let mut indented: usize = 0;

    while ptr < in_.len() {

        let mut lineend: Option<usize> = in_[ptr..].find('\n');

        if lineend == None {
            lineend = Some(in_.len());
        }

        let linelen:   usize = lineend.unwrap() - ptr;
        let rem_width: usize = width - indented;

        if linelen <= rem_width {

            out.write(in_[ptr..linelen + 1].as_bytes())?;

            ptr = lineend.unwrap() + 1;

            indented = 0;

        } else {

            let mut finalspace: Option<usize> = in_[..=ptr + rem_width].rfind(" \n");

            if finalspace == None || finalspace.unwrap() < ptr {

                // No place to break; just include
                // the entire word and move on
                finalspace = in_[ptr..].find("\n ");

                if finalspace == None {

                    let c: char = in_
                        .chars()
                        .nth(ptr)
                        .unwrap();

                    let s = format!{"{}",c};

                    // End of the string, just add
                    // it and break
                    out.write(s.as_bytes())?;

                    break;
                }
            }

            out.write(
                format!{
                    "{}\n", 
                    in_[ptr..finalspace.unwrap() - ptr].to_string()
                }.as_bytes()
            )?;

            if in_.chars().nth(finalspace.unwrap()).unwrap() == '\n' {

                indented = 0;

            } else {

                if indent != 0 {
                    out.write(" ".repeat(indent).as_bytes())?;
                    indented = indent;
                }
            }

            ptr = finalspace.unwrap() + 1;
        }
    }

    let bytes = out.into_inner()?;
    let result = String::from_utf8(bytes)?;

    Ok(result)
}

/**
  | Format a string to be used as option description
  | in help messages
  | 
  | -----------
  | @param option
  | 
  | Option message (e.g. "-rpcuser=<user>")
  | ----------
  | @param message
  | 
  | Option description (e.g. "Username
  | for JSON-RPC connections")
  | 
  | -----------
  | @return
  | 
  | the formatted string
  |
  */
pub fn help_message_opt(
        option:  &str,
        message: &str) -> String {

    let paragraph = format_paragraph(
        message,
        Some(SCREEN_WIDTH - MSG_INDENT),
        Some(MSG_INDENT)
    );

    match paragraph {
        Ok(paragraph) => {
            format!{
                "{}{}\n{}{}\n\n",
                " ".repeat(OPT_INDENT),
                option,
                " ".repeat(MSG_INDENT),
                paragraph
            }
        },
        Err(e) => {
            panic!{"format_paragraph failed with error: {:?}", e}
        }
    }
}

impl ArgsManagerInner {

    /**
      | Get the help string
      |
      */
    pub fn get_help_message(&self) -> String {

        let show_debug: bool = self.get_bool_arg("-help-debug",false);

        let mut usage: String = "".to_string();

        for arg_map in self.available_args.iter() {

            match arg_map.0 {

                OptionsCategory::OPTIONS  => {
                    usage += &help_message_group("Options:");
                },

                OptionsCategory::CONNECTION  => {
                    usage += &help_message_group("Connection options:");
                },

                OptionsCategory::ZMQ  => {
                    usage += &help_message_group("ZeroMQ notification options:");
                },

                OptionsCategory::DEBUG_TEST  => {
                    usage += &help_message_group("Debugging/Testing options:");
                },

                OptionsCategory::NODE_RELAY  => {
                    usage += &help_message_group("Node relay options:");
                },

                OptionsCategory::BLOCK_CREATION  => {
                    usage += &help_message_group("Block creation options:");
                },

                OptionsCategory::RPC  => {
                    usage += &help_message_group("RPC server options:");
                },

                OptionsCategory::WALLET  => {
                    usage += &help_message_group("Wallet options:");
                },

                OptionsCategory::WALLET_DEBUG_TEST  => {
                    if show_debug {
                        usage += &help_message_group("Wallet debugging/testing options:");
                    }
                },

                OptionsCategory::CHAINPARAMS  => {
                    usage += &help_message_group("Chain selection options:");
                },

                OptionsCategory::GUI  => {
                    usage += &help_message_group("UI Options:");
                },

                OptionsCategory::COMMANDS  => {
                    usage += &help_message_group("Commands:");
                },

                OptionsCategory::REGISTER_COMMANDS  => {
                    usage += &help_message_group("Register Commands:");
                },

                _  => { },
            }

            // When we get to the hidden options, stop
            if arg_map.0 == &OptionsCategory::HIDDEN {
                break;
            }

            for arg in arg_map.1.iter() {

                if show_debug || (arg.1.flags & ArgsManagerFlags::DEBUG_ONLY.bits()) == 0 {

                    let mut name = String::default();

                    if arg.1.help_param.is_empty() {
                        name = arg.0.to_string();
                    } else {
                        name = format!{"{}{}", arg.0, arg.1.help_param};
                    }

                    usage += &help_message_opt(
                        &name,
                        &arg.1.help_text
                    );
                }
            }
        }

        usage
    }
}