linuxutils-misc 0.1.0

Miscellaneous utilities from linuxutils
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
use linuxutils_common::man::ManContent;

pub const MAN: ManContent = ManContent::empty();

use clap::Parser;
use std::process::ExitCode;

#[derive(Parser)]
#[command(
    name = "getopt",
    about = "Parse command options (enhanced)",
    override_usage = "getopt optstring parameters\n       \
                      getopt [options] [--] optstring parameters\n       \
                      getopt [options] -o|--options optstring [--] parameters"
)]
pub struct Args {
    /// Allow long options to start with a single -
    #[arg(short = 'a', long = "alternative")]
    alternative: bool,

    /// Long options to recognize (comma-separated)
    #[arg(short = 'l', long = "longoptions", value_delimiter = ',')]
    longoptions: Vec<String>,

    /// Program name for error messages
    #[arg(short = 'n', long = "name")]
    name: Option<String>,

    /// Short options string to recognize
    #[arg(short = 'o', long = "options")]
    options: Option<String>,

    /// Disable error output from getopt
    #[arg(short = 'q', long = "quiet")]
    quiet: bool,

    /// Suppress normal output
    #[arg(short = 'Q', long = "quiet-output")]
    quiet_output: bool,

    /// Set quoting conventions for shell (sh, bash, csh, tcsh)
    #[arg(short = 's', long = "shell", default_value = "bash")]
    shell: String,

    /// Test for enhanced getopt version (returns exit code 4)
    #[arg(short = 'T', long = "test")]
    test: bool,

    /// Don't quote the output
    #[arg(short = 'u', long = "unquoted")]
    unquoted: bool,

    /// Parameters to parse
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    params: Vec<String>,
}

#[derive(Clone, Copy)]
enum ArgReq {
    None,
    Required,
    Optional,
}

struct ShortOpt {
    ch: char,
    arg_req: ArgReq,
}

struct LongOpt {
    name: String,
    arg_req: ArgReq,
}

#[derive(Clone, Copy)]
enum ScanMode {
    Permute,
    StopAtFirst,
    InPlace,
}

#[derive(Clone, Copy)]
enum Shell {
    Sh,
    Csh,
}

fn parse_optstring(s: &str) -> (Vec<ShortOpt>, ScanMode) {
    let mut opts = Vec::new();
    let mut mode = ScanMode::Permute;
    let mut chars = s.chars().peekable();

    if chars.peek() == Some(&'+') {
        mode = ScanMode::StopAtFirst;
        chars.next();
    } else if chars.peek() == Some(&'-') {
        mode = ScanMode::InPlace;
        chars.next();
    }

    // Leading : suppresses error reporting (handled separately via -q)
    if chars.peek() == Some(&':') {
        chars.next();
    }

    while let Some(ch) = chars.next() {
        let arg_req = if chars.peek() == Some(&':') {
            chars.next();
            if chars.peek() == Some(&':') {
                chars.next();
                ArgReq::Optional
            } else {
                ArgReq::Required
            }
        } else {
            ArgReq::None
        };
        opts.push(ShortOpt { ch, arg_req });
    }

    (opts, mode)
}

fn parse_longopt_spec(spec: &str) -> LongOpt {
    if let Some(name) = spec.strip_suffix("::") {
        LongOpt {
            name: name.to_string(),
            arg_req: ArgReq::Optional,
        }
    } else if let Some(name) = spec.strip_suffix(':') {
        LongOpt {
            name: name.to_string(),
            arg_req: ArgReq::Required,
        }
    } else {
        LongOpt {
            name: spec.to_string(),
            arg_req: ArgReq::None,
        }
    }
}

fn quote(s: &str, shell: Shell, unquoted: bool) -> String {
    if unquoted {
        return s.to_string();
    }
    match shell {
        Shell::Sh => {
            if s.is_empty() {
                return "''".to_string();
            }
            format!("'{}'", s.replace('\'', "'\\''"))
        }
        Shell::Csh => {
            if s.is_empty() {
                return "''".to_string();
            }
            let mut out = String::from("'");
            for ch in s.chars() {
                match ch {
                    '\'' => out.push_str("'\\''"),
                    '!' => out.push_str("\\!"),
                    '\n' => out.push_str("'\\\n'"),
                    _ => out.push(ch),
                }
            }
            out.push('\'');
            out
        }
    }
}

struct Ctx<'a> {
    long_opts: &'a [LongOpt],
    prog_name: &'a str,
    quiet: bool,
    shell: Shell,
    unquoted: bool,
}

impl Ctx<'_> {
    fn quote(&self, s: &str) -> String {
        quote(s, self.shell, self.unquoted)
    }
}

fn handle_long_option(
    name: &str,
    value: Option<&str>,
    ctx: &Ctx<'_>,
    args: &[String],
    i: &mut usize,
    output: &mut Vec<String>,
) -> bool {
    let matches: Vec<_> = ctx
        .long_opts
        .iter()
        .filter(|o| o.name.starts_with(name))
        .collect();

    match matches.len() {
        0 => {
            if !ctx.quiet {
                eprintln!("{}: unrecognized option '--{name}'", ctx.prog_name);
            }
            true
        }
        1 => {
            let opt = matches[0];
            output.push(format!("--{}", opt.name));
            match opt.arg_req {
                ArgReq::Required => {
                    if let Some(v) = value {
                        output.push(ctx.quote(v));
                    } else {
                        *i += 1;
                        if *i < args.len() {
                            output.push(ctx.quote(&args[*i]));
                        } else {
                            if !ctx.quiet {
                                eprintln!(
                                    "{}: option '--{}' requires an argument",
                                    ctx.prog_name, opt.name
                                );
                            }
                            return true;
                        }
                    }
                }
                ArgReq::Optional => {
                    output.push(ctx.quote(value.unwrap_or("")));
                }
                ArgReq::None => {}
            }
            false
        }
        _ => {
            if !ctx.quiet {
                let names: Vec<_> =
                    matches.iter().map(|o| format!("'--{}'", o.name)).collect();
                eprintln!(
                    "{}: option '--{name}' is ambiguous; possibilities: {}",
                    ctx.prog_name,
                    names.join(" ")
                );
            }
            true
        }
    }
}

fn parse_user_args(
    short_opts: &[ShortOpt],
    ctx: &Ctx<'_>,
    scan_mode: ScanMode,
    alternative: bool,
    args: &[String],
) -> (Vec<String>, bool) {
    let mut output: Vec<String> = Vec::new();
    let mut non_opts: Vec<String> = Vec::new();
    let mut errors = false;
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];

        if arg == "--" {
            non_opts.extend_from_slice(&args[i + 1..]);
            break;
        }

        if arg.starts_with("--") && arg.len() > 2 {
            let rest = &arg[2..];
            let (name, value) = match rest.split_once('=') {
                Some((n, v)) => (n, Some(v)),
                None => (rest, None),
            };
            if handle_long_option(name, value, ctx, args, &mut i, &mut output) {
                errors = true;
            }
        } else if arg.starts_with('-') && arg.len() > 1 {
            let rest = &arg[1..];

            // Try alternative long option (single - prefix)
            if alternative && rest.len() > 1 && !rest.starts_with('-') {
                let (name, value) = match rest.split_once('=') {
                    Some((n, v)) => (n, Some(v)),
                    None => (rest, None),
                };
                let matches: Vec<_> = ctx
                    .long_opts
                    .iter()
                    .filter(|o| o.name.starts_with(name))
                    .collect();
                if matches.len() == 1 {
                    if handle_long_option(
                        name,
                        value,
                        ctx,
                        args,
                        &mut i,
                        &mut output,
                    ) {
                        errors = true;
                    }
                    i += 1;
                    continue;
                }
            }

            // Short options
            let chars: Vec<char> = rest.chars().collect();
            let mut j = 0;
            while j < chars.len() {
                let ch = chars[j];
                if let Some(opt) = short_opts.iter().find(|o| o.ch == ch) {
                    output.push(format!("-{ch}"));
                    match opt.arg_req {
                        ArgReq::Required => {
                            if j + 1 < chars.len() {
                                let val: String =
                                    chars[j + 1..].iter().collect();
                                output.push(ctx.quote(&val));
                                j = chars.len();
                            } else {
                                i += 1;
                                if i < args.len() {
                                    output.push(ctx.quote(&args[i]));
                                } else {
                                    if !ctx.quiet {
                                        eprintln!(
                                            "{}: option requires an argument -- '{ch}'",
                                            ctx.prog_name
                                        );
                                    }
                                    errors = true;
                                }
                            }
                        }
                        ArgReq::Optional => {
                            if j + 1 < chars.len() {
                                let val: String =
                                    chars[j + 1..].iter().collect();
                                output.push(ctx.quote(&val));
                                j = chars.len();
                            } else {
                                output.push(ctx.quote(""));
                            }
                        }
                        ArgReq::None => {}
                    }
                } else {
                    if !ctx.quiet {
                        eprintln!(
                            "{}: invalid option -- '{ch}'",
                            ctx.prog_name
                        );
                    }
                    errors = true;
                }
                j += 1;
            }
        } else {
            match scan_mode {
                ScanMode::StopAtFirst => {
                    non_opts.push(arg.clone());
                    non_opts.extend(args[i + 1..].iter().cloned());
                    break;
                }
                ScanMode::InPlace => {
                    output.push(ctx.quote(arg));
                }
                ScanMode::Permute => {
                    non_opts.push(arg.clone());
                }
            }
        }

        i += 1;
    }

    output.push("--".to_string());
    for no in &non_opts {
        output.push(ctx.quote(no));
    }

    (output, errors)
}

pub fn run(args: Args) -> ExitCode {
    if args.test {
        return ExitCode::from(4);
    }

    let shell = match args.shell.as_str() {
        "sh" | "bash" => Shell::Sh,
        "csh" | "tcsh" => Shell::Csh,
        other => {
            eprintln!("getopt: unknown shell: {other}");
            return ExitCode::from(2);
        }
    };

    let (optstring, user_args) = if let Some(ref opts) = args.options {
        (opts.as_str(), args.params.as_slice())
    } else if !args.params.is_empty() {
        (args.params[0].as_str(), &args.params[1..])
    } else {
        eprintln!("getopt: missing optstring argument");
        return ExitCode::from(2);
    };

    let (short_opts, scan_mode) = parse_optstring(optstring);

    let scan_mode = if std::env::var("POSIXLY_CORRECT").is_ok() {
        ScanMode::StopAtFirst
    } else {
        scan_mode
    };

    let long_opts: Vec<LongOpt> = args
        .longoptions
        .iter()
        .filter(|s| !s.is_empty())
        .map(|s| parse_longopt_spec(s))
        .collect();

    let ctx = Ctx {
        long_opts: &long_opts,
        prog_name: args.name.as_deref().unwrap_or("getopt"),
        quiet: args.quiet,
        shell,
        unquoted: args.unquoted,
    };

    let (output, errors) = parse_user_args(
        &short_opts,
        &ctx,
        scan_mode,
        args.alternative,
        user_args,
    );

    if !args.quiet_output {
        println!(" {}", output.join(" "));
    }

    if errors {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}