|
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +import codecs |
| 4 | +import re |
| 5 | +from optparse import OptionParser, BadOptionError, AmbiguousOptionError |
| 6 | + |
| 7 | +ESCAPES_PATTERN = re.compile( |
| 8 | + r"(\\0[0-7]{1,3}|\\x[0-9A-Za-z]{1,2}|\\[\\0abcefnrtv])", |
| 9 | + re.UNICODE | re.VERBOSE, |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +class PassthroughOptionParser(OptionParser): |
| 14 | + """ |
| 15 | + A modified version of OptionParser that treats unknown options and "--" as |
| 16 | + regular arguments. Always behaves as if interspersed args are disabled. |
| 17 | + """ |
| 18 | + |
| 19 | + def _process_args(self, largs, rargs, values): |
| 20 | + parsing_options = True |
| 21 | + |
| 22 | + for arg in rargs: |
| 23 | + if parsing_options and arg and arg[0] == "-" and arg != "--": |
| 24 | + try: |
| 25 | + super()._process_args([], [arg], values) |
| 26 | + except (BadOptionError, AmbiguousOptionError) as e: |
| 27 | + parsing_options = False |
| 28 | + largs.append(e.opt_str) |
| 29 | + else: |
| 30 | + parsing_options = False |
| 31 | + largs.append(arg) |
| 32 | + |
| 33 | + rargs.clear() |
| 34 | + |
| 35 | + |
| 36 | +def echo(opts, args): |
| 37 | + string = " ".join(args) |
| 38 | + |
| 39 | + if opts.escapes: |
| 40 | + |
| 41 | + def decode_match(match: re.Match[str]) -> str: |
| 42 | + try: |
| 43 | + if (escape := match.group(0))[1] == "0" and len(escape) > 2: |
| 44 | + # Convert octal escapes from "\0NNN" to Python's form |
| 45 | + # ("\NNN" without the "0"). |
| 46 | + escape = "\\" + escape[2:] |
| 47 | + |
| 48 | + return codecs.decode(escape, "unicode_escape") |
| 49 | + except UnicodeDecodeError: |
| 50 | + return match.group(0) |
| 51 | + |
| 52 | + string = ESCAPES_PATTERN.sub(decode_match, string) |
| 53 | + |
| 54 | + print(string, end="" if opts.n else "\n") |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + parser = PassthroughOptionParser( |
| 59 | + usage="Usage: %prog [OPTION]... [STRING]...", |
| 60 | + description="Print STRING(s) to standard output.", |
| 61 | + add_help_option=False, |
| 62 | + ) |
| 63 | + parser.disable_interspersed_args() |
| 64 | + parser.add_option("--help", action="help", help="show usage information and exit") |
| 65 | + |
| 66 | + parser.add_option( |
| 67 | + "-n", action="store_true", help="do not output the trailing newline" |
| 68 | + ) |
| 69 | + parser.add_option( |
| 70 | + "-e", |
| 71 | + dest="escapes", |
| 72 | + action="store_true", |
| 73 | + help="enable interpretation of backslash escapes", |
| 74 | + ) |
| 75 | + parser.add_option( |
| 76 | + "-E", |
| 77 | + dest="escapes", |
| 78 | + action="store_false", |
| 79 | + default=False, |
| 80 | + help="disable interpretation of backslash escapes (default)", |
| 81 | + ) |
| 82 | + |
| 83 | + echo(*parser.parse_args()) |
0 commit comments