cfonts 1.3.0

Sexy ANSI fonts for the console
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! The contents of this module is all about parsing cli arguments
use std::collections::HashMap;

use crate::color::{color, get_foreground_color, hex2rgb, rgb2hex};
use crate::config::{
	Align, BgColors, CliOption, Colors, Env, Fonts, OptionType, Options, CLIOPTIONS, GRADIENTS_AGENDER,
	GRADIENTS_AROMANTIC, GRADIENTS_ASEXUAL, GRADIENTS_BISEXUAL, GRADIENTS_GENDERFLUID, GRADIENTS_GENDERQUEER,
	GRADIENTS_INTERSEX, GRADIENTS_LESBIAN, GRADIENTS_NONBINARY, GRADIENTS_PANSEXUAL, GRADIENTS_POLYSEXUAL,
	GRADIENTS_PRIDE, GRADIENTS_TRANSGENDER,
};
use crate::debug::{d, Dt};

/// This function converts command line arguments into an [`Options`] struct
///
/// ```rust
/// extern crate cfonts;
///
/// use cfonts::{ Options, Align, Colors, BgColors, Fonts, Env };
/// use cfonts::args::parse;
///
/// let mut options = Options::default();
/// options.text = "long text|with new line".to_string();
/// options.font = Fonts::FontSimple3d;
/// options.align = Align::Center;
/// options.colors = vec![Colors::Blue, Colors::White];
/// options.background = BgColors::CyanBright;
/// options.letter_spacing = 9;
/// options.line_height = 2;
/// options.spaceless = true;
/// options.max_length = 100;
/// options.gradient = vec!["#ff0000".to_string(), "#0000ff".to_string()];
/// options.independent_gradient = true;
/// options.transition_gradient = true;
/// options.raw_mode = true;
/// options.env = Env::Browser;
/// options.help = true;
/// options.version = true;
/// options.debug = true;
/// options.debug_level = 3;
///
/// // All shortcut flags
/// assert_eq!(
///     parse(vec![
///         "path/to/bin".to_string(),
///         "long text|with new line".to_string(),
///         "-f".to_string(),
///         "simple3d".to_string(),
///         "-a".to_string(),
///         "center".to_string(),
///         "-c".to_string(),
///         "blue,white".to_string(),
///         "-b".to_string(),
///         "cyanBright".to_string(),
///         "-l".to_string(),
///         "9".to_string(),
///         "-z".to_string(),
///         "2".to_string(),
///         "-s".to_string(),
///         "-m".to_string(),
///         "100".to_string(),
///         "-g".to_string(),
///         "red,blue".to_string(),
///         "-i".to_string(),
///         "-t".to_string(),
///         "-e".to_string(),
///         "browser".to_string(),
///         "-r".to_string(),
///         "-h".to_string(),
///         "-v".to_string(),
///         "-d".to_string(),
///         "-x".to_string(),
///         "3".to_string(),
///     ])
///     .unwrap(),
///     options
/// );
///
/// // All shortcut flags but all boolean flags are stacked
/// assert_eq!(
///     parse(vec![
///         "path/to/bin".to_string(),
///         "long text|with new line".to_string(),
///         "-f".to_string(),
///         "simple3d".to_string(),
///         "-a".to_string(),
///         "center".to_string(),
///         "-c".to_string(),
///         "blue,white".to_string(),
///         "-b".to_string(),
///         "cyanBright".to_string(),
///         "-l".to_string(),
///         "9".to_string(),
///         "-z".to_string(),
///         "2".to_string(),
///         "-sithvdr".to_string(), // <-- stacked boolean flags
///         "-m".to_string(),
///         "100".to_string(),
///         "-g".to_string(),
///         "red,blue".to_string(),
///         "-e".to_string(),
///         "browser".to_string(),
///         "-x".to_string(),
///         "3".to_string(),
///     ])
///     .unwrap(),
///     options
/// );
///
/// // All long-form flags
/// assert_eq!(
///     parse(vec![
///         "path/to/bin".to_string(),
///         "long text|with new line".to_string(),
///         "--font".to_string(),
///         "simple3d".to_string(),
///         "--align".to_string(),
///         "center".to_string(),
///         "--colors".to_string(),
///         "blue,white".to_string(),
///         "--background".to_string(),
///         "cyanBright".to_string(),
///         "--letter-spacing".to_string(),
///         "9".to_string(),
///         "--line-height".to_string(),
///         "2".to_string(),
///         "--spaceless".to_string(),
///         "--independent-gradient".to_string(),
///         "--transition-gradient".to_string(),
///         "--max-length".to_string(),
///         "100".to_string(),
///         "--gradient".to_string(),
///         "red,blue".to_string(),
///         "--raw-mode".to_string(),
///         "--env".to_string(),
///         "browser".to_string(),
///         "--help".to_string(),
///         "--version".to_string(),
///         "--debug".to_string(),
///         "--debug-level".to_string(),
///         "3".to_string(),
///     ])
///     .unwrap(),
///     options
/// );
/// ```
pub fn parse(args: Vec<String>) -> Result<Options, String> {
	let mut my_args = args;
	let mut options = Options::default();

	// create a lookup table for our CLIOPTIONS
	let mut options_lookup: HashMap<String, CliOption> = HashMap::new();

	for option in CLIOPTIONS {
		let name = option.name.to_string();
		let shortcut = option.shortcut.to_string();
		options_lookup.insert(name, option.clone());
		options_lookup.insert(shortcut, option.clone());
		if !option.fallback_shortcut.is_empty() {
			let shortcut = option.fallback_shortcut.to_string();
			options_lookup.insert(shortcut, option);
		}
	}

	// we check for the debug flag to make sure we send debug messages in this function as well
	let debug_options = options_lookup.get("-d").unwrap();
	let enabled_debug =
		my_args.contains(&debug_options.name.to_string()) || my_args.contains(&debug_options.shortcut.to_string());
	if enabled_debug {
		options.debug = true;
	}

	// we check for the line_height flag to make sure we don't override it with the console font
	let line_height_options = options_lookup.get("-z").unwrap();
	let line_height_changed = my_args.contains(&line_height_options.name.to_string())
		|| my_args.contains(&line_height_options.shortcut.to_string());

	d("args::parse()", 1, Dt::Head, &options, &mut std::io::stdout());

	if my_args.len() < 2 {
		let (start, end) = get_foreground_color(&Colors::Green);
		return Err(format!(
			"Please provide text to convert with: {start}cfonts \"Text\"{end}\nRun {start}cfonts --help{end} for more infos",
			start = start,
			end = end
		));
	}

	let version_options = options_lookup.get("-v").unwrap();
	if my_args[1] == *version_options.shortcut.to_string()
		|| my_args[1] == *version_options.name.to_string()
		|| my_args[1] == *version_options.fallback_shortcut.to_string()
	{
		options.version = true;
	}

	let help_options = options_lookup.get("-h").unwrap();
	if my_args[1] == *help_options.shortcut.to_string() || my_args[1] == *help_options.name.to_string() {
		options.help = true;
	}

	// our text to be converted
	options.text.clone_from(&my_args[1]);

	let mut args_length = my_args.len();
	let mut i = 2; // we skip the first two arguments as the first is path to binary and the second we already take care of above
								// we iterate over all arguments and match them with our lookup table
	while i < args_length {
		// before we see if this flag exists in our lookup we see if boolean flags have been stacked here
		if my_args[i].starts_with('-') && !my_args[i].starts_with("--") && my_args[i].len() > 2 {
			// we know that this is a stack of boolean flags
			let this_flag = my_args[i].clone();
			let mut middle_flags = Vec::new();

			// unwrap is guarded by if clause it's contained in
			for flag in this_flag.strip_prefix('-').unwrap().chars() {
				let flag_name = format!("-{}", flag);
				if options_lookup.contains_key(&flag_name) {
					middle_flags.push(flag_name);
				}
			}

			my_args.splice(i..i + 1, middle_flags.iter().cloned());
			args_length = my_args.len();
		}

		match options_lookup.get(&my_args[i]) {
			Some(this_flag) => {
				match this_flag.kind {
					OptionType::Text => { /* Only Text type is on argvs[1] */ }
					OptionType::Font => {
						i += 1;
						if i >= args_length {
							return Err(format!("Missing value for option: {}", color(this_flag.name, Colors::Green)));
						}
						options.font = match my_args[i].to_lowercase().as_str() {
							"console" => Fonts::FontConsole,
							"block" => Fonts::FontBlock,
							"simpleblock" => Fonts::FontSimpleBlock,
							"simple" => Fonts::FontSimple,
							"3d" => Fonts::Font3d,
							"simple3d" => Fonts::FontSimple3d,
							"chrome" => Fonts::FontChrome,
							"huge" => Fonts::FontHuge,
							"shade" => Fonts::FontShade,
							"slick" => Fonts::FontSlick,
							"grid" => Fonts::FontGrid,
							"pallet" => Fonts::FontPallet,
							"tiny" => Fonts::FontTiny,
							unknown => {
								return Err(format!(
									"The font \"{}\" is not supported.\nAllowed options are: {}",
									color(unknown, Colors::Green),
									color(&Fonts::list(), Colors::Green)
								));
							}
						};

						if options.font == Fonts::FontConsole && !line_height_changed {
							options.line_height = 0;
						}
					}
					OptionType::Align => {
						i += 1;
						if i >= args_length {
							return Err(format!("Missing value for option: {}", color(this_flag.name, Colors::Green)));
						}
						options.align = match my_args[i].to_lowercase().as_str() {
							"left" => Align::Left,
							"center" => Align::Center,
							"right" => Align::Right,
							"top" => Align::Top,
							"bottom" => Align::Bottom,
							unknown => {
								return Err(format!(
									"The alignment option \"{}\" is not supported.\nAllowed options are: {}",
									color(unknown, Colors::Green),
									color(&Align::list(), Colors::Green)
								));
							}
						};
					}
					OptionType::Colors => {
						i += 1;
						if i >= args_length {
							return Err(format!("Missing value for option: {}", color(this_flag.name, Colors::Green)));
						}
						options.colors = my_args[i]
							.to_lowercase()
							.as_str()
							.split(',')
							.map(|this_color| match this_color {
								"system" => Ok(Colors::System),
								"black" => Ok(Colors::Black),
								"red" => Ok(Colors::Red),
								"green" => Ok(Colors::Green),
								"yellow" => Ok(Colors::Yellow),
								"blue" => Ok(Colors::Blue),
								"magenta" => Ok(Colors::Magenta),
								"cyan" => Ok(Colors::Cyan),
								"white" => Ok(Colors::White),
								"gray" => Ok(Colors::Gray),
								"grey" => Ok(Colors::Gray),
								"redbright" => Ok(Colors::RedBright),
								"greenbright" => Ok(Colors::GreenBright),
								"yellowbright" => Ok(Colors::YellowBright),
								"bluebright" => Ok(Colors::BlueBright),
								"magentabright" => Ok(Colors::MagentaBright),
								"cyanbright" => Ok(Colors::CyanBright),
								"whitebright" => Ok(Colors::WhiteBright),
								"candy" => Ok(Colors::Candy),
								unknown => {
									if unknown.starts_with('#') && unknown.len() > 2 {
										Ok(Colors::Rgb(hex2rgb(unknown, &options)))
									} else {
										Err(format!(
											"The color \"{}\" is not supported.\nAllowed options are: {}",
											color(unknown, Colors::Green),
											color(&Colors::list(), Colors::Green)
										))
									}
								}
							})
							.collect::<Result<Vec<Colors>, String>>()?;
					}
					OptionType::BgColor => {
						i += 1;
						if i >= args_length {
							return Err(format!("Missing value for option: {}", color(this_flag.name, Colors::Green)));
						}
						options.background = match my_args[i].to_lowercase().as_str() {
							"transparent" => BgColors::Transparent,
							"black" => BgColors::Black,
							"red" => BgColors::Red,
							"green" => BgColors::Green,
							"yellow" => BgColors::Yellow,
							"blue" => BgColors::Blue,
							"magenta" => BgColors::Magenta,
							"cyan" => BgColors::Cyan,
							"white" => BgColors::White,
							"gray" => BgColors::Gray,
							"grey" => BgColors::Gray,
							"redbright" => BgColors::RedBright,
							"greenbright" => BgColors::GreenBright,
							"yellowbright" => BgColors::YellowBright,
							"bluebright" => BgColors::BlueBright,
							"magentabright" => BgColors::MagentaBright,
							"cyanbright" => BgColors::CyanBright,
							"whitebright" => BgColors::WhiteBright,
							unknown => {
								if unknown.starts_with('#') && unknown.len() > 2 {
									BgColors::Rgb(hex2rgb(unknown, &options))
								} else {
									return Err(format!(
										"The background color \"{}\" is not supported.\nAllowed options are: {}",
										color(unknown, Colors::Green),
										color(&BgColors::list(), Colors::Green)
									));
								}
							}
						};
					}
					OptionType::Gradient => {
						i += 1;
						if i >= args_length {
							return Err(format!("Missing value for option: {}", color(this_flag.name, Colors::Green)));
						}
						let expanded_args = match my_args[i].to_lowercase().as_str() {
							"lgbt" | "lgbtq" | "lgbtqa" | "pride" => {
								options.transition_gradient = true;
								GRADIENTS_PRIDE.join(",")
							}
							"agender" => {
								options.transition_gradient = true;
								GRADIENTS_AGENDER.join(",")
							}
							"aromantic" => {
								options.transition_gradient = true;
								GRADIENTS_AROMANTIC.join(",")
							}
							"asexual" => {
								options.transition_gradient = true;
								GRADIENTS_ASEXUAL.join(",")
							}
							"bisexual" | "bi" => {
								options.transition_gradient = true;
								GRADIENTS_BISEXUAL.join(",")
							}
							"genderfluid" => {
								options.transition_gradient = true;
								GRADIENTS_GENDERFLUID.join(",")
							}
							"genderqueer" => {
								options.transition_gradient = true;
								GRADIENTS_GENDERQUEER.join(",")
							}
							"intersex" => {
								options.transition_gradient = true;
								GRADIENTS_INTERSEX.join(",")
							}
							"lesbian" => {
								options.transition_gradient = true;
								GRADIENTS_LESBIAN.join(",")
							}
							"nonbinary" => {
								options.transition_gradient = true;
								GRADIENTS_NONBINARY.join(",")
							}
							"pansexual" | "pan" => {
								options.transition_gradient = true;
								GRADIENTS_PANSEXUAL.join(",")
							}
							"polysexual" | "poly" => {
								options.transition_gradient = true;
								GRADIENTS_POLYSEXUAL.join(",")
							}
							"transgender" | "trans" => {
								options.transition_gradient = true;
								GRADIENTS_TRANSGENDER.join(",")
							}
							unknown => unknown.to_string(),
						};

						options.gradient = expanded_args
							.split(',')
							.map(|this_color| match this_color {
								"black" => Ok(String::from("#000000")),
								"red" => Ok(String::from("#ff0000")),
								"green" => Ok(String::from("#00ff00")),
								"blue" => Ok(String::from("#0000ff")),
								"yellow" => Ok(String::from("#ffff00")),
								"magenta" => Ok(String::from("#ff00ff")),
								"cyan" => Ok(String::from("#00ffff")),
								"white" => Ok(String::from("#ffffff")),
								"gray" | "grey" => Ok(String::from("#808080")),
								unknown => {
									if unknown.starts_with('#') && unknown.len() > 2 {
										// parsing hex round trip to make sure it's in a good format
										Ok(rgb2hex(&hex2rgb(unknown, &options), &options))
									} else {
										Err(format!("The gradient color \"{}\" is not supported.\nAllowed options are: black, red, green, blue, yellow, magenta, cyan, white, gray, grey", color(unknown, Colors::Green)))
									}
								}
							}).collect::<Result<Vec<String>,String>>()?;

						let transition_options = options_lookup.get("-t").unwrap();
						let is_transition = my_args.contains(&transition_options.name.to_string())
							|| my_args.contains(&transition_options.shortcut.to_string())
							|| options.transition_gradient;
						if is_transition && options.gradient.len() < 2 {
							return Err(format!(
								"You must specify at least two colors for transition gradients. You specified only \"{}\"",
								color(&format!("{}", options.gradient.len()), Colors::Green)
							));
						}

						if !is_transition && options.gradient.len() != 2 {
							return Err(format!(
								"You must specify two colors for a gradient. You specified \"{}\"",
								color(&format!("{}", options.gradient.len()), Colors::Green)
							));
						}
					}
					OptionType::Number => {
						i += 1;
						if i >= args_length {
							return Err(format!("Missing value for option: {}", color(this_flag.name, Colors::Green)));
						}
						let number = match my_args[i].parse::<u16>() {
							Ok(n) => n,
							Err(_) => {
								return Err(format!(
									"Could not read argument for option: {}. Needs to be a positive number but found instead: \"{}\"",
									color(this_flag.name, Colors::Green),
									color(&my_args[i], Colors::Green)
								));
							}
						};

						match this_flag.key {
							"letter_spacing" => {
								options.letter_spacing = number;
							}
							"line_height" => {
								options.line_height = number;
							}
							"max_length" => {
								options.max_length = number;
							}
							"debug_level" => {
								options.debug_level = number;
							}
							_ => {}
						}
					}
					OptionType::Bool => match this_flag.key {
						"version" => {
							options.version = true;
						}
						"help" => {
							options.help = true;
						}
						"spaceless" => {
							options.spaceless = true;
						}
						"independent_gradient" => {
							options.independent_gradient = true;
						}
						"transition_gradient" => {
							options.transition_gradient = true;
						}
						"raw_mode" => {
							options.raw_mode = true;
						}
						"debug" => {
							options.debug = true;
						}
						_ => {}
					},
					OptionType::Env => {
						i += 1;
						if i >= args_length {
							return Err(format!("Missing value for option: {}", color(this_flag.name, Colors::Green)));
						}
						options.env = match my_args[i].to_lowercase().as_str() {
							"node" | "cli" => Env::Cli,
							"browser" => Env::Browser,
							unknown => {
								return Err(format!(
									"The env option \"{}\" is not supported.\nAllowed options are: {}",
									color(unknown, Colors::Green),
									color(&Env::list(), Colors::Green)
								));
							}
						};
					}
				}
			}
			None => {
				/* We ignore flags we don't recognize */
				d(&format!("CLI flag \"{}\" was ignored", my_args[i]), 1, Dt::Log, &options, &mut std::io::stdout());
				// note this will only debug print flags after the encounter the debug flag
			}
		};

		// iterating to next loop count
		i += 1;
	}

	Ok(options)
}