manifestparser 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ # flake8: noqa
2
+ # This Source Code Form is subject to the terms of the Mozilla Public
3
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
4
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
5
+
6
+ from .expression import *
7
+ from .ini import *
8
+ from .manifestparser import *
manifestparser/cli.py ADDED
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env python
2
+ # This Source Code Form is subject to the terms of the Mozilla Public
3
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
4
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
5
+
6
+ """
7
+ Mozilla universal manifest parser
8
+ """
9
+
10
+ import os
11
+ import sys
12
+ from optparse import OptionParser
13
+
14
+ from .logger import Logger
15
+ from .manifestparser import ManifestParser, convert
16
+
17
+
18
+ class ParserError(Exception):
19
+ """error for exceptions while parsing the command line"""
20
+
21
+
22
+ def parse_args(_args):
23
+ """
24
+ parse and return:
25
+ --keys=value (or --key value)
26
+ -tags
27
+ args
28
+ """
29
+
30
+ # return values
31
+ _dict = {}
32
+ tags = []
33
+ args = []
34
+
35
+ # parse the arguments
36
+ key = None
37
+ for arg in _args:
38
+ if arg.startswith("---"):
39
+ raise ParserError("arguments should start with '-' or '--' only")
40
+ elif arg.startswith("--"):
41
+ if key:
42
+ raise ParserError("Key %s still open" % key)
43
+ key = arg[2:]
44
+ if "=" in key:
45
+ key, value = key.split("=", 1)
46
+ _dict[key] = value
47
+ key = None
48
+ continue
49
+ elif arg.startswith("-"):
50
+ if key:
51
+ raise ParserError("Key %s still open" % key)
52
+ tags.append(arg[1:])
53
+ continue
54
+ else:
55
+ if key:
56
+ _dict[key] = arg
57
+ continue
58
+ args.append(arg)
59
+
60
+ # return values
61
+ return (_dict, tags, args)
62
+
63
+
64
+ class CLICommand:
65
+ usage = "%prog [options] command"
66
+
67
+ def __init__(self, parser):
68
+ self._parser = parser # master parser
69
+ self.logger = Logger()
70
+
71
+ def parser(self):
72
+ return OptionParser(
73
+ usage=self.usage, description=self.__doc__, add_help_option=False
74
+ )
75
+
76
+
77
+ class CopyCLI(CLICommand):
78
+ """
79
+ To copy tests and manifests from a source
80
+ """
81
+
82
+ usage = "%prog [options] copy manifest directory -tag1 -tag2 --key1=value1 --key2=value2 ..."
83
+
84
+ def __call__(self, global_options, args):
85
+ # parse the arguments
86
+ try:
87
+ kwargs, tags, args = parse_args(args)
88
+ except ParserError as e:
89
+ self._parser.error(str(e))
90
+
91
+ # make sure we have some manifests, otherwise it will
92
+ # be quite boring
93
+ if not len(args) == 2:
94
+ self.logger.error("missing arguments: manifest directory")
95
+ HelpCLI(self._parser)(global_options, ["copy"])
96
+ return 1
97
+
98
+ # read the manifests
99
+ # TODO: should probably ensure these exist here
100
+ manifests = ManifestParser()
101
+ manifests.read(args[0])
102
+
103
+ # print the resultant query
104
+ manifests.copy(args[1], None, *tags, **kwargs)
105
+ return 0
106
+
107
+
108
+ class CreateCLI(CLICommand):
109
+ """
110
+ create a manifest from a list of directories
111
+ """
112
+
113
+ usage = "%prog [options] create directory <directory> <...>"
114
+
115
+ def parser(self):
116
+ parser = CLICommand.parser(self)
117
+ parser.add_option(
118
+ "-p", "--pattern", dest="pattern", help="glob pattern for files"
119
+ )
120
+ parser.add_option(
121
+ "-i",
122
+ "--ignore",
123
+ dest="ignore",
124
+ default=[],
125
+ action="append",
126
+ help="directories to ignore",
127
+ )
128
+ parser.add_option(
129
+ "-w",
130
+ "--in-place",
131
+ dest="in_place",
132
+ help="Write .ini files in place; filename to write to",
133
+ )
134
+ return parser
135
+
136
+ def __call__(self, global_options, args):
137
+ parser = self.parser()
138
+ options, args = parser.parse_args(args)
139
+
140
+ # need some directories
141
+ if not len(args):
142
+ self.logger.error("missing arguments: directory ...")
143
+ parser.print_usage()
144
+ return 1
145
+
146
+ # add the directories to the manifest
147
+ for arg in args:
148
+ assert os.path.exists(arg)
149
+ assert os.path.isdir(arg)
150
+ manifest = convert(
151
+ args,
152
+ pattern=options.pattern,
153
+ ignore=options.ignore,
154
+ write=options.in_place,
155
+ )
156
+ if manifest:
157
+ print(manifest)
158
+ return 0
159
+
160
+
161
+ class HelpCLI(CLICommand):
162
+ """
163
+ get help on a command
164
+ """
165
+
166
+ usage = "%prog [options] help [command]"
167
+
168
+ def __call__(self, global_options, args):
169
+ if len(args) == 1 and args[0] in commands:
170
+ commands[args[0]](self._parser).parser().print_help()
171
+ else:
172
+ self._parser.print_help()
173
+ print("\nCommands:")
174
+ for command in sorted(commands):
175
+ print(" %s : %s" % (command, commands[command].__doc__.strip()))
176
+
177
+
178
+ class UpdateCLI(CLICommand):
179
+ """
180
+ update the tests as listed in a manifest from a directory
181
+ """
182
+
183
+ usage = "%prog [options] update manifest directory -tag1 -tag2 --key1=value1 --key2=value2 ..."
184
+
185
+ def __call__(self, options, args):
186
+ # parse the arguments
187
+ try:
188
+ kwargs, tags, args = parse_args(args)
189
+ except ParserError as e:
190
+ self._parser.error(str(e))
191
+
192
+ # make sure we have some manifests, otherwise it will
193
+ # be quite boring
194
+ if not len(args) == 2:
195
+ self.logger.error("missing arguments: manifest directory")
196
+ HelpCLI(self._parser)(options, ["update"])
197
+ return 1
198
+
199
+ # read the manifests
200
+ # TODO: should probably ensure these exist here
201
+ manifests = ManifestParser()
202
+ manifests.read(args[0])
203
+
204
+ # print the resultant query
205
+ manifests.update(args[1], None, *tags, **kwargs)
206
+ return 0
207
+
208
+
209
+ class WriteCLI(CLICommand):
210
+ """
211
+ write a manifest based on a query
212
+ """
213
+
214
+ usage = "%prog [options] write manifest <manifest> -tag1 -tag2 --key1=value1 --key2=value2 ..."
215
+
216
+ def __call__(self, options, args):
217
+ # parse the arguments
218
+ try:
219
+ kwargs, tags, args = parse_args(args)
220
+ except ParserError as e:
221
+ self._parser.error(str(e))
222
+
223
+ # make sure we have some manifests, otherwise it will
224
+ # be quite boring
225
+ if not args:
226
+ self.logger.error("missing arguments: manifest ...")
227
+ HelpCLI(self._parser)(options, ["write"])
228
+ return 1
229
+
230
+ # read the manifests
231
+ # TODO: should probably ensure these exist here
232
+ manifests = ManifestParser()
233
+ manifests.read(*args)
234
+
235
+ # print the resultant query
236
+ manifests.write(global_tags=tags, global_kwargs=kwargs)
237
+ return 0
238
+
239
+
240
+ # command -> class mapping
241
+ commands = {
242
+ "copy": CopyCLI,
243
+ "create": CreateCLI,
244
+ "help": HelpCLI,
245
+ "update": UpdateCLI,
246
+ "write": WriteCLI,
247
+ }
248
+
249
+
250
+ def main(args=sys.argv[1:]):
251
+ """console_script entry point"""
252
+
253
+ # set up an option parser
254
+ usage = "%prog [options] [command] ..."
255
+ description = "%s. Use `help` to display commands" % __doc__.strip()
256
+ parser = OptionParser(usage=usage, description=description)
257
+ parser.add_option(
258
+ "-s",
259
+ "--strict",
260
+ dest="strict",
261
+ action="store_true",
262
+ default=False,
263
+ help="adhere strictly to errors",
264
+ )
265
+ parser.disable_interspersed_args()
266
+
267
+ global_options, args = parser.parse_args(args)
268
+
269
+ if not args:
270
+ HelpCLI(parser)(global_options, args)
271
+ parser.exit()
272
+
273
+ # get the command
274
+ command = args[0]
275
+ if command not in commands:
276
+ parser.error(
277
+ "Command must be one of %s (you gave '%s')"
278
+ % (", ".join(sorted(commands.keys())), command)
279
+ )
280
+ return 1
281
+
282
+ handler = commands[command](parser)
283
+ return handler(global_options, args[1:])
284
+
285
+
286
+ if __name__ == "__main__":
287
+ sys.exit(main())
@@ -0,0 +1,328 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ import functools
6
+ import re
7
+ import sys
8
+ import traceback
9
+
10
+ __all__ = ["parse", "ParseError", "ExpressionParser"]
11
+
12
+ # expr.py
13
+ # from:
14
+ # http://k0s.org/mozilla/hg/expressionparser
15
+ # http://hg.mozilla.org/users/tmielczarek_mozilla.com/expressionparser
16
+
17
+ # Implements a top-down parser/evaluator for simple boolean expressions.
18
+ # ideas taken from http://effbot.org/zone/simple-top-down-parsing.htm
19
+ #
20
+ # Rough grammar:
21
+ # expr := literal
22
+ # | '(' expr ')'
23
+ # | expr '&&' expr
24
+ # | expr '||' expr
25
+ # | expr '==' expr
26
+ # | expr '!=' expr
27
+ # | expr '<' expr
28
+ # | expr '>' expr
29
+ # | expr '<=' expr
30
+ # | expr '>=' expr
31
+ # literal := BOOL
32
+ # | INT
33
+ # | STRING
34
+ # | IDENT
35
+ # BOOL := true|false
36
+ # INT := [0-9]+
37
+ # STRING := "[^"]*"
38
+ # IDENT := [A-Za-z_]\w*
39
+
40
+ # Identifiers take their values from a mapping dictionary passed as the second
41
+ # argument.
42
+
43
+ # Glossary (see above URL for details):
44
+ # - nud: null denotation
45
+ # - led: left detonation
46
+ # - lbp: left binding power
47
+ # - rbp: right binding power
48
+
49
+
50
+ class ident_token:
51
+ def __init__(self, scanner, value):
52
+ self.value = value
53
+
54
+ def nud(self, parser):
55
+ # identifiers take their value from the value mappings passed
56
+ # to the parser
57
+ return parser.value(self.value)
58
+
59
+
60
+ class literal_token:
61
+ def __init__(self, scanner, value):
62
+ self.value = value
63
+
64
+ def nud(self, parser):
65
+ return self.value
66
+
67
+
68
+ class eq_op_token:
69
+ "=="
70
+
71
+ def led(self, parser, left):
72
+ return left == parser.expression(self.lbp)
73
+
74
+
75
+ class neq_op_token:
76
+ "!="
77
+
78
+ def led(self, parser, left):
79
+ return left != parser.expression(self.lbp)
80
+
81
+
82
+ class lt_op_token:
83
+ "<"
84
+
85
+ def led(self, parser, left):
86
+ return left < parser.expression(self.lbp)
87
+
88
+
89
+ class gt_op_token:
90
+ ">"
91
+
92
+ def led(self, parser, left):
93
+ return left > parser.expression(self.lbp)
94
+
95
+
96
+ class le_op_token:
97
+ "<="
98
+
99
+ def led(self, parser, left):
100
+ return left <= parser.expression(self.lbp)
101
+
102
+
103
+ class ge_op_token:
104
+ ">="
105
+
106
+ def led(self, parser, left):
107
+ return left >= parser.expression(self.lbp)
108
+
109
+
110
+ class not_op_token:
111
+ "!"
112
+
113
+ def nud(self, parser):
114
+ return not parser.expression(100)
115
+
116
+
117
+ class and_op_token:
118
+ "&&"
119
+
120
+ def led(self, parser, left):
121
+ right = parser.expression(self.lbp)
122
+ return left and right
123
+
124
+
125
+ class or_op_token:
126
+ "||"
127
+
128
+ def led(self, parser, left):
129
+ right = parser.expression(self.lbp)
130
+ return left or right
131
+
132
+
133
+ class lparen_token:
134
+ "("
135
+
136
+ def nud(self, parser):
137
+ expr = parser.expression()
138
+ parser.advance(rparen_token)
139
+ return expr
140
+
141
+
142
+ class rparen_token:
143
+ ")"
144
+
145
+
146
+ class end_token:
147
+ """always ends parsing"""
148
+
149
+
150
+ # derived literal tokens
151
+
152
+
153
+ class bool_token(literal_token):
154
+ def __init__(self, scanner, value):
155
+ value = {"true": True, "false": False}[value]
156
+ literal_token.__init__(self, scanner, value)
157
+
158
+
159
+ class int_token(literal_token):
160
+ def __init__(self, scanner, value):
161
+ literal_token.__init__(self, scanner, int(value))
162
+
163
+
164
+ class string_token(literal_token):
165
+ def __init__(self, scanner, value):
166
+ literal_token.__init__(self, scanner, value[1:-1])
167
+
168
+
169
+ precedence = [
170
+ (end_token, rparen_token),
171
+ (or_op_token,),
172
+ (and_op_token,),
173
+ (lt_op_token, gt_op_token, le_op_token, ge_op_token, eq_op_token, neq_op_token),
174
+ (lparen_token,),
175
+ ]
176
+ for index, rank in enumerate(precedence):
177
+ for token in rank:
178
+ token.lbp = index # lbp = lowest left binding power
179
+
180
+
181
+ class ParseError(Exception):
182
+ """error parsing conditional expression"""
183
+
184
+
185
+ @functools.cache
186
+ def scan(text):
187
+ if not ExpressionParser.scanner:
188
+ ExpressionParser.scanner = re.Scanner([
189
+ # Note: keep these in sync with the class docstring above.
190
+ (r"true|false", bool_token),
191
+ (r"[a-zA-Z_]\w*", ident_token),
192
+ (r"[0-9]+", int_token),
193
+ (r'"[^"]*"|\'[^\']*\'', string_token),
194
+ (r"==", eq_op_token()),
195
+ (r"!=", neq_op_token()),
196
+ (r"<=", le_op_token()),
197
+ (r">=", ge_op_token()),
198
+ (r"<", lt_op_token()),
199
+ (r">", gt_op_token()),
200
+ (r"\|\|", or_op_token()),
201
+ (r"!", not_op_token()),
202
+ (r"&&", and_op_token()),
203
+ (r"\(", lparen_token()),
204
+ (r"\)", rparen_token()),
205
+ (r"\s+", None), # skip whitespace
206
+ ])
207
+ tokens, _ = ExpressionParser.scanner.scan(text)
208
+ return tokens
209
+
210
+
211
+ class ExpressionParser:
212
+ r"""
213
+ A parser for a simple expression language.
214
+
215
+ The expression language can be described as follows::
216
+
217
+ EXPRESSION ::= LITERAL | '(' EXPRESSION ')' | '!' EXPRESSION | EXPRESSION OP EXPRESSION
218
+ OP ::= '==' | '!=' | '<' | '>' | '<=' | '>=' | '&&' | '||'
219
+ LITERAL ::= BOOL | INT | IDENT | STRING
220
+ BOOL ::= 'true' | 'false'
221
+ INT ::= [0-9]+
222
+ IDENT ::= [a-zA-Z_]\w*
223
+ STRING ::= '"' [^\"] '"' | ''' [^\'] '''
224
+
225
+ At its core, expressions consist of booleans, integers, identifiers and.
226
+ strings. Booleans are one of *true* or *false*. Integers are a series
227
+ of digits. Identifiers are a series of English letters and underscores.
228
+ Strings are a pair of matching quote characters (single or double) with
229
+ zero or more characters inside.
230
+
231
+ Expressions can be combined with operators: the equals (==) and not
232
+ equals (!=) operators compare two expressions and produce a boolean. The
233
+ and (&&) and or (||) operators take two expressions and produce the logical
234
+ AND or OR value of them, respectively. An expression can also be prefixed
235
+ with the not (!) operator, which produces its logical negation.
236
+
237
+ Finally, any expression may be contained within parentheses for grouping.
238
+
239
+ Identifiers take their values from the mapping provided.
240
+ """
241
+
242
+ scanner = None
243
+
244
+ def __init__(self, text, valuemapping, strict=False):
245
+ """
246
+ Initialize the parser
247
+ :param text: The expression to parse as a string.
248
+ :param valuemapping: A dict mapping identifier names to values.
249
+ :param strict: If true, referencing an identifier that was not
250
+ provided in :valuemapping: will raise an error.
251
+ """
252
+ self.text = text
253
+ self.valuemapping = valuemapping
254
+ self.strict = strict
255
+
256
+ def _tokenize(self):
257
+ """
258
+ Lex the input text into tokens and yield them in sequence.
259
+ """
260
+ yield from scan(self.text)
261
+ yield end_token()
262
+
263
+ def value(self, ident):
264
+ """
265
+ Look up the value of |ident| in the value mapping passed in the
266
+ constructor.
267
+ """
268
+ if self.strict:
269
+ return self.valuemapping[ident]
270
+ else:
271
+ return self.valuemapping.get(ident, "")
272
+
273
+ def advance(self, expected):
274
+ """
275
+ Assert that the next token is an instance of |expected|, and advance
276
+ to the next token.
277
+ """
278
+ if not isinstance(self.token, expected):
279
+ raise Exception("Unexpected token!")
280
+ self.token = next(self.iter)
281
+
282
+ def expression(self, rbp=0):
283
+ """
284
+ Parse and return the value of an expression until a token with
285
+ right binding power greater than rbp is encountered.
286
+ """
287
+ t = self.token
288
+ self.token = next(self.iter)
289
+ left = t.nud(self)
290
+ while rbp < self.token.lbp:
291
+ t = self.token
292
+ self.token = next(self.iter)
293
+ left = t.led(self, left)
294
+ return left
295
+
296
+ def parse(self):
297
+ """
298
+ Parse and return the value of the expression in the text
299
+ passed to the constructor. Raises a ParseError if the expression
300
+ could not be parsed.
301
+ """
302
+ try:
303
+ self.iter = self._tokenize()
304
+ self.token = next(self.iter)
305
+ return self.expression()
306
+ except Exception:
307
+ extype, ex, tb = sys.exc_info()
308
+ formatted = "".join(traceback.format_exception_only(extype, ex))
309
+ pe = ParseError(
310
+ "could not parse: %s\nexception: %svariables: %s"
311
+ % (self.text, formatted, self.valuemapping)
312
+ )
313
+ raise pe.with_traceback(tb)
314
+
315
+ __call__ = parse
316
+
317
+
318
+ @functools.cache
319
+ def parse(text, strict=False, **values):
320
+ """
321
+ Parse and evaluate a boolean expression.
322
+ :param text: The expression to parse, as a string.
323
+ :param values: A dict containing a name to value mapping for identifiers
324
+ referenced in *text*.
325
+ :rtype: the final value of the expression.
326
+ :raises: :py:exc::ParseError: will be raised if parsing fails.
327
+ """
328
+ return ExpressionParser(text, values, strict=strict).parse()