Debian Codegraph @

osc_lib/utils/tags.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import argparse
14 import collections.abc
15 import typing as ty
16
17 from osc_lib.i18n import _
18
19
20 class _CommaListAction(argparse.Action):
21 def __call__(
22 self,
23 parser: argparse.ArgumentParser,
24 namespace: argparse.Namespace,
25 values: str | ty.Sequence[ty.Any] | None,
26 option_string: str | None = None,
27 ) -> None:
28 if not isinstance(values, str):
29 raise TypeError('expected str')
30 setattr(namespace, self.dest, values.split(','))
31
32
33 def add_tag_filtering_option_to_parser(
34 parser: argparse.ArgumentParser,
35 resource_name: str,
36 enhance_help: collections.abc.Callable[[str], str] = lambda _h: _h,
37 ) -> None:
38 """Add tag filtering options to a parser.
39
40 :param parser: argparse.Argument parser object.
41 :param resource_name: Description of the object being filtered.
42 :param enhance_help: A callable accepting a single parameter, the
43 (translated) help string, and returning a (translated) help string. May
44 be used by a caller wishing to add qualifying text, such as "Applies to
45 version XYZ only", to the help strings for all options produced by this
46 method.
47 """
48 parser.add_argument(
49 '--tags',
50 metavar='<tag>[,<tag>,...]',
51 action=_CommaListAction,
52 help=enhance_help(
53 _(
54 'List %s which have all given tag(s) '
55 '(Comma-separated list of tags)'
56 )
57 % resource_name
58 ),
59 )
60 parser.add_argument(
61 '--any-tags',
62 metavar='<tag>[,<tag>,...]',
63 action=_CommaListAction,
64 help=enhance_help(
65 _(
66 'List %s which have any given tag(s) '
67 '(Comma-separated list of tags)'
68 )
69 % resource_name
70 ),
71 )
72 parser.add_argument(
73 '--not-tags',
74 metavar='<tag>[,<tag>,...]',
75 action=_CommaListAction,
76 help=enhance_help(
77 _(
78 'Exclude %s which have all given tag(s) '
79 '(Comma-separated list of tags)'
80 )
81 % resource_name
82 ),
83 )
84 parser.add_argument(
85 '--not-any-tags',
86 metavar='<tag>[,<tag>,...]',
87 action=_CommaListAction,
88 help=enhance_help(
89 _(
90 'Exclude %s which have any given tag(s) '
91 '(Comma-separated list of tags)'
92 )
93 % resource_name
94 ),
95 )
96
97
98 def get_tag_filtering_args(
99 parsed_args: argparse.Namespace,
100 args: dict[str, ty.Any],
101 ) -> None:
102 """Adds the tag arguments to an args list.
103
104 Intended to be used to append the tags to an argument list that will be
105 used for service client.
106
107 :param parsed_args: Parsed argument object returned by argparse parse_args.
108 :param args: The argument list to add tags to.
109 """
110 if parsed_args.tags:
111 args['tags'] = ','.join(parsed_args.tags)
112 if parsed_args.any_tags:
113 args['any_tags'] = ','.join(parsed_args.any_tags)
114 if parsed_args.not_tags:
115 args['not_tags'] = ','.join(parsed_args.not_tags)
116 if parsed_args.not_any_tags:
117 args['not_any_tags'] = ','.join(parsed_args.not_any_tags)
118
119
120 def add_tag_option_to_parser_for_create(
121 parser: argparse.ArgumentParser,
122 resource_name: str,
123 enhance_help: collections.abc.Callable[[str], str] = lambda _h: _h,
124 ) -> None:
125 """Add tag options to a parser for create commands.
126
127 :param parser: argparse.Argument parser object.
128 :param resource_name: Description of the object being filtered.
129 :param enhance_help: A callable accepting a single parameter, the
130 (translated) help string, and returning a (translated) help string. May
131 be used by a caller wishing to add qualifying text, such as "Applies to
132 version XYZ only", to the help strings for all options produced by this
133 method.
134 """
135 tag_group = parser.add_mutually_exclusive_group()
136 tag_group.add_argument(
137 '--tag',
138 action='append',
139 dest='tags',
140 metavar='<tag>',
141 help=enhance_help(
142 _("Tag to be added to the %s (repeat option to set multiple tags)")
143 % resource_name
144 ),
145 )
146 tag_group.add_argument(
147 '--no-tag',
148 action='store_true',
149 help=enhance_help(_("No tags associated with the %s") % resource_name),
150 )
151
152
153 def add_tag_option_to_parser_for_set(
154 parser: argparse.ArgumentParser,
155 resource_name: str,
156 enhance_help: collections.abc.Callable[[str], str] = lambda _h: _h,
157 ) -> None:
158 """Add tag options to a parser for set commands.
159
160 :param parser: argparse.Argument parser object.
161 :param resource_name: Description of the object being filtered.
162 :param enhance_help: A callable accepting a single parameter, the
163 (translated) help string, and returning a (translated) help string. May
164 be used by a caller wishing to add qualifying text, such as "Applies to
165 version XYZ only", to the help strings for all options produced by this
166 method.
167 """
168 parser.add_argument(
169 '--tag',
170 action='append',
171 dest='tags',
172 metavar='<tag>',
173 help=enhance_help(
174 _("Tag to be added to the %s (repeat option to set multiple tags)")
175 % resource_name
176 ),
177 )
178 parser.add_argument(
179 '--no-tag',
180 action='store_true',
181 help=enhance_help(
182 _(
183 "Clear tags associated with the %s. Specify both "
184 "--tag and --no-tag to overwrite current tags"
185 )
186 % resource_name
187 ),
188 )
189
190
191 def add_tag_option_to_parser_for_unset(
192 parser: argparse.ArgumentParser,
193 resource_name: str,
194 enhance_help: collections.abc.Callable[[str], str] = lambda _h: _h,
195 ) -> None:
196 """Add tag options to a parser for set commands.
197
198 :param parser: argparse.Argument parser object.
199 :param resource_name: Description of the object being filtered.
200 :param enhance_help: A callable accepting a single parameter, the
201 (translated) help string, and returning a (translated) help string. May
202 be used by a caller wishing to add qualifying text, such as "Applies to
203 version XYZ only", to the help strings for all options produced by this
204 method.
205 """
206 tag_group = parser.add_mutually_exclusive_group()
207 tag_group.add_argument(
208 '--tag',
209 action='append',
210 dest='tags',
211 metavar='<tag>',
212 help=enhance_help(
213 _(
214 "Tag to be removed from the %s "
215 "(repeat option to remove multiple tags)"
216 )
217 % resource_name
218 ),
219 )
220 tag_group.add_argument(
221 '--all-tag',
222 action='store_true',
223 help=enhance_help(
224 _("Clear all tags associated with the %s") % resource_name
225 ),
226 )
227
228
229 def update_tags_for_set(
230 client: ty.Any, obj: ty.Any, parsed_args: argparse.Namespace
231 ) -> None:
232 """Set the tags on an object.
233
234 :param client: The service client to use setting the tags.
235 :param obj: The object (Resource) to set the tags on.
236 :param parsed_args: Parsed argument object returned by argparse parse_args.
237 """
238 if parsed_args.no_tag:
239 tags = set()
240 else:
241 tags = set(obj.tags or [])
242 if parsed_args.tags:
243 tags |= set(parsed_args.tags)
244 if set(obj.tags or []) != tags:
245 client.set_tags(obj, sorted(list(tags)))
246
247
248 def update_tags_for_unset(
249 client: ty.Any, obj: ty.Any, parsed_args: argparse.Namespace
250 ) -> None:
251 """Unset the tags on an object.
252
253 :param client: The service client to use unsetting the tags.
254 :param obj: The object (Resource) to unset the tags on.
255 :param parsed_args: Parsed argument object returned by argparse parse_args.
256 """
257 tags = set(obj.tags)
258 if parsed_args.all_tag:
259 tags = set()
260 if parsed_args.tags:
261 tags -= set(parsed_args.tags)
262 if set(obj.tags) != tags:
263 client.set_tags(obj, sorted(list(tags)))