{{ message }}
Repository navigation
Expand file tree
/
Copy pathrun
More file actions
executable file
·787 lines (695 loc) · 25 KB
/
Copy pathrun
File metadata and controls
executable file
·787 lines (695 loc) · 25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
#!/usr/bin/env python3
"""This is a wrapper script used for maintaining projects.
It wraps the commands and tools you need to run to develop and
maintain projects -- building, testing, packaging, etc. -- and provides
a project-neutral interface to them.
"""
import argparse
import glob
import os
import re
import shlex
import shutil
import subprocess
import sys
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
THIS_FULL_VER = sys.version.split()[0]
THIS_VER = '.'.join(str(x) for x in sys.version_info[:2])
# This'll need to change if there's ever a Python 4 to support.
MIN_PARTIAL_MINOR_VER = 8
MIN_FULL_MINOR_VER = 11
MAX_FULL_MINOR_VER = 14
MAX_PARTIAL_MINOR_VER = 15
PARTIAL_COMMANDS = ['clean', 'devenv', 'help', 'tests']
PARTIAL_COMMANDS_STR = (
', '.join('`{x}`' for x in PARTIAL_COMMANDS[:-1])
+ '`{PARTIAL_COMMANDS[-1]}`'
)
class FailFastException(Exception):
def __init__(self, returncode):
self.returncode = returncode
class Runner:
def __init__(self):
self.arg_parser = None
self.args = None
self.grammar = 'json5/json5.g'
self.package = 'json5'
self.parser_file = f'{self.package}/parser.py'
self.subps = None
self.failfast = False
self.returncode = 0
with open(self.package + '/version.py', encoding='utf-8') as fp:
contents = fp.read()
m = re.search("__version__ = '(.*)'", contents, re.MULTILINE)
if m:
self.version = m.group(1)
else:
print(
'Error, could not determine package version. Exiting',
file=sys.stderr,
)
sys.exit(1)
self.uv_path = shutil.which('uv')
if self.uv_path is None and self.args.command not in ('help', 'tests'):
print('You need to have `uv` installed to run this script')
sys.exit(2)
self.venv = None
if 'VIRTUAL_ENV' in os.environ:
self.venv = os.environ['VIRTUAL_ENV'].replace(THIS_DIR, '/')
self.run_cmd = ['python', '-m']
def main(self, argv):
# Change stdout to be unbuffered so that output shows up in
# the right interleaving between this process and any child
# processes.
sys.stdout.reconfigure(line_buffering=True)
self.parse_args(argv)
if not self.is_supported_python_version():
return 1
if not self.venv and self.args.command != 'devenv':
is_uv = 'UV' in os.environ
if not is_uv:
run_cmd = ['uv', 'run', '--isolated']
if not self.args.verbose:
run_cmd += ['--quiet']
run_cmd += ['--python', self.args.python, 'python']
run_cmd += sys.argv
return self._call(run_cmd).returncode
print('This command must be run in a virtualenv')
return 1
self.failfast = getattr(self.args, 'failfast', False)
if (
not self.args.quiet
and self.args.command != 'devenv'
and (
(self.args.verbose and self.args.command != 'help')
or self.args.command == 'presubmit'
)
):
venv_path = self.venv.replace(THIS_DIR, '/')
if 'cache/uv/builds' in venv_path:
venv_path = 'an isolated .venv'
print(
f'# Running `{self.args.command}` using Python '
f'{THIS_VER} and {venv_path}'
)
try:
return self.args.func(self.args)
except FailFastException as e:
return e.returncode
def parse_args(self, argv):
self.arg_parser = argparse.ArgumentParser(
prog='run', description=__doc__
)
self.subps = self.arg_parser.add_subparsers(
dest='command', required=True
)
subp = self._add_parser(
'regen',
help=f'Regenerate the parser ({self.parser_file}) if the grammar '
f'({self.grammar}) has changed',
)
subp.add_argument(
'--check',
action='store_true',
help='Just check to see if the grammar needs to be regenerated',
)
subp = self._add_parser(
'format',
help='Format the source code with ruff format and pyproject-fmt',
)
subp.add_argument(
'--check',
action='store_true',
help='Just check to see if any files need to be reformatted',
)
subp = self._add_parser(
'checks', help='Run static analyzers (ruff check, pylint, mypy)'
)
subp.add_argument(
'-f',
'--failfast',
action='store_true',
help='Stop on first failure or error',
)
subp = self._add_parser('tests', help='Run the tests')
subp.add_argument(
'-d',
'--durations',
metavar='N',
action='store',
help='show the N slowed test cases (N=0 for all)',
)
subp.add_argument(
'-f',
'--failfast',
action='store_true',
help='Stop on first failure or error',
)
subp.add_argument(
'-u', '--unit', action='store_true', help='Only run unit tests'
)
subp.add_argument('test', nargs='*', action='store')
subp = self._add_parser(
'coverage', help='Run tests and report code coverage'
)
subp.add_argument(
'-b',
'--branch',
action='store_true',
help='Report branch coverage.',
)
subp.add_argument(
'--omit',
help='Omit files whose paths match one of these patterns',
)
subp.add_argument(
'-u', '--unit', action='store_true', help='Only run unit tests'
)
subp.add_argument('test', nargs='*', action='store')
self._add_parser('build', help='Build the package')
subp = self._add_parser('publish', help='Publish packages to PyPI')
subp.add_argument(
'--check',
action='store_true',
help='Check the package intead of publishing',
)
subp.add_argument(
'--test',
action='store_true',
help='Upload to the PyPI test instance',
)
subp.add_argument(
'--prod',
action='store_true',
help='Upload to the real PyPI instance',
)
subp = self._add_parser(
'presubmit', help='Check that all of the above commands pass'
)
subp.add_argument(
'-b',
'--branch',
action='store_true',
help='Report branch coverage',
)
subp.add_argument(
'-f',
'--failfast',
action='store_true',
help='Stop on first failure or error',
)
subp = self._add_parser('help', help='Get help on a subcommand')
subp.add_argument(
nargs='?',
action='store',
dest='subcommand',
help='The command to get help for',
)
self._add_parser(
'devenv',
help='Set up a Python venv at //.venv with all the needed '
'development packages',
)
subp = self._add_parser(
'clean', help='Remove any unversioned local files'
)
subp.add_argument(
'--check',
action='store_true',
help='Just check if there are any unversioned files and report them',
)
self.args = self.arg_parser.parse_args(self._shuffle_argv(argv))
if '.' not in self.args.python:
self.args.python = '3.' + self.args.python
def _add_parser(self, cmd, help): # pylint: disable=redefined-builtin
method = getattr(self, 'run_' + cmd.replace('-', '_'))
subp = self.subps.add_parser(cmd, help=help)
subp.add_argument(
'-n',
'--no-execute',
action='store_true',
help="Don't do anything that causes effects.",
)
subp.add_argument(
'-q',
'--quiet',
action='store_true',
help='Suppress output unless something fails.',
)
subp.add_argument(
'-v',
'--verbose',
action='store_true',
help='Echo commands as they are run.',
)
subp.add_argument(
'-p',
'--python',
help=(
f'Use the specified Python version (3.{MIN_PARTIAL_MINOR_VER} '
f'to 3.{MAX_PARTIAL_MINOR_VER} are supported; default is to '
f'use the current version (%(default)s))'
),
default=f'{THIS_VER}',
)
subp.set_defaults(func=lambda _: method())
return subp
#
# Commands
#
def run_build(self):
self._check_version()
cmd = [self.uv_path, 'build']
if self.args.quiet:
cmd.append('--quiet')
proc = self._call(cmd, capture_output=True)
for line in proc.stderr.decode('utf-8').splitlines():
# Build is very verbose by default; ignore most output unless
# we're running with --verbose.
lines_to_ignore = (
'Building',
'Copying',
'Creating',
'Writing',
'adding',
'copying',
'creating',
'installing',
'removing',
'reading',
'running',
'writing',
)
if self.args.verbose or not line.startswith(lines_to_ignore):
print(line, file=sys.stderr)
return self.returncode
def run_checks(self):
if self.args.command == 'presubmit':
print()
if not self.args.quiet:
print('### ruff check')
self._call(self.run_cmd + ['ruff', 'check'])
if not self.args.quiet:
print('\n### pylint')
proc = self._call(self.run_cmd + ['pylint'] + self._files())
if proc.returncode == 0 and not self.args.quiet:
print('Success: pylint found no issues')
if not self.args.quiet:
print('\n### mypy')
self._call(self.run_cmd + ['mypy'] + self._files())
return self.returncode
def run_clean(self):
path = shutil.which('git')
if path is None:
print('You must have git installed to clean out the right files.')
if self.failfast:
raise FailFastException(1)
self.returncode = 1
if self.args.check:
self._call([path, 'clean', '-nd'])
else:
self._call([path, 'clean', '-fd'])
self._remove('.coverage')
self._remove('build')
self._remove('dist')
self._remove('json5.egg-info')
return self.returncode
def run_coverage(self):
env = os.environ.copy()
if self.args.unit:
env['SKIP'] = 'integration'
self.args.omit = '*_test.py'
cmd = self.run_cmd + ['coverage', 'run']
if self.args.branch:
cmd.append('--branch')
cmd.extend(
[
'-m',
'unittest',
'discover',
'-p',
'*_test.py',
],
)
if self.args.verbose:
cmd.append('-v')
for test in self.args.test:
cmd.extend(['-k', self._trim_test_glob(test)])
self._call(cmd, env=env)
cmd = self.run_cmd + ['coverage', 'report', '--show-missing']
if self.args.omit:
cmd.append(f'--omit={self.args.omit}')
self._call(cmd)
return self.returncode
def run_devenv(self):
if self.uv_path is None:
print('You need to have `uv` installed to set up a dev env.')
return 1
cmd = [self.uv_path, 'sync', '--python', self.args.python]
if self.args.quiet:
cmd.append('--quiet')
in_venv = 'VIRTUAL_ENV' in os.environ
self._call(cmd)
if not in_venv and not self.returncode:
print('Run `source .venv/bin/activate` to finish devenv setup.')
return self.returncode
def run_format(self):
cmd = self.run_cmd[:-2] + [
'pyproject-fmt',
'--column-width',
'80',
'--no-print-diff',
]
if self.args.check:
cmd.append('--check')
else:
cmd.append('--stdout')
cmd.append('pyproject.toml')
old = None
with open('pyproject.toml', 'r', encoding='utf8') as fp:
old = fp.read()
proc = self._call(cmd, capture_output=True, ignore_error=True)
if self.args.check:
if proc.returncode:
self.returncode = proc.returncode
print('pyproject.toml needs formatting')
cmd.remove('--no-print-diff')
self._call(cmd, ignore_error=True)
if self.failfast:
return proc.returncode
elif not self.args.quiet:
print('pyproject.toml already formatted')
elif proc.returncode and not proc.stdout:
return proc.returncode
new = proc.stdout.decode('utf8')
if not self.args.no_execute and not self.args.check:
if new != old:
with open('pyproject.toml', 'wb') as fp:
fp.write(proc.stdout)
print('pyproject.toml reformatted')
elif not self.args.quiet:
print('pyproject.toml already formatted')
cmd = self.run_cmd + ['ruff', 'format']
if self.args.check:
cmd.append('--check')
proc = self._call(cmd, capture_output=True)
out = proc.stdout.decode('utf-8')
out = out.replace('left unchanged', 'already formatted')
if not self.args.quiet or not out.endswith('already formatted\n'):
print(out, end='')
if proc.returncode:
return proc.returncode
if self.returncode:
return self.returncode
return 0
def run_help(self):
if self.args.subcommand:
self.main([self.args.subcommand, '--help'])
return self.main(['--help'])
def run_presubmit(self):
self.args.check = True
# Stub out args to `run tests`
self.args.durations = []
self.args.omit = []
self.args.test = []
self.args.unit = False
steps = (
# TODO: Enable this once glop is properly packaged and available.
# ('regen --check', self.run_regen),
('format --check', self.run_format),
('checks', self.run_checks),
('tests', self.run_tests),
('coverage --check', self.run_coverage),
('build', self.run_build),
('publish --check', self.run_publish),
)
for desc, func in steps:
if not self.args.quiet:
print(f'\n## Running `{desc}`')
func()
if self.returncode and self.failfast:
break
if not self.args.quiet and not self.returncode:
print('\n## Presubmit passed.')
elif self.returncode:
print('\n## Presubmit failed.')
return self.returncode
def run_publish(self):
if not self.args.check and not self.args.test and not self.args.prod:
print('You must specify either --test or --prod to upload.')
return 2
self._check_version()
sep = os.path.sep
tgz = f'dist{sep}{self.package}-{self.version}.tar.gz'
wheel = f'dist{sep}{self.package}-{self.version}-py3-none-any.whl'
self.run_build()
if not os.path.exists(tgz) or not os.path.exists(wheel):
print('Run `./run build` first')
return 1
if self.args.test:
test = ['--repository', 'testpypi']
else:
test = []
if self.args.check:
self._call(self.run_cmd + ['twine', 'check'] + [tgz, wheel])
else:
self._call(
self.run_cmd + ['twine', 'upload'] + test + [tgz, wheel]
)
return self.returncode
def run_regen(self):
with open(self.parser_file, encoding='utf-8') as fp:
old = fp.read()
old_fname = self.parser_file + '.old'
try:
# We wrap this in a try block to ensure that if something
# goes wrong we restore the old version.
self._rename(self.parser_file, old_fname)
self._gen_parser()
with open(self.parser_file, encoding='utf-8') as fp:
new = fp.read()
if old != new:
if self.args.check:
if self.args.verbose:
print(
'Need to regenerate the parser with `run regen`:.'
)
self._call(
['diff', old_fname, self.parser_file],
indent=' ',
capture_output=True,
ignore_error=True,
)
else:
print(
'Need to regenerate the parser with `run regen`.'
)
else:
print(f'{self.parser_file} regenerated.')
elif not self.args.quiet:
print(f'{self.parser_file} is up-to-date.')
if old != new:
if self.args.check:
self._rename(old_fname, self.parser_file)
return 1
else:
self._remove(old_fname, quiet=True)
return self.returncode
except Exception:
if not os.path.exists(self.parser_file) and os.path.exists(
old_fname
):
self._rename(old_fname, self.parser_file)
raise
def _gen_parser(self):
cmd = self.run_cmd + [
'-m',
'glop',
'-o',
self.parser_file,
'--no-main',
'--no-memoize',
'-c',
self.grammar,
]
proc = self._call(cmd)
if proc.returncode:
return proc.returncode
# ignore the output from `ruff format`; glop currently produces
# files that need reformatting.
proc = self._call(
self.run_cmd + ['ruff', 'format', self.parser_file],
capture_output=True,
ignore_error=True,
)
return proc.returncode
def run_tests(self):
_ = self._call(self.run_cmd + ['doctest', 'json5/lib.py'])
cmd = self.run_cmd + [
'unittest',
'discover',
'-p',
'*_test.py',
]
if self.args.quiet:
cmd.append('-q')
if self.args.verbose:
cmd.append('-v')
if self.failfast:
cmd.append('-f')
if self.args.durations:
cmd.extend(['--durations', self.args.durations])
for test in self.args.test:
cmd.extend(['-k', self._trim_test_glob(test)])
env = os.environ.copy()
if self.args.unit:
env['SKIP'] = 'integration'
_ = self._call(cmd, env=env)
return self.returncode
def _call(self, args, indent='', ignore_error=False, **kwargs):
cmd = shlex.join(args)
verbose = kwargs.pop('verbose', self.args.verbose)
if self.args.no_execute or verbose:
print(f'{indent}{cmd}')
if self.args.no_execute:
return None
capture_output = kwargs.get('capture_output', self.args.quiet)
kwargs.pop('capture_output', None)
proc = subprocess.run(
args, capture_output=capture_output, check=False, **kwargs
)
if (proc.returncode or verbose) and not capture_output:
if proc.stdout:
print(self._indent(indent, proc.stdout.decode('utf8')))
if proc.stderr:
print(
self._indent(indent, proc.stderr.decode('utf8')),
file=sys.stderr,
)
if proc.returncode and not ignore_error:
if self.failfast:
raise FailFastException(proc.returncode)
self.returncode = proc.returncode
return proc
def _indent(self, indent, output):
line_sep = '\n' + indent
out = indent
out += line_sep.join(output.splitlines())
return out
def _rename(self, old, new):
if self.args.no_execute or self.args.verbose:
print(f'mv {old} {new}')
if not self.args.no_execute:
os.rename(old, new)
def _remove(self, fname, quiet=False):
if not os.path.exists(fname):
return
is_dir = os.path.isdir(fname)
dchar = '/' if is_dir else ''
try:
if self.args.check and not quiet:
print(f'Would remove {fname}{dchar}')
else:
if (
not self.args.quiet
and not quiet
and not self.args.no_execute
):
print(f'Removing {fname}{dchar}')
if os.path.isdir(fname):
if self.args.verbose or self.args.no_execute:
print(f'rm -fr {fname}{dchar}')
shutil.rmtree(fname)
else:
if self.args.verbose or self.args.no_execute:
print(f'rm -f {fname}{dchar}')
if not self.args.no_execute:
os.remove(fname)
except OSError as e:
print(e, file=sys.stderr)
raise FailFastException(1) from e
def _shuffle_argv(self, argv):
# Take any flags that appear before the subcommand and append
# them after the subcommand but before any flags following the
# subcommand.
leading_args = []
argc = len(argv)
i = 0
while i < argc:
if argv[i][0] != '-':
break
leading_args.append(argv[i])
if argv[i] in ('-p', '--python'):
leading_args.append(argv[i + 1])
i += 2
else:
i += 1
return argv[i : i + 1] + leading_args + argv[i + 1 :]
def _files(self):
return (
['./run']
+ glob.glob(f'{self.package}/*.py')
+ glob.glob('tests/*.py')
)
def _trim_test_glob(self, test):
if test.startswith('^'):
test = test[1:]
else:
test = '*' + test
if test.endswith('$'):
test = test[:-1]
else:
test = test + '*'
return test
def _check_version(self):
m = re.match(r'\d+\.\d+\.\d+(\.dev\d+)?', self.version)
if not m:
print(f'Unexpected version format: "{self.version}"')
raise FailFastException(1)
def is_supported_python_version(self):
def _to_str(l):
return ', '.join(l[:-1]) + ' and ' + l[-1]
partial = [
'3.' + str(x)
for x in range(MIN_PARTIAL_MINOR_VER, MAX_PARTIAL_MINOR_VER + 1)
]
full = [
'3.' + str(x)
for x in range(MIN_FULL_MINOR_VER, MAX_FULL_MINOR_VER + 1)
]
partial_only = [x for x in partial if x not in full]
full_str = f'{full[0]} to {full[-1]}'
partial_str = f'{partial[0]} to {partial[-1]}'
partial_only_str = _to_str(partial_only)
partial_commands_str = _to_str([f'`{x}`' for x in PARTIAL_COMMANDS])
is_uv = 'UV' in os.environ
ver = self.args.python
if self.venv and not is_uv:
if ver not in partial:
print(
f'Warning, this version of Python ({THIS_VER}) '
f'may not be supported. '
)
sys.stdout.flush()
else:
# Note: we explicitly want to prevent a hypothetical Python 4
# here, so we disable the ruff warning YTT201.
if sys.version_info[0] != 3 or ver not in partial: # noqa: YTT201
print(
f'This version of Python ({THIS_VER}) is not supported, '
f'only {partial_str} are.'
)
print(f'{full_str} are fully supported.')
print(
f'{partial_only_str} can only run {partial_commands_str}.'
)
return False
if ver not in full and self.args.command not in PARTIAL_COMMANDS:
print(
f'This version of Python ({THIS_VER}) is not fully '
f'supported and can only run {partial_commands_str}.'
)
return False
return True
if __name__ == '__main__':
sys.exit(Runner().main(sys.argv[1:]))
You can’t perform that action at this time.
