ngxparse 0.5.15__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.
crossplane/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ # -*- coding: utf-8 -*-
2
+ from .parser import parse, parse_string
3
+ from .lexer import lex, lex_string
4
+ from .builder import build
5
+ from .formatter import format
6
+ from .ext.lua import LuaBlockPlugin
7
+
8
+ __all__ = ['parse', 'parse_string', 'lex', 'lex_string', 'build', 'format']
9
+
10
+ __title__ = 'crossplane'
11
+ __summary__ = 'Reliable and fast NGINX configuration file parser.'
12
+ __url__ = 'https://github.com/nginxinc/crossplane'
13
+
14
+ __version__ = '0.5.15'
15
+
16
+ __author__ = 'Arie van Luttikhuizen'
17
+ __email__ = 'aluttik@gmail.com'
18
+
19
+ __license__ = 'Apache 2.0'
20
+ __copyright__ = 'Copyright 2018 NGINX, Inc.'
21
+
22
+ default_enabled_extensions = [LuaBlockPlugin()]
23
+ for extension in default_enabled_extensions:
24
+ extension.register_extension()
crossplane/__main__.py ADDED
@@ -0,0 +1,259 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ import io
4
+ import os
5
+ import sys
6
+ from argparse import ArgumentParser, RawDescriptionHelpFormatter
7
+ from traceback import format_exception
8
+
9
+ from . import __version__
10
+ from .lexer import lex as lex_file
11
+ from .parser import parse as parse_file
12
+ from .builder import build as build_string, build_files, _enquote, DELIMITERS
13
+ from .formatter import format as format_file
14
+ from .compat import json, input
15
+
16
+
17
+ def _prompt_yes():
18
+ try:
19
+ return input('overwrite? (y/n [n]) ').lower().startswith('y')
20
+ except (KeyboardInterrupt, EOFError):
21
+ sys.exit(1)
22
+
23
+
24
+ def _dump_payload(obj, fp, indent):
25
+ kwargs = {'indent': indent}
26
+ if indent is None:
27
+ kwargs['separators'] = ',', ':'
28
+ fp.write(json.dumps(obj, **kwargs) + u'\n')
29
+
30
+
31
+ def parse(filename, out, indent=None, catch=None, tb_onerror=None, ignore='',
32
+ single=False, comments=False, strict=False, combine=False):
33
+
34
+ ignore = ignore.split(',') if ignore else []
35
+
36
+ def callback(e):
37
+ exc = sys.exc_info() + (10,)
38
+ return ''.join(format_exception(*exc)).rstrip()
39
+
40
+ kwargs = {
41
+ 'catch_errors': catch,
42
+ 'ignore': ignore,
43
+ 'combine': combine,
44
+ 'single': single,
45
+ 'comments': comments,
46
+ 'strict': strict
47
+ }
48
+
49
+ if tb_onerror:
50
+ kwargs['onerror'] = callback
51
+
52
+ payload = parse_file(filename, **kwargs)
53
+ o = sys.stdout if out is None else io.open(out, 'w', encoding='utf-8')
54
+ try:
55
+ _dump_payload(payload, o, indent=indent)
56
+ finally:
57
+ o.close()
58
+
59
+
60
+ def build(filename, dirname=None, force=False, indent=4, tabs=False,
61
+ header=True, stdout=False, verbose=False):
62
+
63
+ if dirname is None:
64
+ dirname = os.getcwd()
65
+
66
+ # read the json payload from the specified file
67
+ with open(filename, 'r') as fp:
68
+ payload = json.load(fp)
69
+
70
+ # find which files from the json payload will overwrite existing files
71
+ if not force and not stdout:
72
+ existing = []
73
+ for config in payload['config']:
74
+ path = config['file']
75
+ if not os.path.isabs(path):
76
+ path = os.path.join(dirname, path)
77
+ if os.path.exists(path):
78
+ existing.append(path)
79
+ # ask the user if it's okay to overwrite existing files
80
+ if existing:
81
+ print('building {} would overwrite these files:'.format(filename))
82
+ print('\n'.join(existing))
83
+ if not _prompt_yes():
84
+ print('not overwritten')
85
+ return
86
+
87
+ # if stdout is set then just print each file after another like nginx -T
88
+ if stdout:
89
+ for config in payload['config']:
90
+ path = config['file']
91
+ if not os.path.isabs(path):
92
+ path = os.path.join(dirname, path)
93
+ parsed = config['parsed']
94
+ output = build_string(parsed, indent=indent, tabs=tabs, header=header)
95
+ output = output.rstrip() + '\n'
96
+ print('# ' + path + '\n' + output)
97
+ return
98
+
99
+ # build the nginx configuration file from the json payload
100
+ build_files(payload, dirname=dirname, indent=indent, tabs=tabs, header=header)
101
+
102
+ # if verbose print the paths of the config files that were created
103
+ if verbose:
104
+ for config in payload['config']:
105
+ path = config['file']
106
+ if not os.path.isabs(path):
107
+ path = os.path.join(dirname, path)
108
+ print('wrote to ' + path)
109
+
110
+
111
+ def lex(filename, out, indent=None, line_numbers=False):
112
+ payload = list(lex_file(filename))
113
+ if line_numbers:
114
+ payload = [(token, lineno) for token, lineno, quoted in payload]
115
+ else:
116
+ payload = [token for token, lineno, quoted in payload]
117
+ o = sys.stdout if out is None else io.open(out, 'w', encoding='utf-8')
118
+ try:
119
+ _dump_payload(payload, o, indent=indent)
120
+ finally:
121
+ o.close()
122
+
123
+
124
+ def minify(filename, out):
125
+ payload = parse_file(
126
+ filename,
127
+ single=True,
128
+ catch_errors=False,
129
+ check_args=False,
130
+ check_ctx=False,
131
+ comments=False,
132
+ strict=False
133
+ )
134
+ o = sys.stdout if out is None else io.open(out, 'w', encoding='utf-8')
135
+ def write_block(block):
136
+ for stmt in block:
137
+ o.write(_enquote(stmt['directive']))
138
+ if stmt['directive'] == 'if':
139
+ o.write(u' (%s)' % ' '.join(map(_enquote, stmt['args'])))
140
+ else:
141
+ o.write(u' %s' % ' '.join(map(_enquote, stmt['args'])))
142
+ if 'block' in stmt:
143
+ o.write(u'{')
144
+ write_block(stmt['block'])
145
+ o.write(u'}')
146
+ else:
147
+ o.write(u';')
148
+ try:
149
+ write_block(payload['config'][0]['parsed'])
150
+ o.write(u'\n')
151
+ finally:
152
+ o.close()
153
+
154
+
155
+ def format(filename, out, indent=4, tabs=False):
156
+ output = format_file(filename, indent=indent, tabs=tabs)
157
+ o = sys.stdout if out is None else io.open(out, 'w', encoding='utf-8')
158
+ try:
159
+ o.write(output + u'\n')
160
+ finally:
161
+ o.close()
162
+
163
+
164
+ class _SubparserHelpFormatter(RawDescriptionHelpFormatter):
165
+ def _format_action(self, action):
166
+ line = super(RawDescriptionHelpFormatter, self)._format_action(action)
167
+
168
+ if action.nargs == 'A...':
169
+ line = line.split('\n', 1)[-1]
170
+
171
+ if line.startswith(' ') and line[4] != ' ':
172
+ parts = filter(len, line.lstrip().partition(' '))
173
+ line = ' ' + ' '.join(parts)
174
+
175
+ return line
176
+
177
+
178
+ def parse_args(args=None):
179
+ parser = ArgumentParser(
180
+ formatter_class=_SubparserHelpFormatter,
181
+ description='various operations for nginx config files',
182
+ usage='%(prog)s <command> [options]'
183
+ )
184
+ parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__)
185
+ subparsers = parser.add_subparsers(title='commands')
186
+
187
+ def create_subparser(function, help):
188
+ name = function.__name__
189
+ prog = 'crossplane ' + name
190
+ p = subparsers.add_parser(name, prog=prog, help=help, description=help)
191
+ p.set_defaults(_subcommand=function)
192
+ return p
193
+
194
+ p = create_subparser(parse, 'parses a json payload for an nginx config')
195
+ p.add_argument('filename', help='the nginx config file')
196
+ p.add_argument('-o', '--out', type=str, help='write output to a file')
197
+ p.add_argument('-i', '--indent', type=int, metavar='NUM', help='number of spaces to indent output')
198
+ p.add_argument('--ignore', metavar='DIRECTIVES', default='', help='ignore directives (comma-separated)')
199
+ p.add_argument('--no-catch', action='store_false', dest='catch', help='only collect first error in file')
200
+ p.add_argument('--tb-onerror', action='store_true', help='include tracebacks in config errors')
201
+ p.add_argument('--combine', action='store_true', help='use includes to create one single file')
202
+ p.add_argument('--single-file', action='store_true', dest='single', help='do not include other config files')
203
+ p.add_argument('--include-comments', action='store_true', dest='comments', help='include comments in json')
204
+ p.add_argument('--strict', action='store_true', help='raise errors for unknown directives')
205
+
206
+ p = create_subparser(build, 'builds an nginx config from a json payload')
207
+ p.add_argument('filename', help='the file with the config payload')
208
+ p.add_argument('-v', '--verbose', action='store_true', help='verbose output')
209
+ p.add_argument('-d', '--dir', metavar='PATH', default=None, dest='dirname', help='the base directory to build in')
210
+ p.add_argument('-f', '--force', action='store_true', help='overwrite existing files')
211
+ g = p.add_mutually_exclusive_group()
212
+ g.add_argument('-i', '--indent', type=int, metavar='NUM', help='number of spaces to indent output', default=4)
213
+ g.add_argument('-t', '--tabs', action='store_true', help='indent with tabs instead of spaces')
214
+ p.add_argument('--no-headers', action='store_false', dest='header', help='do not write header to configs')
215
+ p.add_argument('--stdout', action='store_true', help='write configs to stdout instead')
216
+
217
+ p = create_subparser(lex, 'lexes tokens from an nginx config file')
218
+ p.add_argument('filename', help='the nginx config file')
219
+ p.add_argument('-o', '--out', type=str, help='write output to a file')
220
+ p.add_argument('-i', '--indent', type=int, metavar='NUM', help='number of spaces to indent output')
221
+ p.add_argument('-n', '--line-numbers', action='store_true', help='include line numbers in json payload')
222
+
223
+ p = create_subparser(minify, 'removes all whitespace from an nginx config')
224
+ p.add_argument('filename', help='the nginx config file')
225
+ p.add_argument('-o', '--out', type=str, help='write output to a file')
226
+
227
+ p = create_subparser(format, 'formats an nginx config file')
228
+ p.add_argument('filename', help='the nginx config file')
229
+ p.add_argument('-o', '--out', type=str, help='write output to a file')
230
+ g = p.add_mutually_exclusive_group()
231
+ g.add_argument('-i', '--indent', type=int, metavar='NUM', help='number of spaces to indent output', default=4)
232
+ g.add_argument('-t', '--tabs', action='store_true', help='indent with tabs instead of spaces')
233
+
234
+ def help(command):
235
+ if command not in parser._actions[-1].choices:
236
+ parser.error('unknown command %r' % command)
237
+ else:
238
+ parser._actions[-1].choices[command].print_help()
239
+
240
+ p = create_subparser(help, 'show help for commands')
241
+ p.add_argument('command', help='command to show help for')
242
+
243
+ parsed = parser.parse_args(args=args)
244
+
245
+ # this addresses a bug that was added to argparse in Python 3.3
246
+ if not parsed.__dict__:
247
+ parser.error('too few arguments')
248
+
249
+ return parsed
250
+
251
+
252
+ def main():
253
+ kwargs = parse_args().__dict__
254
+ func = kwargs.pop('_subcommand')
255
+ func(**kwargs)
256
+
257
+
258
+ if __name__ == '__main__':
259
+ main()