Gentoo Archives: gentoo-commits

From: Arthur Zamarin <arthurzam@g.o>
To: gentoo-commits@l.g.o
Subject: [gentoo-commits] proj/pkgcore/snakeoil:master commit in: src/snakeoil/cli/
Date: Fri, 30 Dec 2022 19:04:04
Message-Id: 1672427016.47d21307c44cad87641e20f50f57b3f5d218c0f4.arthurzam@gentoo
1 commit: 47d21307c44cad87641e20f50f57b3f5d218c0f4
2 Author: Arthur Zamarin <arthurzam <AT> gentoo <DOT> org>
3 AuthorDate: Fri Dec 30 19:03:36 2022 +0000
4 Commit: Arthur Zamarin <arthurzam <AT> gentoo <DOT> org>
5 CommitDate: Fri Dec 30 19:03:36 2022 +0000
6 URL: https://gitweb.gentoo.org/proj/pkgcore/snakeoil.git/commit/?id=47d21307
7
8 little modernization of snakeoil.cli
9
10 Signed-off-by: Arthur Zamarin <arthurzam <AT> gentoo.org>
11
12 src/snakeoil/cli/arghparse.py | 48 +++++++++++++++++++++----------------------
13 src/snakeoil/cli/input.py | 5 ++---
14 src/snakeoil/cli/tool.py | 2 +-
15 3 files changed, 26 insertions(+), 29 deletions(-)
16
17 diff --git a/src/snakeoil/cli/arghparse.py b/src/snakeoil/cli/arghparse.py
18 index 774699ed..a7a29826 100644
19 --- a/src/snakeoil/cli/arghparse.py
20 +++ b/src/snakeoil/cli/arghparse.py
21 @@ -148,13 +148,13 @@ class CommaSeparatedValues(argparse._AppendAction):
22 """Split comma-separated values into a list."""
23
24 def parse_values(self, values):
25 - items = []
26 if isinstance(values, str):
27 - items.extend(x for x in values.split(",") if x)
28 + return list(filter(None, values.split(",")))
29 else:
30 + items = []
31 for value in values:
32 items.extend(x for x in value.split(",") if x)
33 - return items
34 + return items
35
36 def __call__(self, parser, namespace, values, option_string=None):
37 items = self.parse_values(values)
38 @@ -188,9 +188,9 @@ class CommaSeparatedNegations(argparse._AppendAction):
39 values = [values]
40 for value in values:
41 try:
42 - neg, pos = split_negations(x for x in value.split(",") if x)
43 - except ValueError as e:
44 - raise argparse.ArgumentTypeError(e)
45 + neg, pos = split_negations(filter(None, value.split(",")))
46 + except ValueError as exc:
47 + raise argparse.ArgumentTypeError(exc)
48 disabled.extend(neg)
49 enabled.extend(pos)
50
51 @@ -236,9 +236,9 @@ class CommaSeparatedElements(argparse._AppendAction):
52 values = [values]
53 for value in values:
54 try:
55 - neg, neu, pos = split_elements(x for x in value.split(",") if x)
56 - except ValueError as e:
57 - raise argparse.ArgumentTypeError(e)
58 + neg, neu, pos = split_elements(filter(None, value.split(",")))
59 + except ValueError as exc:
60 + raise argparse.ArgumentTypeError(exc)
61 disabled.extend(neg)
62 neutral.extend(neu)
63 enabled.extend(pos)
64 @@ -323,7 +323,7 @@ class StoreBool(argparse._StoreAction):
65 return True
66 elif value in ("n", "no", "false", "0"):
67 return False
68 - raise ValueError("value %r must be [y|yes|true|1|n|no|false|0]" % (value,))
69 + raise ValueError(f"value {value!r} must be [y|yes|true|1|n|no|false|0]")
70
71
72 class EnableDebug(argparse._StoreTrueAction):
73 @@ -469,7 +469,7 @@ class Expansion(argparse.Action):
74 args = [x % dvals for x in args]
75 if not action:
76 raise ValueError(
77 - "unable to find option %r for %r" % (option, self.option_strings)
78 + f"unable to find option {option!r} for {self.option_strings!r}"
79 )
80 if action.type is not None:
81 args = list(map(action.type, args))
82 @@ -1137,7 +1137,7 @@ class ArgumentParser(OptionalsParser, CsvActionsParser):
83 help="enable/disable color support",
84 docs="""
85 Toggle colored output support. This can be used to forcibly
86 - enable color support when piping output or other sitations
87 + enable color support when piping output or other situations
88 where stdout is not a tty.
89 """,
90 )
91 @@ -1273,7 +1273,7 @@ class ArgumentParser(OptionalsParser, CsvActionsParser):
92 namespace.main_func = subcmd_parser.__main_func
93
94 if unknown_args:
95 - self.error("unrecognized arguments: %s" % " ".join(unknown_args))
96 + self.error(f"unrecognized arguments: {' '.join(unknown_args)}")
97
98 # Two runs are required; first, handle any suppression defaults
99 # introduced. Subparsers defaults cannot override the parent parser, as
100 @@ -1302,19 +1302,17 @@ class ArgumentParser(OptionalsParser, CsvActionsParser):
101 try:
102 for attr, delayed in sorted(i, key=lambda val: val[1].priority):
103 delayed(args, attr)
104 - except (TypeError, ValueError) as e:
105 - raise TypeError("failed loading/parsing '%s': %s" % (attr, str(e))) from e
106 + except (TypeError, ValueError) as exc:
107 + raise TypeError(f"failed loading/parsing {attr!r}: {exc}") from exc
108 except argparse.ArgumentError:
109 - e = sys.exc_info()[1]
110 - self.error(str(e))
111 + exc = sys.exc_info()[1]
112 + self.error(str(exc))
113
114 # run final arg validation
115 - final_checks = [
116 - k for k in args.__dict__.keys() if k.startswith("__final_check__")
117 - ]
118 - for check in final_checks:
119 - functor = args.pop(check)
120 - functor(self, args)
121 + for check in set(vars(args).keys()):
122 + if check.startswith("__final_check__"):
123 + functor = args.pop(check)
124 + functor(self, args)
125
126 return args
127
128 @@ -1327,7 +1325,7 @@ class ArgumentParser(OptionalsParser, CsvActionsParser):
129 if self.debug and sys.exc_info() != (None, None, None):
130 # output traceback if any exception is on the stack
131 traceback.print_exc()
132 - self.exit(status, "%s: error: %s\n" % (self.prog, message))
133 + self.exit(status, f"{self.prog}: error: {message}\n")
134
135 def bind_main_func(self, functor):
136 """Decorator to set a main function for the parser."""
137 @@ -1340,7 +1338,7 @@ class ArgumentParser(OptionalsParser, CsvActionsParser):
138 def bind_class(self, obj):
139 if not isinstance(obj, ArgparseCommand):
140 raise ValueError(
141 - "expected obj to be an instance of " "ArgparseCommand; got %r" % (obj,)
142 + f"expected obj to be an instance of ArgparseCommand; got {obj!r}"
143 )
144 obj.bind_to_parser(self)
145 return self
146
147 diff --git a/src/snakeoil/cli/input.py b/src/snakeoil/cli/input.py
148 index 9db9ea8c..7e63e332 100644
149 --- a/src/snakeoil/cli/input.py
150 +++ b/src/snakeoil/cli/input.py
151 @@ -91,11 +91,10 @@ def userquery(prompt, out, err, responses=None, default_answer=None, limit=3):
152 )
153 )
154 if not results:
155 - err.write("Sorry, response %r not understood." % (response,))
156 + err.write(f"Sorry, response {response!r} not understood.")
157 elif len(results) > 1:
158 err.write(
159 - "Response %r is ambiguous (%s)"
160 - % (response, ", ".join(key for key, val in results))
161 + f"Response {response!r} is ambiguous ({', '.join(key for key, _ in results)})"
162 )
163 else:
164 return list(results)[0][1][0]
165
166 diff --git a/src/snakeoil/cli/tool.py b/src/snakeoil/cli/tool.py
167 index d00b3cf2..18b2f89d 100644
168 --- a/src/snakeoil/cli/tool.py
169 +++ b/src/snakeoil/cli/tool.py
170 @@ -234,5 +234,5 @@ class FormattingHandler(logging.Handler):
171 self.handleError(record)
172 finally:
173 self.out.later_prefix.pop()
174 - for i in range(len(first_prefix)):
175 + for _ in range(len(first_prefix)):
176 self.out.first_prefix.pop()