Debian Codegraph @

examples/basename.rs

raw symbols SCIP
1 use jargon_args::Jargon;
2
3 // Not required, but a helper struct to contain arguments and their data.
4 struct Args {
5 multiple: bool,
6 suffix: Option<String>,
7 zero: bool,
8 names: Vec<String>,
9 }
10
11 fn main() {
12 let mut j: Jargon = Jargon::from_env(); // Get an instance of Jargon using `std::env::args()`
13
14 if j.contains(["-h", "--help"]) { // check for help argument
15 print!("{}", HELP);
16 return;
17 }
18
19 if j.contains(["-v", "--version"]) { // check for version argument
20 println!(
21 "basename example for Jargon crate {}",
22 env!("CARGO_PKG_VERSION")
23 );
24 return;
25 }
26
27 let args = Args { // fill helper struct
28 multiple: j.contains(["-a", "--multiple"]), // multiple
29 suffix: j.option_arg(["-s", "--suffix"]), // suffix to remove
30 zero: j.contains(["-z", "--zero"]), // terminate lines with null
31 names: j.finish(), // get names
32 };
33
34 if args.names.is_empty() { // check if there are names
35 println!("Missing NAMES");
36 return;
37 }
38
39 let mut v: Vec<String> = vec![print(&args, &args.names[0])]; // initiate vector of names
40
41 if args.multiple { // fill the rest if `-a` or `--multiple` was passed
42 args.names.iter().skip(1).for_each(|name| v.append(&mut vec![print(&args, name)]));
43 }
44
45 if args.zero { // terminate with null if `-z` or `--zero` was passed
46 v.iter().for_each(|name| print!("{}", name));
47 } else { // terminate each name with space or new line
48 v.iter().for_each(|name| println!("{} ", name));
49 }
50 }
51
52 // extract basename and remove suffix
53 fn print(args: &Args, name: &String) -> String {
54 if let Some(name) = name.split('/').last() {
55 if let Some(suffix) = &args.suffix {
56 if name.ends_with(suffix) {
57 if let Some(n) = name.strip_suffix(suffix) {
58 return n.to_string();
59 }
60 }
61 }
62 return name.to_string();
63 }
64 name.to_string()
65 }
66
67 const HELP: &str = "Usage: basename NAME [SUFFIX]
68 or: basename OPTION... NAME...
69 Print NAME with any leading directory components removed.
70 If specified, also remove a trailing SUFFIX.
71
72 -a, --multiple support multiple arguments and treat each as a NAME
73 -s, --suffix SUFFIX remove a trailing SUFFIX; implies -a
74 -z, --zero end each output line with NUL, not newline
75 -h, --help display this help and exit
76 -v, --version output version information and exit
77 ";