coverage 7.13.1__cp314-cp314t-musllinux_1_2_aarch64.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.
Files changed (61) hide show
  1. a1_coverage.pth +1 -0
  2. coverage/__init__.py +38 -0
  3. coverage/__main__.py +12 -0
  4. coverage/annotate.py +113 -0
  5. coverage/bytecode.py +197 -0
  6. coverage/cmdline.py +1220 -0
  7. coverage/collector.py +487 -0
  8. coverage/config.py +732 -0
  9. coverage/context.py +74 -0
  10. coverage/control.py +1514 -0
  11. coverage/core.py +139 -0
  12. coverage/data.py +251 -0
  13. coverage/debug.py +669 -0
  14. coverage/disposition.py +59 -0
  15. coverage/env.py +135 -0
  16. coverage/exceptions.py +85 -0
  17. coverage/execfile.py +329 -0
  18. coverage/files.py +553 -0
  19. coverage/html.py +860 -0
  20. coverage/htmlfiles/coverage_html.js +735 -0
  21. coverage/htmlfiles/favicon_32.png +0 -0
  22. coverage/htmlfiles/index.html +199 -0
  23. coverage/htmlfiles/keybd_closed.png +0 -0
  24. coverage/htmlfiles/pyfile.html +149 -0
  25. coverage/htmlfiles/style.css +389 -0
  26. coverage/htmlfiles/style.scss +844 -0
  27. coverage/inorout.py +590 -0
  28. coverage/jsonreport.py +200 -0
  29. coverage/lcovreport.py +218 -0
  30. coverage/misc.py +381 -0
  31. coverage/multiproc.py +120 -0
  32. coverage/numbits.py +146 -0
  33. coverage/parser.py +1215 -0
  34. coverage/patch.py +118 -0
  35. coverage/phystokens.py +197 -0
  36. coverage/plugin.py +617 -0
  37. coverage/plugin_support.py +299 -0
  38. coverage/pth_file.py +16 -0
  39. coverage/py.typed +1 -0
  40. coverage/python.py +272 -0
  41. coverage/pytracer.py +370 -0
  42. coverage/regions.py +127 -0
  43. coverage/report.py +298 -0
  44. coverage/report_core.py +117 -0
  45. coverage/results.py +502 -0
  46. coverage/sqldata.py +1212 -0
  47. coverage/sqlitedb.py +226 -0
  48. coverage/sysmon.py +509 -0
  49. coverage/templite.py +319 -0
  50. coverage/tomlconfig.py +212 -0
  51. coverage/tracer.cpython-314t-aarch64-linux-musl.so +0 -0
  52. coverage/tracer.pyi +43 -0
  53. coverage/types.py +214 -0
  54. coverage/version.py +35 -0
  55. coverage/xmlreport.py +263 -0
  56. coverage-7.13.1.dist-info/METADATA +200 -0
  57. coverage-7.13.1.dist-info/RECORD +61 -0
  58. coverage-7.13.1.dist-info/WHEEL +5 -0
  59. coverage-7.13.1.dist-info/entry_points.txt +4 -0
  60. coverage-7.13.1.dist-info/licenses/LICENSE.txt +177 -0
  61. coverage-7.13.1.dist-info/top_level.txt +1 -0
coverage/cmdline.py ADDED
@@ -0,0 +1,1220 @@
1
+ # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
2
+ # For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
3
+
4
+ """Command-line support for coverage.py."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import glob
9
+ import optparse
10
+ import os
11
+ import os.path
12
+ import shlex
13
+ import signal
14
+ import sys
15
+ import textwrap
16
+ import traceback
17
+ import types
18
+ from typing import Any, NoReturn, cast
19
+
20
+ import coverage
21
+ from coverage import Coverage, env
22
+ from coverage.config import CoverageConfig
23
+ from coverage.control import DEFAULT_DATAFILE
24
+ from coverage.core import CTRACER_FILE
25
+ from coverage.data import CoverageData, combinable_files, debug_data_file
26
+ from coverage.debug import info_header, short_stack, write_formatted_info
27
+ from coverage.exceptions import NoSource, CoverageException, _ExceptionDuringRun
28
+ from coverage.execfile import PyRunner
29
+ from coverage.results import display_covered, should_fail_under
30
+ from coverage.version import __url__
31
+
32
+ # When adding to this file, alphabetization is important. Look for
33
+ # "alphabetize" comments throughout.
34
+
35
+
36
+ def prep_help(text: str) -> str:
37
+ r"""Prepare a multi-line string for help to reformat nicely.
38
+
39
+ A \f character indicates a paragraph break.
40
+ """
41
+ return "\f".join(" ".join(p.split()) for p in text.split("\f"))
42
+
43
+
44
+ class Opts:
45
+ """A namespace class for individual options we'll build parsers from."""
46
+
47
+ # Keep these entries alphabetized (roughly) by the option name as it
48
+ # appears on the command line.
49
+
50
+ append = optparse.make_option(
51
+ "-a",
52
+ "--append",
53
+ action="store_true",
54
+ help="Append data to the data file. Otherwise it starts clean each time.",
55
+ )
56
+ branch = optparse.make_option(
57
+ "",
58
+ "--branch",
59
+ action="store_true",
60
+ help="Measure branch coverage in addition to statement coverage.",
61
+ )
62
+ concurrency = optparse.make_option(
63
+ "",
64
+ "--concurrency",
65
+ action="store",
66
+ metavar="LIBS",
67
+ help=prep_help(
68
+ """
69
+ Properly measure code using a concurrency library.
70
+ Valid values are: {}, or a comma-list of them.
71
+ """
72
+ ).format(", ".join(sorted(CoverageConfig.CONCURRENCY_CHOICES))),
73
+ )
74
+ context = optparse.make_option(
75
+ "",
76
+ "--context",
77
+ action="store",
78
+ metavar="LABEL",
79
+ help="The context label to record for this coverage run.",
80
+ )
81
+ contexts = optparse.make_option(
82
+ "",
83
+ "--contexts",
84
+ action="store",
85
+ metavar="REGEX1,REGEX2,...",
86
+ help=prep_help(
87
+ """
88
+ Only display data from lines covered in the given contexts.
89
+ Accepts Python regexes, which must be quoted.
90
+ """
91
+ ),
92
+ )
93
+ datafile = optparse.make_option(
94
+ "",
95
+ "--data-file",
96
+ action="store",
97
+ metavar="DATAFILE",
98
+ help=prep_help(
99
+ """
100
+ Base name of the data files to operate on.
101
+ Defaults to '.coverage'. [env: COVERAGE_FILE]
102
+ """
103
+ ),
104
+ )
105
+ datafle_input = optparse.make_option(
106
+ "",
107
+ "--data-file",
108
+ action="store",
109
+ metavar="INFILE",
110
+ help=prep_help(
111
+ """
112
+ Read coverage data for report generation from this file.
113
+ Defaults to '.coverage'. [env: COVERAGE_FILE]
114
+ """
115
+ ),
116
+ )
117
+ datafile_output = optparse.make_option(
118
+ "",
119
+ "--data-file",
120
+ action="store",
121
+ metavar="OUTFILE",
122
+ help=prep_help(
123
+ """
124
+ Write the recorded coverage data to this file.
125
+ Defaults to '.coverage'. [env: COVERAGE_FILE]
126
+ """
127
+ ),
128
+ )
129
+ debug = optparse.make_option(
130
+ "",
131
+ "--debug",
132
+ action="store",
133
+ metavar="OPTS",
134
+ help="Debug options, separated by commas. [env: COVERAGE_DEBUG]",
135
+ )
136
+ directory = optparse.make_option(
137
+ "-d",
138
+ "--directory",
139
+ action="store",
140
+ metavar="DIR",
141
+ help="Write the output files to DIR.",
142
+ )
143
+ fail_under = optparse.make_option(
144
+ "",
145
+ "--fail-under",
146
+ action="store",
147
+ metavar="MIN",
148
+ type="float",
149
+ help="Exit with a status of 2 if the total coverage is less than MIN.",
150
+ )
151
+ format = optparse.make_option(
152
+ "",
153
+ "--format",
154
+ action="store",
155
+ metavar="FORMAT",
156
+ help="Output format, either text (default), markdown, or total.",
157
+ )
158
+ help = optparse.make_option(
159
+ "-h",
160
+ "--help",
161
+ action="store_true",
162
+ help="Get help on this command.",
163
+ )
164
+ ignore_errors = optparse.make_option(
165
+ "-i",
166
+ "--ignore-errors",
167
+ action="store_true",
168
+ help="Ignore errors while reading source files.",
169
+ )
170
+ include = optparse.make_option(
171
+ "",
172
+ "--include",
173
+ action="store",
174
+ metavar="PAT1,PAT2,...",
175
+ help=prep_help(
176
+ """
177
+ Include only files whose paths match one of these patterns.
178
+ Accepts shell-style wildcards, which must be quoted.
179
+ """
180
+ ),
181
+ )
182
+ keep = optparse.make_option(
183
+ "",
184
+ "--keep",
185
+ action="store_true",
186
+ help="Keep original coverage files, otherwise they are deleted.",
187
+ )
188
+ pylib = optparse.make_option(
189
+ "-L",
190
+ "--pylib",
191
+ action="store_true",
192
+ help=prep_help(
193
+ """
194
+ Measure coverage even inside the Python installed library,
195
+ which isn't done by default.
196
+ """
197
+ ),
198
+ )
199
+ show_missing = optparse.make_option(
200
+ "-m",
201
+ "--show-missing",
202
+ action="store_true",
203
+ help="Show line numbers of statements in each module that weren't executed.",
204
+ )
205
+ module = optparse.make_option(
206
+ "-m",
207
+ "--module",
208
+ action="store_true",
209
+ help=prep_help(
210
+ """
211
+ <pyfile> is an importable Python module, not a script path,
212
+ to be run as 'python -m' would run it.
213
+ """
214
+ ),
215
+ )
216
+ omit = optparse.make_option(
217
+ "",
218
+ "--omit",
219
+ action="store",
220
+ metavar="PAT1,PAT2,...",
221
+ help=prep_help(
222
+ """
223
+ Omit files whose paths match one of these patterns.
224
+ Accepts shell-style wildcards, which must be quoted.
225
+ """
226
+ ),
227
+ )
228
+ output_xml = optparse.make_option(
229
+ "-o",
230
+ "",
231
+ action="store",
232
+ dest="outfile",
233
+ metavar="OUTFILE",
234
+ help="Write the XML report to this file. Defaults to 'coverage.xml'",
235
+ )
236
+ output_json = optparse.make_option(
237
+ "-o",
238
+ "",
239
+ action="store",
240
+ dest="outfile",
241
+ metavar="OUTFILE",
242
+ help="Write the JSON report to this file. Defaults to 'coverage.json'",
243
+ )
244
+ output_lcov = optparse.make_option(
245
+ "-o",
246
+ "",
247
+ action="store",
248
+ dest="outfile",
249
+ metavar="OUTFILE",
250
+ help="Write the LCOV report to this file. Defaults to 'coverage.lcov'",
251
+ )
252
+ json_pretty_print = optparse.make_option(
253
+ "",
254
+ "--pretty-print",
255
+ action="store_true",
256
+ help="Format the JSON for human readers.",
257
+ )
258
+ parallel_mode = optparse.make_option(
259
+ "-p",
260
+ "--parallel-mode",
261
+ action="store_true",
262
+ help=prep_help(
263
+ """
264
+ Append a unique suffix to the data file name to collect separate
265
+ data from multiple processes.
266
+ """
267
+ ),
268
+ )
269
+ precision = optparse.make_option(
270
+ "",
271
+ "--precision",
272
+ action="store",
273
+ metavar="N",
274
+ type=int,
275
+ help=prep_help(
276
+ """
277
+ Number of digits after the decimal point to display for
278
+ reported coverage percentages.
279
+ """
280
+ ),
281
+ )
282
+ quiet = optparse.make_option(
283
+ "-q",
284
+ "--quiet",
285
+ action="store_true",
286
+ help="Don't print messages about what is happening.",
287
+ )
288
+ rcfile = optparse.make_option(
289
+ "",
290
+ "--rcfile",
291
+ action="store",
292
+ help=prep_help(
293
+ """
294
+ Specify configuration file.
295
+ By default '.coveragerc', 'setup.cfg', 'tox.ini', and
296
+ 'pyproject.toml' are tried. [env: COVERAGE_RCFILE]
297
+ """
298
+ ),
299
+ )
300
+ save_signal = optparse.make_option(
301
+ "",
302
+ "--save-signal",
303
+ action="store",
304
+ metavar="SIGNAL",
305
+ choices=["USR1", "USR2"],
306
+ help=prep_help(
307
+ """
308
+ Specify a signal that will trigger coverage to write its collected data.
309
+ Supported values are: USR1, USR2. Not available on Windows.
310
+ """
311
+ ),
312
+ )
313
+ show_contexts = optparse.make_option(
314
+ "--show-contexts",
315
+ action="store_true",
316
+ help="Show contexts for covered lines.",
317
+ )
318
+ skip_covered = optparse.make_option(
319
+ "--skip-covered",
320
+ action="store_true",
321
+ help="Skip files with 100% coverage.",
322
+ )
323
+ no_skip_covered = optparse.make_option(
324
+ "--no-skip-covered",
325
+ action="store_false",
326
+ dest="skip_covered",
327
+ help="Disable --skip-covered.",
328
+ )
329
+ skip_empty = optparse.make_option(
330
+ "--skip-empty",
331
+ action="store_true",
332
+ help="Skip files with no code.",
333
+ )
334
+ sort = optparse.make_option(
335
+ "--sort",
336
+ action="store",
337
+ metavar="COLUMN",
338
+ help=prep_help(
339
+ """
340
+ Sort the report by the named column: name, stmts, miss, branch, brpart, or cover.
341
+ Default is name.
342
+ """
343
+ ),
344
+ )
345
+ source = optparse.make_option(
346
+ "",
347
+ "--source",
348
+ action="store",
349
+ metavar="SRC1,SRC2,...",
350
+ help="A list of directories or importable names of code to measure.",
351
+ )
352
+ timid = optparse.make_option(
353
+ "",
354
+ "--timid",
355
+ action="store_true",
356
+ help="Use the slower Python trace function core.",
357
+ )
358
+ title = optparse.make_option(
359
+ "",
360
+ "--title",
361
+ action="store",
362
+ metavar="TITLE",
363
+ help="A text string to use as the title on the HTML.",
364
+ )
365
+ version = optparse.make_option(
366
+ "",
367
+ "--version",
368
+ action="store_true",
369
+ help="Display version information and exit.",
370
+ )
371
+
372
+
373
+ class CoverageOptionParser(optparse.OptionParser):
374
+ """Base OptionParser for coverage.py.
375
+
376
+ Problems don't exit the program.
377
+ Defaults are initialized for all options.
378
+
379
+ """
380
+
381
+ def __init__(self, **kwargs: Any) -> None:
382
+ super().__init__(
383
+ add_help_option=False,
384
+ formatter=MultiParaHelpFormatter(),
385
+ **kwargs,
386
+ )
387
+ self.set_defaults(
388
+ # Keep these arguments alphabetized by their names.
389
+ action=None,
390
+ append=None,
391
+ branch=None,
392
+ concurrency=None,
393
+ context=None,
394
+ contexts=None,
395
+ data_file=None,
396
+ debug=None,
397
+ directory=None,
398
+ fail_under=None,
399
+ format=None,
400
+ help=None,
401
+ ignore_errors=None,
402
+ include=None,
403
+ keep=None,
404
+ module=None,
405
+ omit=None,
406
+ parallel_mode=None,
407
+ precision=None,
408
+ pylib=None,
409
+ quiet=None,
410
+ rcfile=True,
411
+ save_signal=None,
412
+ show_contexts=None,
413
+ show_missing=None,
414
+ skip_covered=None,
415
+ skip_empty=None,
416
+ sort=None,
417
+ source=None,
418
+ timid=None,
419
+ title=None,
420
+ version=None,
421
+ )
422
+
423
+ self.disable_interspersed_args()
424
+
425
+ class OptionParserError(Exception):
426
+ """Used to stop the optparse error handler ending the process."""
427
+
428
+ pass
429
+
430
+ def parse_args_ok(self, args: list[str]) -> tuple[bool, optparse.Values | None, list[str]]:
431
+ """Call optparse.parse_args, but return a triple:
432
+
433
+ (ok, options, args)
434
+
435
+ """
436
+ try:
437
+ options, args = super().parse_args(args)
438
+ except self.OptionParserError:
439
+ return False, None, []
440
+ return True, options, args
441
+
442
+ def error(self, msg: str) -> NoReturn:
443
+ """Override optparse.error so sys.exit doesn't get called."""
444
+ show_help(msg)
445
+ raise self.OptionParserError
446
+
447
+
448
+ class GlobalOptionParser(CoverageOptionParser):
449
+ """Command-line parser for coverage.py global option arguments."""
450
+
451
+ def __init__(self) -> None:
452
+ super().__init__()
453
+
454
+ self.add_options(
455
+ [
456
+ Opts.help,
457
+ Opts.version,
458
+ ]
459
+ )
460
+
461
+
462
+ class MultiParaHelpFormatter(optparse.IndentedHelpFormatter):
463
+ """An optparse formatter that allows multi-paragraph help text."""
464
+
465
+ def _format_text(self, text: str) -> str:
466
+ r"""
467
+ Format help text. \f characters become paragraph breaks with blank lines.
468
+ """
469
+ # _format_text is not documented in optparse, so mypy can't find it.
470
+ super_format = super()._format_text # type: ignore[misc]
471
+ paras = text.split("\f")
472
+ return "\n\n".join(super_format(p) for p in paras)
473
+
474
+
475
+ class CmdOptionParser(CoverageOptionParser):
476
+ """Parse one of the new-style commands for coverage.py."""
477
+
478
+ def __init__(
479
+ self,
480
+ action: str,
481
+ options: list[optparse.Option],
482
+ description: str,
483
+ usage: str | None = None,
484
+ ):
485
+ """Create an OptionParser for a coverage.py command.
486
+
487
+ `action` is the slug to put into `options.action`.
488
+ `options` is a list of Option's for the command.
489
+ `description` is the description of the command, for the help text.
490
+ `usage` is the usage string to display in help.
491
+
492
+ """
493
+ if usage:
494
+ usage = "%prog " + usage
495
+ super().__init__(
496
+ usage=usage,
497
+ description=description,
498
+ )
499
+ self.set_defaults(action=action)
500
+ self.add_options(options)
501
+ self.cmd = action
502
+
503
+ def __eq__(self, other: str) -> bool: # type: ignore[override]
504
+ # A convenience equality, so that I can put strings in unit test
505
+ # results, and they will compare equal to objects.
506
+ return other == f"<CmdOptionParser:{self.cmd}>"
507
+
508
+ __hash__ = None # type: ignore[assignment]
509
+
510
+ def get_prog_name(self) -> str:
511
+ """Override of an undocumented function in optparse.OptionParser."""
512
+ program_name = super().get_prog_name()
513
+
514
+ # Include the sub-command for this parser as part of the command.
515
+ return f"{program_name} {self.cmd}"
516
+
517
+
518
+ # In lists of Opts, keep them alphabetized by the option names as they appear
519
+ # on the command line, since these lists determine the order of the options in
520
+ # the help output.
521
+ #
522
+ # In COMMANDS, keep the keys (command names) alphabetized.
523
+
524
+ GLOBAL_ARGS = [
525
+ Opts.debug,
526
+ Opts.help,
527
+ Opts.rcfile,
528
+ ]
529
+
530
+ COMMANDS = {
531
+ "annotate": CmdOptionParser(
532
+ "annotate",
533
+ [
534
+ Opts.directory,
535
+ Opts.datafle_input,
536
+ Opts.ignore_errors,
537
+ Opts.include,
538
+ Opts.omit,
539
+ ]
540
+ + GLOBAL_ARGS,
541
+ usage="[options] [modules]",
542
+ description=prep_help(
543
+ """
544
+ Make annotated copies of the given files, marking statements that are executed
545
+ with > and statements that are missed with !.
546
+ """
547
+ ),
548
+ ),
549
+ "combine": CmdOptionParser(
550
+ "combine",
551
+ [
552
+ Opts.append,
553
+ Opts.datafile,
554
+ Opts.keep,
555
+ Opts.quiet,
556
+ ]
557
+ + GLOBAL_ARGS,
558
+ usage="[options] <path1> <path2> ... <pathN>",
559
+ description=prep_help(
560
+ """
561
+ Combine data from multiple coverage files.
562
+ The combined results are written to a single
563
+ file representing the union of the data. The positional
564
+ arguments are data files or directories containing data files.
565
+ If no paths are provided, data files in the default data file's
566
+ directory are combined.
567
+ """
568
+ ),
569
+ ),
570
+ "debug": CmdOptionParser(
571
+ "debug",
572
+ GLOBAL_ARGS,
573
+ usage="<topic>",
574
+ description=prep_help(
575
+ """
576
+ Display information about the internals of coverage.py,
577
+ for diagnosing problems. Topics are:
578
+ \f 'config' to show configuration settings.
579
+ \f 'data [filenames]' to summarize data files.
580
+ \f 'premain' to show what is calling coverage.
581
+ \f 'pybehave' to show internal flags describing Python behavior.
582
+ \f 'sqlite' to show SQLite compilation options.
583
+ \f 'sys' to show installation information.
584
+ """
585
+ ),
586
+ ),
587
+ "erase": CmdOptionParser(
588
+ "erase",
589
+ [
590
+ Opts.datafile,
591
+ ]
592
+ + GLOBAL_ARGS,
593
+ description="Erase previously collected coverage data.",
594
+ ),
595
+ "help": CmdOptionParser(
596
+ "help",
597
+ GLOBAL_ARGS,
598
+ usage="[command]",
599
+ description="Describe how to use coverage.py",
600
+ ),
601
+ "html": CmdOptionParser(
602
+ "html",
603
+ [
604
+ Opts.contexts,
605
+ Opts.directory,
606
+ Opts.datafle_input,
607
+ Opts.fail_under,
608
+ Opts.ignore_errors,
609
+ Opts.include,
610
+ Opts.omit,
611
+ Opts.precision,
612
+ Opts.quiet,
613
+ Opts.show_contexts,
614
+ Opts.skip_covered,
615
+ Opts.no_skip_covered,
616
+ Opts.skip_empty,
617
+ Opts.title,
618
+ ]
619
+ + GLOBAL_ARGS,
620
+ usage="[options] [modules]",
621
+ description=prep_help(
622
+ """
623
+ Create an HTML report of the coverage of the files.
624
+ Each file gets its own page, with the source decorated to show
625
+ executed, excluded, and missed lines.
626
+ """
627
+ ),
628
+ ),
629
+ "json": CmdOptionParser(
630
+ "json",
631
+ [
632
+ Opts.contexts,
633
+ Opts.datafle_input,
634
+ Opts.fail_under,
635
+ Opts.ignore_errors,
636
+ Opts.include,
637
+ Opts.omit,
638
+ Opts.output_json,
639
+ Opts.json_pretty_print,
640
+ Opts.quiet,
641
+ Opts.show_contexts,
642
+ ]
643
+ + GLOBAL_ARGS,
644
+ usage="[options] [modules]",
645
+ description="Generate a JSON report of coverage results.",
646
+ ),
647
+ "lcov": CmdOptionParser(
648
+ "lcov",
649
+ [
650
+ Opts.datafle_input,
651
+ Opts.fail_under,
652
+ Opts.ignore_errors,
653
+ Opts.include,
654
+ Opts.output_lcov,
655
+ Opts.omit,
656
+ Opts.quiet,
657
+ ]
658
+ + GLOBAL_ARGS,
659
+ usage="[options] [modules]",
660
+ description="Generate an LCOV report of coverage results.",
661
+ ),
662
+ "report": CmdOptionParser(
663
+ "report",
664
+ [
665
+ Opts.contexts,
666
+ Opts.datafle_input,
667
+ Opts.fail_under,
668
+ Opts.format,
669
+ Opts.ignore_errors,
670
+ Opts.include,
671
+ Opts.omit,
672
+ Opts.precision,
673
+ Opts.sort,
674
+ Opts.show_missing,
675
+ Opts.skip_covered,
676
+ Opts.no_skip_covered,
677
+ Opts.skip_empty,
678
+ ]
679
+ + GLOBAL_ARGS,
680
+ usage="[options] [modules]",
681
+ description="Report coverage statistics on modules.",
682
+ ),
683
+ "run": CmdOptionParser(
684
+ "run",
685
+ [
686
+ Opts.append,
687
+ Opts.branch,
688
+ Opts.concurrency,
689
+ Opts.context,
690
+ Opts.datafile_output,
691
+ Opts.include,
692
+ Opts.module,
693
+ Opts.omit,
694
+ Opts.pylib,
695
+ Opts.parallel_mode,
696
+ Opts.save_signal,
697
+ Opts.source,
698
+ Opts.timid,
699
+ ]
700
+ + GLOBAL_ARGS,
701
+ usage="[options] <pyfile> [program options]",
702
+ description="Run a Python program, measuring code execution.",
703
+ ),
704
+ "xml": CmdOptionParser(
705
+ "xml",
706
+ [
707
+ Opts.datafle_input,
708
+ Opts.fail_under,
709
+ Opts.ignore_errors,
710
+ Opts.include,
711
+ Opts.omit,
712
+ Opts.output_xml,
713
+ Opts.quiet,
714
+ Opts.skip_empty,
715
+ ]
716
+ + GLOBAL_ARGS,
717
+ usage="[options] [modules]",
718
+ description="Generate an XML report of coverage results.",
719
+ ),
720
+ }
721
+
722
+
723
+ def show_help(
724
+ error: str | None = None,
725
+ topic: str | None = None,
726
+ parser: optparse.OptionParser | None = None,
727
+ ) -> None:
728
+ """Display an error message, or the named topic."""
729
+ assert error or topic or parser
730
+
731
+ program_path = sys.argv[0]
732
+ if program_path.endswith(os.path.sep + "__main__.py"):
733
+ # The path is the main module of a package; get that path instead.
734
+ program_path = os.path.dirname(program_path)
735
+ program_name = os.path.basename(program_path)
736
+ if env.WINDOWS:
737
+ # entry_points={"console_scripts":...} on Windows makes files
738
+ # called coverage.exe, coverage3.exe, and coverage-3.5.exe. These
739
+ # invoke coverage-script.py, coverage3-script.py, and
740
+ # coverage-3.5-script.py. argv[0] is the .py file, but we want to
741
+ # get back to the original form.
742
+ auto_suffix = "-script.py"
743
+ if program_name.endswith(auto_suffix):
744
+ program_name = program_name[: -len(auto_suffix)]
745
+
746
+ help_params = dict(coverage.__dict__)
747
+ help_params["__url__"] = __url__
748
+ help_params["program_name"] = program_name
749
+ if CTRACER_FILE:
750
+ help_params["extension_modifier"] = "with C extension"
751
+ else:
752
+ help_params["extension_modifier"] = "without C extension"
753
+
754
+ if error:
755
+ print(error, file=sys.stderr)
756
+ print(f"Use '{program_name} help' for help.", file=sys.stderr)
757
+ elif parser:
758
+ print(parser.format_help().strip())
759
+ print()
760
+ else:
761
+ assert topic is not None
762
+ help_msg = textwrap.dedent(HELP_TOPICS.get(topic, "")).strip()
763
+ if help_msg:
764
+ print(help_msg.format(**help_params))
765
+ else:
766
+ print(f"Don't know topic {topic!r}")
767
+ print("Full documentation is at {__url__}".format(**help_params))
768
+
769
+
770
+ OK, ERR, FAIL_UNDER = 0, 1, 2
771
+
772
+
773
+ class CoverageScript:
774
+ """The command-line interface to coverage.py."""
775
+
776
+ def __init__(self) -> None:
777
+ self.global_option = False
778
+ self.coverage: Coverage
779
+
780
+ def command_line(self, argv: list[str]) -> int:
781
+ """The bulk of the command line interface to coverage.py.
782
+
783
+ `argv` is the argument list to process.
784
+
785
+ Returns 0 if all is well, 1 if something went wrong.
786
+
787
+ """
788
+ # Collect the command-line options.
789
+ if not argv:
790
+ show_help(topic="minimum_help")
791
+ return OK
792
+
793
+ # The command syntax we parse depends on the first argument. Global
794
+ # switch syntax always starts with an option.
795
+ parser: optparse.OptionParser | None
796
+ self.global_option = argv[0].startswith("-")
797
+ if self.global_option:
798
+ parser = GlobalOptionParser()
799
+ else:
800
+ parser = COMMANDS.get(argv[0])
801
+ if not parser:
802
+ show_help(f"Unknown command: {argv[0]!r}")
803
+ return ERR
804
+ argv = argv[1:]
805
+
806
+ ok, options, args = parser.parse_args_ok(argv)
807
+ if not ok:
808
+ return ERR
809
+ assert options is not None
810
+
811
+ # Handle help and version.
812
+ if self.do_help(options, args, parser):
813
+ return OK
814
+
815
+ # Listify the list options.
816
+ source = unshell_list(options.source)
817
+ omit = unshell_list(options.omit)
818
+ include = unshell_list(options.include)
819
+ debug = unshell_list(options.debug)
820
+ contexts = unshell_list(options.contexts)
821
+
822
+ if options.concurrency is not None:
823
+ concurrency = options.concurrency.split(",")
824
+ else:
825
+ concurrency = None
826
+
827
+ # Do something.
828
+ self.coverage = Coverage(
829
+ data_file=options.data_file or DEFAULT_DATAFILE,
830
+ data_suffix=options.parallel_mode,
831
+ cover_pylib=options.pylib,
832
+ timid=options.timid,
833
+ branch=options.branch,
834
+ config_file=options.rcfile,
835
+ source=source,
836
+ omit=omit,
837
+ include=include,
838
+ debug=debug,
839
+ concurrency=concurrency,
840
+ check_preimported=True,
841
+ context=options.context,
842
+ messages=not options.quiet,
843
+ )
844
+
845
+ if options.action == "debug":
846
+ return self.do_debug(args)
847
+
848
+ elif options.action == "erase":
849
+ self.coverage.erase()
850
+ return OK
851
+
852
+ elif options.action == "run":
853
+ return self.do_run(options, args)
854
+
855
+ elif options.action == "combine":
856
+ if options.append:
857
+ self.coverage.load()
858
+ data_paths = args or None
859
+ self.coverage.combine(data_paths, strict=True, keep=bool(options.keep))
860
+ self.coverage.save()
861
+ return OK
862
+
863
+ # Remaining actions are reporting, with some common options.
864
+ report_args: dict[str, Any] = dict(
865
+ morfs=unglob_args(args),
866
+ ignore_errors=options.ignore_errors,
867
+ omit=omit,
868
+ include=include,
869
+ contexts=contexts,
870
+ )
871
+
872
+ # We need to be able to import from the current directory, because
873
+ # plugins may try to, for example, to read Django settings.
874
+ sys.path.insert(0, "")
875
+
876
+ self.coverage.load()
877
+
878
+ total = None
879
+ if options.action == "report":
880
+ total = self.coverage.report(
881
+ precision=options.precision,
882
+ show_missing=options.show_missing,
883
+ skip_covered=options.skip_covered,
884
+ skip_empty=options.skip_empty,
885
+ sort=options.sort,
886
+ output_format=options.format,
887
+ **report_args,
888
+ )
889
+ elif options.action == "annotate":
890
+ self.coverage.annotate(directory=options.directory, **report_args)
891
+ elif options.action == "html":
892
+ total = self.coverage.html_report(
893
+ directory=options.directory,
894
+ precision=options.precision,
895
+ skip_covered=options.skip_covered,
896
+ skip_empty=options.skip_empty,
897
+ show_contexts=options.show_contexts,
898
+ title=options.title,
899
+ **report_args,
900
+ )
901
+ elif options.action == "xml":
902
+ total = self.coverage.xml_report(
903
+ outfile=options.outfile,
904
+ skip_empty=options.skip_empty,
905
+ **report_args,
906
+ )
907
+ elif options.action == "json":
908
+ total = self.coverage.json_report(
909
+ outfile=options.outfile,
910
+ pretty_print=options.pretty_print,
911
+ show_contexts=options.show_contexts,
912
+ **report_args,
913
+ )
914
+ elif options.action == "lcov":
915
+ total = self.coverage.lcov_report(
916
+ outfile=options.outfile,
917
+ **report_args,
918
+ )
919
+ else:
920
+ # There are no other possible actions.
921
+ raise AssertionError
922
+
923
+ if total is not None:
924
+ # Apply the command line fail-under options, and then use the config
925
+ # value, so we can get fail_under from the config file.
926
+ if options.fail_under is not None:
927
+ self.coverage.set_option("report:fail_under", options.fail_under)
928
+ if options.precision is not None:
929
+ self.coverage.set_option("report:precision", options.precision)
930
+
931
+ fail_under = cast(float, self.coverage.get_option("report:fail_under"))
932
+ precision = cast(int, self.coverage.get_option("report:precision"))
933
+ if should_fail_under(total, fail_under, precision):
934
+ msg = "total of {total} is less than fail-under={fail_under:.{p}f}".format(
935
+ total=display_covered(total, precision),
936
+ fail_under=fail_under,
937
+ p=precision,
938
+ )
939
+ print("Coverage failure:", msg)
940
+ return FAIL_UNDER
941
+
942
+ return OK
943
+
944
+ def do_help(
945
+ self,
946
+ options: optparse.Values,
947
+ args: list[str],
948
+ parser: optparse.OptionParser,
949
+ ) -> bool:
950
+ """Deal with help requests.
951
+
952
+ Return True if it handled the request, False if not.
953
+
954
+ """
955
+ # Handle help.
956
+ if options.help:
957
+ if self.global_option:
958
+ show_help(topic="help")
959
+ else:
960
+ show_help(parser=parser)
961
+ return True
962
+
963
+ if options.action == "help":
964
+ if args:
965
+ for a in args:
966
+ parser_maybe = COMMANDS.get(a)
967
+ if parser_maybe is not None:
968
+ show_help(parser=parser_maybe)
969
+ else:
970
+ show_help(topic=a)
971
+ else:
972
+ show_help(topic="help")
973
+ return True
974
+
975
+ # Handle version.
976
+ if options.version:
977
+ show_help(topic="version")
978
+ return True
979
+
980
+ return False
981
+
982
+ def do_signal_save(self, _signum: int, _frame: types.FrameType | None) -> None:
983
+ """Signal handler to save coverage report"""
984
+ print("Saving coverage data...", flush=True)
985
+ self.coverage.save()
986
+
987
+ def do_run(self, options: optparse.Values, args: list[str]) -> int:
988
+ """Implementation of 'coverage run'."""
989
+
990
+ if not args:
991
+ if options.module:
992
+ # Specified -m with nothing else.
993
+ show_help("No module specified for -m")
994
+ return ERR
995
+ command_line = cast(str, self.coverage.get_option("run:command_line"))
996
+ if command_line is not None:
997
+ args = shlex.split(command_line)
998
+ if args and args[0] in {"-m", "--module"}:
999
+ options.module = True
1000
+ args = args[1:]
1001
+ if not args:
1002
+ show_help("Nothing to do.")
1003
+ return ERR
1004
+
1005
+ if options.append and self.coverage.get_option("run:parallel"):
1006
+ show_help("Can't append to data files in parallel mode.")
1007
+ return ERR
1008
+
1009
+ if options.concurrency == "multiprocessing":
1010
+ # Can't set other run-affecting command line options with
1011
+ # multiprocessing.
1012
+ for opt_name in ["branch", "include", "omit", "pylib", "source", "timid"]:
1013
+ # As it happens, all of these options have no default, meaning
1014
+ # they will be None if they have not been specified.
1015
+ if getattr(options, opt_name) is not None:
1016
+ show_help(
1017
+ "Options affecting multiprocessing must only be specified "
1018
+ + "in a configuration file.\n"
1019
+ + f"Remove --{opt_name} from the command line.",
1020
+ )
1021
+ return ERR
1022
+
1023
+ os.environ["COVERAGE_RUN"] = "true"
1024
+
1025
+ runner = PyRunner(args, as_module=bool(options.module))
1026
+ runner.prepare()
1027
+
1028
+ if options.append:
1029
+ self.coverage.load()
1030
+
1031
+ if options.save_signal:
1032
+ if env.WINDOWS:
1033
+ show_help("--save-signal is not supported on Windows.")
1034
+ return ERR
1035
+ sig = getattr(signal, f"SIG{options.save_signal}")
1036
+ signal.signal(sig, self.do_signal_save)
1037
+
1038
+ # Run the script.
1039
+ self.coverage.start()
1040
+ code_ran = True
1041
+ try:
1042
+ runner.run()
1043
+ except NoSource:
1044
+ code_ran = False
1045
+ raise
1046
+ finally:
1047
+ self.coverage.stop()
1048
+ if code_ran:
1049
+ self.coverage.save()
1050
+
1051
+ return OK
1052
+
1053
+ def do_debug(self, args: list[str]) -> int:
1054
+ """Implementation of 'coverage debug'."""
1055
+
1056
+ if not args:
1057
+ show_help(
1058
+ "What information would you like: "
1059
+ + "config, data, sys, premain, pybehave, sqlite?"
1060
+ )
1061
+ return ERR
1062
+
1063
+ if args[0] == "data":
1064
+ file_names = args[1:]
1065
+ if not file_names:
1066
+ file_names = [self.coverage.config.data_file]
1067
+ for data_file in file_names:
1068
+ print(info_header("data"))
1069
+ debug_data_file(data_file)
1070
+ for filename in combinable_files(data_file):
1071
+ print("-----")
1072
+ debug_data_file(filename)
1073
+ else:
1074
+ if args[1:]:
1075
+ show_help(f"'debug {args[0]}' takes no additional arguments")
1076
+ return ERR
1077
+ if args[0] == "sys":
1078
+ write_formatted_info(print, "sys", self.coverage.sys_info())
1079
+ elif args[0] == "config":
1080
+ write_formatted_info(print, "config", self.coverage.config.debug_info())
1081
+ elif args[0] == "premain":
1082
+ print(info_header("premain"))
1083
+ print(short_stack(full=True))
1084
+ elif args[0] == "pybehave":
1085
+ write_formatted_info(print, "pybehave", env.debug_info())
1086
+ elif args[0] == "sqlite":
1087
+ write_formatted_info(print, "sqlite", CoverageData.sys_info())
1088
+ else:
1089
+ show_help(f"Don't know what you mean by {args[0]!r}")
1090
+ return ERR
1091
+
1092
+ return OK
1093
+
1094
+
1095
+ def unshell_list(s: str) -> list[str] | None:
1096
+ """Turn a command-line argument into a list."""
1097
+ if not s:
1098
+ return None
1099
+ if env.WINDOWS:
1100
+ # When running coverage.py as coverage.exe, some of the behavior
1101
+ # of the shell is emulated: wildcards are expanded into a list of
1102
+ # file names. So you have to single-quote patterns on the command
1103
+ # line, but (not) helpfully, the single quotes are included in the
1104
+ # argument, so we have to strip them off here.
1105
+ s = s.strip("'")
1106
+ return s.split(",")
1107
+
1108
+
1109
+ def unglob_args(args: list[str]) -> list[str]:
1110
+ """Interpret shell wildcards for platforms that need it."""
1111
+ if env.WINDOWS:
1112
+ globbed = []
1113
+ for arg in args:
1114
+ if "?" in arg or "*" in arg:
1115
+ globbed.extend(glob.glob(arg))
1116
+ else:
1117
+ globbed.append(arg)
1118
+ args = globbed
1119
+ return args
1120
+
1121
+
1122
+ HELP_TOPICS = {
1123
+ "help": """\
1124
+ Coverage.py, version {__version__} {extension_modifier}
1125
+ Measure, collect, and report on code coverage in Python programs.
1126
+
1127
+ usage: {program_name} <command> [options] [args]
1128
+
1129
+ Commands:
1130
+ annotate Annotate source files with execution information.
1131
+ combine Combine a number of data files.
1132
+ debug Display information about the internals of coverage.py
1133
+ erase Erase previously collected coverage data.
1134
+ help Get help on using coverage.py.
1135
+ html Create an HTML report.
1136
+ json Create a JSON report of coverage results.
1137
+ lcov Create an LCOV report of coverage results.
1138
+ report Report coverage stats on modules.
1139
+ run Run a Python program and measure code execution.
1140
+ xml Create an XML report of coverage results.
1141
+
1142
+ Use "{program_name} help <command>" for detailed help on any command.
1143
+ """,
1144
+ "minimum_help": prep_help(
1145
+ """
1146
+ Code coverage for Python, version {__version__} {extension_modifier}.
1147
+ Use '{program_name} help' for help.
1148
+ """
1149
+ ),
1150
+ "version": "Coverage.py, version {__version__} {extension_modifier}",
1151
+ }
1152
+
1153
+
1154
+ def main(argv: list[str] | None = None) -> int | None:
1155
+ """The main entry point to coverage.py.
1156
+
1157
+ This is installed as the script entry point.
1158
+
1159
+ """
1160
+ if argv is None:
1161
+ argv = sys.argv[1:]
1162
+ try:
1163
+ status = CoverageScript().command_line(argv)
1164
+ except _ExceptionDuringRun as err:
1165
+ # An exception was caught while running the product code. The
1166
+ # sys.exc_info() return tuple is packed into an _ExceptionDuringRun
1167
+ # exception.
1168
+ traceback.print_exception(*err.args) # pylint: disable=no-value-for-parameter
1169
+ status = ERR
1170
+ except CoverageException as err:
1171
+ # A controlled error inside coverage.py: print the message to the user.
1172
+ msg = err.args[0]
1173
+ if err.slug:
1174
+ msg = f"{msg.rstrip('.')}; see {__url__}/messages.html#error-{err.slug}"
1175
+ print(msg)
1176
+ status = ERR
1177
+ except SystemExit as err:
1178
+ # The user called `sys.exit()`. Exit with their argument, if any.
1179
+ if err.args:
1180
+ status = err.args[0]
1181
+ else:
1182
+ status = None
1183
+ return status
1184
+
1185
+
1186
+ def main_deprecated(argv: list[str] | None = None) -> int | None:
1187
+ """For entry points we'll be getting rid of."""
1188
+ print(
1189
+ textwrap.dedent("""\
1190
+ **
1191
+ ** This entry point is deprecated and will be removed.
1192
+ ** Send me an email if you want to keep this command name working:
1193
+ ** ned@nedbatchelder.com
1194
+ **
1195
+ """)
1196
+ )
1197
+ return main(argv)
1198
+
1199
+
1200
+ # Profiling using ox_profile. Install it from GitHub:
1201
+ # pip install git+https://github.com/emin63/ox_profile.git
1202
+ #
1203
+ # $set_env.py: COVERAGE_PROFILE - Set to use ox_profile.
1204
+ _profile = os.getenv("COVERAGE_PROFILE")
1205
+ if _profile: # pragma: debugging
1206
+ from ox_profile.core.launchers import SimpleLauncher # pylint: disable=import-error
1207
+
1208
+ original_main = main
1209
+
1210
+ def main( # pylint: disable=function-redefined
1211
+ argv: list[str] | None = None,
1212
+ ) -> int | None:
1213
+ """A wrapper around main that profiles."""
1214
+ profiler = SimpleLauncher.launch()
1215
+ try:
1216
+ return original_main(argv)
1217
+ finally:
1218
+ data, _ = profiler.query(re_filter="coverage", max_records=100)
1219
+ print(profiler.show(query=data, limit=100, sep="", col=""))
1220
+ profiler.cancel()