uptu_libs 0.1.0

A collection of libraries for my projects that I use often
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/// The FormatOpt enum is used to specify formatting options for strings.
/// It has several variants, each corresponding to a different formatting option.
/// All variants except for NoEndReset are used to determine the initial format string.
/// The NoEndReset variant is used to prevent the addition of a terminal reset sequence.
///
/// Note that these are private and should not be used directly. Use the Format struct instead.
enum FormatOpt {
    /// Foreground colour
    FgColour(ColourOpt),
    /// Background colour
    BgColour(ColourOpt),
    /// Bold text
    Bold,
    /// Dim text
    Dim,
    /// Underlined text
    Underline,
    /// Blinking text
    Blink,
    /// Inverted text
    Inverse,
    /// Hidden text
    Hidden,
    /// Reset all formatting
    Reset,
    /// Do not reset formatting at the end of the string
    NoEndReset,
}

/// The ColourOpt enum is used to specify colour options for strings.
/// It has several variants, each corresponding to a different 4-bit terminal colour.
pub enum ColourOpt {
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    White,
    Black,
    BrightRed,
    BrightGreen,
    BrightYellow,
    BrightBlue,
    BrightMagenta,
    BrightCyan,
    BrightWhite,
    BrightBlack,
}

impl ColourOpt {
    /// fg
    ///
    /// The fg function returns the ANSI escape code for the foreground colour.
    ///
    /// # Returns
    /// `&str` - The ANSI escape code for the foreground colour.
    fn fg(&self) -> &str {
        match self {
            ColourOpt::Red => "31",
            ColourOpt::Green => "32",
            ColourOpt::Yellow => "33",
            ColourOpt::Blue => "34",
            ColourOpt::Magenta => "35",
            ColourOpt::Cyan => "36",
            ColourOpt::White => "37",
            ColourOpt::Black => "30",
            ColourOpt::BrightRed => "91",
            ColourOpt::BrightGreen => "92",
            ColourOpt::BrightYellow => "93",
            ColourOpt::BrightBlue => "94",
            ColourOpt::BrightMagenta => "95",
            ColourOpt::BrightCyan => "96",
            ColourOpt::BrightWhite => "97",
            ColourOpt::BrightBlack => "90",
        }
    }

    /// bg
    ///
    /// The bg function returns the ANSI escape code for the background colour.
    ///
    /// # Returns
    /// `&str` - The ANSI escape code for the background colour.
    fn bg(&self) -> &str {
        match self {
            ColourOpt::Red => "41",
            ColourOpt::Green => "42",
            ColourOpt::Yellow => "43",
            ColourOpt::Blue => "44",
            ColourOpt::Magenta => "45",
            ColourOpt::Cyan => "46",
            ColourOpt::White => "47",
            ColourOpt::Black => "40",
            ColourOpt::BrightRed => "101",
            ColourOpt::BrightGreen => "102",
            ColourOpt::BrightYellow => "103",
            ColourOpt::BrightBlue => "104",
            ColourOpt::BrightMagenta => "105",
            ColourOpt::BrightCyan => "106",
            ColourOpt::BrightWhite => "107",
            ColourOpt::BrightBlack => "100",
        }
    }
}

/// The ResetFlag is used internally by the parser.
/// It is used to determine how the parser should handle the final reset sequence.
///
/// When NoEndReset is the terminal option, the parser must change the last ';' character.
/// This is due to the fact that NoEndReset doesn't append characters to the initial string.
/// As such, the parser would have "\x1b[31;42;1;MESSAGE" instead of "\x1b[31;42;1mMESSAGE".
/// The ResetFlag enum is used to determine how the parser should handle this case.
/// When NoEndReset is the terminal option, the flag is set to Final.
/// When NoEndReset is not the terminal option but still exists, the flag is set to False.
/// When NoEndReset does not exist, the flag is set to True, indicating terminal reset.
enum ResetFlag {
    /// Add a reset sequence to the end of the string
    True,
    /// Do not add a reset sequence to the end of the string
    False,
    /// Add a reset sequence to the end of the string, but change the last character
    /// of the initial string to 'm'
    Final,
}

/// The Format struct is used to format strings with various options.
/// It is instantiated with a string slice, which contains the inner message.
///
/// Example:
/// ```
/// use uptu_libs::cli::Format;
/// let fmt = Format::new("Test message");
/// ```
///
/// The struct has several public methods, which allow for method chaining.
/// This makes it easy to apply multiple formatting options to a string.
///
/// Example:
/// ```
/// use uptu_libs::cli::{Format, ColourOpt::*};
/// // This code will print a red message with a green background, bold, and underlined.
/// Format::new("Test message")
///    .fg(Red)
///    .bg(Green)
///    .bold()
///    .underline()
///    .print();
/// ```
pub struct Format {
    opts: Vec<FormatOpt>,
    str: String,
}

impl Format {
    //! # Method Chaining
    //!
    //! All of the following functions except for [Self::new()], [Self::fmt()],
    //! and [Self::print()] return a mutable reference to the Format struct.
    //! This allows for method chaining.
    //!
    //! Example:
    //! ```
    //! use uptu_libs::cli::{Format, ColourOpt::*};
    //! let msg = "Test message";
    //! let fmt = Format::new(msg)
    //!    .fg(Red)
    //!    .bg(Green)
    //!    .bold()
    //!    .underline()
    //!    .fmt();
    //! ```

    /// The `new` function creates a new Format struct with the specified string.
    ///
    /// # Arguments
    /// - `str: &str` - The string to be formatted.
    ///
    /// # Returns
    /// `Format` - The Format struct.
    pub fn new(str: &str) -> Format {
        Format {
            opts: Vec::new(),
            str: str.to_string(),
        }
    }

    /// The `add_opt` function adds a FormatOpt enum to the Format struct.
    /// It is used internally to add formatting options.
    /// It is not intended to be used directly.
    ///
    /// # Arguments
    /// - `opt: FormatOpt` - The FormatOpt enum to be added.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    fn add_opt(&mut self, opt: FormatOpt) -> &mut Self {
        self.opts.push(opt);
        self
    }

    /// The `fg` function sets the text colour.
    ///
    /// # Arguments
    /// - `colour: ColourOpt` - The ColourOpt enum to be added.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn fg(&mut self, colour: ColourOpt) -> &mut Self {
        self.add_opt(FormatOpt::FgColour(colour))
    }

    /// The `bg` function sets the background colour.
    ///
    /// # Arguments
    /// - `colour: ColourOpt` - The ColourOpt enum to be added.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn bg(&mut self, colour: ColourOpt) -> &mut Self {
        self.add_opt(FormatOpt::BgColour(colour))
    }

    /// The `colour` function sets the text colour and background colour.
    ///
    /// # Arguments
    /// - `fg: ColourOpt` - The foreground colour.
    /// - `bg: ColourOpt` - The background colour.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn colour(&mut self, fg: ColourOpt, bg: ColourOpt) -> &mut Self {
        self.fg(fg).bg(bg)
    }

    /// The `bold` function emboldens the text.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn bold(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::Bold)
    }

    /// The `dim` function dims the text.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn dim(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::Dim)
    }

    /// The `underline` function underlines the text.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn underline(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::Underline)
    }

    /// The `blink` function blinks the text.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn blink(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::Blink)
    }

    /// The `inverse` function inverts the text.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn inverse(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::Inverse)
    }

    /// The `hidden` function hides the text.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn hidden(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::Hidden)
    }

    /// The `reset` function resets all formatting.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn reset(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::Reset)
    }

    /// The `no_end_reset` function prevents the addition of a terminal reset sequence.
    ///
    /// # Returns
    /// `&mut Self` - A mutable reference to the Format struct. Allows for [method chaining](#method-chaining).
    pub fn no_end_reset(&mut self) -> &mut Self {
        self.add_opt(FormatOpt::NoEndReset)
    }

    /// The `fmt` function formats the string with the specified options.
    /// It effectively acts as a destructor for the Format struct.
    ///
    /// # Returns
    /// `String` - The formatted string.
    pub fn fmt(&self) -> String {
        format_str(&self.str, &self.opts)
    }

    /// The `print` function prints the formatted string to the console.
    pub fn print(&self) {
        println!("{}", self.fmt())
    }
}

/// format_str
///
/// The format_str function formats a string with the specified options.
/// It takes a string slice and a slice of FormatOpt enums as arguments.
/// It returns a formatted string.
///
/// This is effectively a parser for the Format struct, and is called internally.
///
/// # Arguments
/// - `msg: &str` - The string to be formatted.
/// - `opts: &[FormatOpt]` - A slice of [FormatOpt] enums.
///
/// # Returns
/// `String` - The formatted string.
fn format_str(msg: &str, opts: &[FormatOpt]) -> String {
    if opts.is_empty() {
        return msg.to_string();
    }
    let len = opts.len();
    let mut fmt_str = String::new();
    let mut reset_flag = ResetFlag::True;
    fmt_str.push_str("\x1b[");
    for (i, opt) in opts.iter().enumerate() {
        if i == len - 1 {
            match opt {
                FormatOpt::FgColour(colour) => {
                    fmt_str.push_str(&format!("{}m", colour.fg()));
                }
                FormatOpt::BgColour(colour) => {
                    fmt_str.push_str(&format!("{}m", colour.bg()));
                }
                FormatOpt::Bold => {
                    fmt_str.push_str("1m");
                }
                FormatOpt::Dim => {
                    fmt_str.push_str("2m");
                }
                FormatOpt::Underline => {
                    fmt_str.push_str("4m");
                }
                FormatOpt::Blink => {
                    fmt_str.push_str("5m");
                }
                FormatOpt::Inverse => {
                    fmt_str.push_str("7m");
                }
                FormatOpt::Hidden => {
                    fmt_str.push_str("8m");
                }
                FormatOpt::Reset => {
                    fmt_str.push_str("0m");
                }
                FormatOpt::NoEndReset => {
                    reset_flag = ResetFlag::Final;
                }
            }
        } else {
            match opt {
                FormatOpt::FgColour(colour) => {
                    fmt_str.push_str(&format!("{};", colour.fg()));
                }
                FormatOpt::BgColour(colour) => {
                    fmt_str.push_str(&format!("{};", colour.bg()));
                }
                FormatOpt::Bold => {
                    fmt_str.push_str("1;");
                }
                FormatOpt::Dim => {
                    fmt_str.push_str("2;");
                }
                FormatOpt::Underline => {
                    fmt_str.push_str("4;");
                }
                FormatOpt::Blink => {
                    fmt_str.push_str("5;");
                }
                FormatOpt::Inverse => {
                    fmt_str.push_str("7;");
                }
                FormatOpt::Hidden => {
                    fmt_str.push_str("8;");
                }
                FormatOpt::Reset => {
                    fmt_str.push_str("0;");
                }
                FormatOpt::NoEndReset => {
                    reset_flag = ResetFlag::False;
                }
            }
        }
    }
    match reset_flag {
        ResetFlag::True => {
            fmt_str.push_str(msg);
            fmt_str.push_str("\x1b[0m");
        }
        ResetFlag::Final => {
            fmt_str.replace_range(fmt_str.len() - 1..fmt_str.len(), "m");
            fmt_str.push_str(msg);
        }
        ResetFlag::False => {
            fmt_str.push_str(msg);
        }
    }
    fmt_str
}