-
Notifications
You must be signed in to change notification settings - Fork 0
/
package.py
3063 lines (2533 loc) · 104 KB
/
package.py
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
The all-in-one python package management tool.
There are lots of tools available that you can use to monitor and improve the
quality of your package. However, you have to configure them, remember how they work,
think about the order in which to execute them, parse their output to get badges and
finally clean up after them. It's easy to forgo this tedious work in the beginning when
all you can think about is the bright idea behind your new python package. Will you do
that later on? Probably not, because then chances are high that you get hundreds of
complaints from these tools and fixing them all will likely set you back for weeks.
Its way more fun to focus on new features anyway.
Meet package.py: It provides short, easy to remember commands for building, testing,
styling, security checking, documentation generation and more. No configuration
required. It keeps your package always clean and tidy by removing intermediate build
artifacts as well as empty folders. It compiles the output into a single, beautiful
report and meaningful badges so you can monitor the most important metrics right from
the start of development.
Just call
```py
python package.py --help
```
for additional information. By the way: The name is no coincidence: It's chosen such that
you can just hit tab for autocompletion after the first "p" of "package.py". Makes for
faster typing. ;)
"""
import argparse
import glob
import importlib
import inspect
import io
import json
import math
import multiprocessing
import os
import re
import runpy
import shutil
import sys
from contextlib import nullcontext, redirect_stdout, redirect_stderr
from datetime import datetime
from pathlib import Path
from typing import List, Optional, Tuple, Union
from urllib.parse import quote
class Settings:
"""
Class for storing all configuration options.
You can change the default settings directly in this class.
"""
# Remove features from the list that you do not need.
FEATURES = [
"GENERATE_DOCUMENTATION",
"GENERATE_REPORT",
"BUILD_WHEELS",
"CHECK_SECURITY",
"RUN_TESTS",
"CHECK_STYLE",
"CHECK_TYPES"
"UPDATE_PASSFAIL_BADGE",
"UPDATE_TESTCOVERAGE_BADGE",
"UPDATE_TEST_BADGE",
"UPDATE_DOCCOVERAGE_BADGE",
"UPDATE_SECURITY_BADGE",
"UPDATE_BUILD_BADGE",
]
# **********************************************
# *** This section specifies temporary files ***
# **********************************************
# Base directory of the repository.
BASE_DIR = Path(__file__).parents[0]
# Directory where the package source code can be found.
SRC_DIR = BASE_DIR / "src"
# Patterns to omit for coverage.
COVERAGE_OMIT_PATTERN = "*/test*"
# Root directory for documentation.
DOCUMENTATION_ROOT_DIR = BASE_DIR / "docfiles"
# The directory in which the generated html documentation is stored.
DOCUMENTATION_HTML_DIR = BASE_DIR / "docs"
# Directories in the html output that can be deleted, because they are irrelevant.
DOCUMENTATION_HTML_DIR_EXCLUDE = [
DOCUMENTATION_HTML_DIR / ".doctrees",
DOCUMENTATION_HTML_DIR / "_sources",
DOCUMENTATION_ROOT_DIR / "build",
DOCUMENTATION_ROOT_DIR / "doctrees",
]
# Temporary directory for storing generated documentation source files.
DOCUMENTATION_SOURCE_DIR = DOCUMENTATION_ROOT_DIR / "source"
# Directory in which documentation templates are stored.
DOCUMENTATION_TEMPLATE_DIR = DOCUMENTATION_ROOT_DIR / "templates"
# Directory in which build artifacts are placed.
DISTRIBUTABLE_DIR = BASE_DIR / "dist"
# The file that contains package configuration for setuptools.
CONFIGFILE = BASE_DIR / "pyproject.toml"
# Directory in which badges are stored.
BADGE_FOLDER = BASE_DIR / "data" / "badges"
# Folder into which json for analyzing dependencies are placed.
TMP_DIR = BASE_DIR / "tmp"
# Folder in which mypy stores its cache.
MYPY_CACHE = BASE_DIR / ".mypy_cache"
# Temporary directory for build files.
BUILD_DIR = BASE_DIR / "build"
# Directory for placing all reports.
REPORT_DIR = DOCUMENTATION_HTML_DIR / "report"
# Directory in which the report template can be found.
REPORT_TEMPLATE_DIR = BASE_DIR / "data" / "report_template"
# Path to the report template.
REPORT_TEMPLATE_FILE = REPORT_TEMPLATE_DIR / "report.jinja"
# Path to the main report file.
REPORT_HTML = REPORT_DIR / "report.html"
# Directory for placing additional files used by the report.
REPORT_FILES_DIR = REPORT_DIR / "files"
# Name of the report section about code style.
REPORT_SECTION_NAME_STYLE = "Style"
# Name of the report section about testing.
REPORT_SECTION_NAME_TEST = "Test"
# Name of the report section about testing.
REPORT_SECTION_NAME_DEPENDENCY_VERSIONS = "Versions"
# Name of the report section about security (bandit).
REPORT_SECTION_NAME_SECURITY = "Security"
# Name of the report section about documentation.
REPORT_SECTION_NAME_DOCUMENTATION = "Documentation"
# The report shows code snippets. These snippets typically have only a few lines
# that are of interest to the user. However, additional lines before and after the
# relevant ones are also shown to provide some context. The number of lines before
# and after is specified here.
REPORT_LINE_RANGE = 10
# The file in which test coverage information is stored (for the coverage package).
TEST_COVERAGE_FILE = BASE_DIR / ".coverage"
# The file in which test coverage information is stored (for parsing by package.py).
TEST_COVERAGE_JSON = TMP_DIR / "coverage.json"
# The file in which bandit's results are stored (for parsing by package.py).
SECURITY_BANDIT_JSON = TMP_DIR / "bandit.json"
# The file in which style violations are documented.
STYLE_REPORT_JSON = TMP_DIR / "style.json"
# THe file in which type errors are documented.
TYPE_REPORT_XML = TMP_DIR / "type.xml"
# File for storing warnings about undefined or undocumented Python code.
DOCUMENTATION_COVERAGE_FILE = TMP_DIR / "doccoverage.json"
# ******************************************************
# *** This section specifies colors for badges files ***
# ******************************************************
# Thresholds for the badge colors that indicate the test coverage. Each dictionary
# key corresponds to the minimum coverage necessary for using the color given as
# dictionary value. The badge will use the highest key value for which
# coverage >= key.
TEST_COVERAGE_THRESHOLDS = {
99: "brightgreen",
98: "green",
96: "yellowgreen",
94: "yellow",
90: "orange",
}
# Thresholds for the badge colors that indicate the documentation coverage. Each
# dictionary key corresponds to the minimum coverage necessary for using the color
# given as dictionary value. The badge will use the highest key value for which
# coverage >= key.
DOCUMENTATION_COVERAGE_THRESHOLDS = {
99: "brightgreen",
98: "green",
96: "yellowgreen",
94: "yellow",
90: "orange",
}
# Thresholds for the badge colors that indicate the number of security issues. Each
# dictionary key corresponds to the maximum issues necessary for using the color
# given as dictionary value. The badge will use the lowest key value for which
# number of issues <= key.
SECURITY_ISSUES_THRESHOLDS = {0: "brightgreen"}
def require(
requirements: List[Tuple[str, Optional[str], Optional[List[str]]]],
install: bool = False,
):
"""
Installs the given module, if it is not available.
Args:
requirements: List of tuples describing the required dependencies. Each tuple
is defined as (modulename, packagename). The packagename only has to be
given, if it differs from the modulename. Otherwise, you can write None
instead of packagename.
install: If True, missing modules will automatically be installed. In the same
case, the function will return False and not install anything if the
parameter is set to False.
Returns:
True, if the given module is installed. False, otherwise.
"""
notinstalled = []
for requirement in requirements:
modulename, packagename, options = requirement
packagename = modulename if packagename is None else packagename
options = [] if options is None else options
run = run_uv if has_uv() else pyexecute
try:
importlib.import_module(modulename)
except ModuleNotFoundError:
if install:
run(
["pip", "install"]
+ options
+ [packagename]
+ ["--disable-pip-version-check"]
)
# Make sure that the running script finds the new module.
importlib.invalidate_caches()
else:
notinstalled.append(requirement)
return notinstalled
def remove_if_exists(path: Union[Path, str]):
"""
Deletes a given file or folder, if it exists.
Args:
path: The path to the file or folder to delete.
"""
try:
if os.path.isfile(str(path)):
os.remove(str(path))
if os.path.isdir(str(path)):
shutil.rmtree(str(path))
except PermissionError as e:
path = Path(path).absolute()
if os.path.isdir(str(path)):
exit(f"Error while trying to delete folder \"{path}\":\n" + str(e))
exit(f"Error while trying to delete file \"{path}\":\n" + str(e))
def remove_if_empty(path: Union[Path, str]):
"""
Deletes a given folder, if it is empty.
Args:
path: The path to the folder that shall be deleted, if it is empty.
"""
if os.path.isdir(str(path)) and len(os.listdir(str(path))) == 0:
shutil.rmtree(str(path))
def file_has_content(path: Union[Path, str]):
if not os.path.isfile(str(path)):
return False # File does not exist.
size = 0
with open(path, "r") as f:
f.seek(0, os.SEEK_END)
size = f.tell()
return size > 0 # Has the file any content?
def mkdirs_if_not_exists(path: Union[str, Path]):
"""
Creates the given folder path, if it does not exist already.
Args:
path: The folder path that shall be created.
"""
if not os.path.isdir(str(path)):
os.makedirs(str(path))
def get_program_path(prog: str):
""" Return the path to the given program.
Args:
prog: The name of the program to find.
"""
spec = importlib.util.find_spec(prog)
try:
return Path(spec.loader.path) # type: ignore
except AttributeError:
return None
def run_uv(args: list):
"""
Runs a command using uv package manager.
Args:
args: The command to run.
"""
from subprocess import run
cmd = ["uv"] + args
run(cmd, shell=True, check=True)
def has_uv():
from subprocess import run, CalledProcessError, DEVNULL
cmd = ["uv"]
try:
# Run with no output to avoid cluttering the console.
run(cmd, shell=True, check=True, stdout=DEVNULL, stderr=DEVNULL)
return True
except (FileNotFoundError, CalledProcessError):
return False
def runner(cmd: list):
"""
Runs a module in a separate process.
Args:
cmd: The command to run. First entry must be the module to execute, e.g.
"pip" for pip for "sphinx.ext.apidoc" for the sphinx apidoc extension.
"""
# Create the list of arguments to provide to the executed module. For this, obtain
# the file path for the module and set it as first argument, then copy the remaining
# arguments as they are to the argument list.
path = get_program_path(cmd[0]) # type: ignore
apppath = path.parents[0] / "__main__.py" if path.name == "__init__.py" else path
arguments = list([str(apppath)])
arguments += cmd[1:]
# Provide arguments to the module and run the module.
sys.argv = arguments
# Run module and silence error messages as well as findings except for pip and uv.
cxt = nullcontext() if cmd[0] in ["pip", "uv"] else redirect_stdout(io.StringIO())
# Silence error messages for tools that output findings on stderr although they
# are part of normal operation.
cxt = redirect_stderr(io.StringIO()) if cmd[0] in ["mypy"] else cxt
with cxt:
try:
runpy.run_module(cmd[0], run_name="__main__")
except Exception as e:
print(f"Running command {' '.join(cmd)} failed:\n{str(e)}")
def pyexecute(cmd: list):
"""
Runs shell commands in a more secure way.
Shell commands are executed using the absolute python path with which the script
was started.
Args:
cmd: Command to execute as a list of arguments.
Returns:
The exit code of the process that ran the module.
"""
if not isinstance(cmd, list):
raise Exception(
"Expected type list for parameter cmd. "
+ f"Instead got {type(cmd).__name__}."
)
p = multiprocessing.Process(
target=runner,
args=(cmd,)
)
p.start()
p.join()
return p.exitcode
class Report:
"""
Generates an HTML report.
The report is structured in sections, each intended for one aspect of code analysis.
For example, one section may show dependency vulnerabilities, and another may show
undocumented code. The main methods are report() to populate the sections and
render() to output the HTML files. There are several subclasses which model different
ways of presenting information like List and Table. In addition, the File subclass
is used for showing code snippets. For example, on the main page the user may click
on an issue and gets to another page highlighting the troublesome piece of code.
"""
SUMMARY_NAME = "name"
SUMMARY_VALUE = "value"
SUMMARY_UNIT = "unit"
SUMMARY_PASSED = "passed"
class List:
"""
Models a list of elements in the final report, e.g. a list of security issues.
Each list element can be expanded to show details.
"""
SUMMARY = "summary"
DETAILS = "details"
def __init__(self, name: str = "") -> None:
"""
Initializes the list with a name (typically used as heading).
Args:
name: The name (typically heading) of the list.
"""
self.heading = name
self.type = "list"
self.entries = []
self.summary = tuple()
def add(self, summary, details) -> None:
"""
Adds a row to the list.
Args:
summary: Brief one-line summary.
details: In-depth description that is shown when the user expands the
row.
"""
self.entries.append({self.SUMMARY: summary, self.DETAILS: details})
def __iter__(self):
"""
Allows the class to be used as an iterable.
"""
self.index = 0
return self
def __next__(self):
"""
Allows the class to be used as an iterable.
"""
if self.index < len(self.entries):
self.index += 1
return self.entries[self.index - 1]
else:
raise StopIteration
@property
def count(self):
"""
Returns the number of entries in the list.
Returns:
Number of entries in the list, i.e. the number of rows.
"""
return len(self.entries)
class Table:
"""
Models a table in the final report, e.g. test coverage per file.
"""
def __init__(self, name: str = "", columns: list = list()) -> None:
"""
Initializes the table with a name and column headings.
Args:
name: The name (typically heading) of the table.
columns: The heading for each column.
"""
self.heading = name
self.columns = columns
self.type = "table"
self.entries = []
self.summary = tuple()
def add(self, *columndata: str) -> None:
"""
Adds a row to the list.
The number of arguments (excluding self) has to match the number of defined
columns in the table.
Args:
columndata: Positional arguments, one for each defined column.
"""
if len(columndata) != len(self.columns):
raise ValueError(
f"Given number of columns ({len(columndata)}) "
+ f"does not match table ({len(self.columns)})."
)
self.entries.append({self.columns[i]: d for i, d in enumerate(columndata)})
def __iter__(self):
"""
Allows the class to be used as an iterable.
"""
self.index = 0
return self
def __next__(self):
"""
Allows the class to be used as an iterable.
"""
if self.index < len(self.entries):
self.index += 1
return self.entries[self.index - 1]
else:
raise StopIteration
@property
def count(self):
"""
Returns the number of entries in the table.
Returns:
Number of rows in the table.
"""
return len(self.entries)
@property
def headings(self):
"""
Returns the headings for each column defined for the table.
"""
return self.columns
class File:
"""
Models a file in the final report.
This is typically used to provide actual code snippets with the issues being
highlighted. The colors used for highlighting are defined in the report's HTML
template. In this class, highlighting will just be categorized in terms of good,
bad, neutral and no highlighting. The report template will then decide which
colors to use to highlight good, bad and neutral code sections. A legend is
also provided in the report to show what each color means. A label can be
assigned to each category using the set_mark_name method.
"""
CONTENT = "content"
COLOR = "color"
COLOR_GOOD = "good"
COLOR_BAD = "bad"
COLOR_NEUTRAL = "neutral"
COLOR_NONE = "none"
def __init__(self, filepath: str) -> None:
"""
Initializes the object with the path to the file that shall be shown.
Args:
filepath: Path to the file that shall be shown.
"""
self.type = "file"
self.summary = tuple()
self.filepath = filepath
self.outputpath = ""
self.colorname = {}
self.lines = []
self.__range = tuple()
with open(filepath, "r") as f:
self.lines = [
{self.CONTENT: line, self.COLOR: self.COLOR_NONE}
for line in f
if line
]
if not self.lines:
self.lines = [{self.CONTENT: "", self.COLOR: self.COLOR_NONE}]
self.__range = (0, len(self.lines))
@property
def range(self):
"""Returns the range of lines to display."""
return self.__range
@range.setter
def range(self, range: Tuple):
"""Sets the range of lines to display."""
self.__range = (max(0, range[0]), min(len(self.lines), range[1]))
@property
def heading(self):
"""
The heading used for the report. Derived from the file path.
"""
absolute = Path(self.filepath).absolute()
return str(absolute.relative_to(Path().cwd()))
def set_mark_name(self, marking: str, label: str):
"""
Sets a label for a marking category.
The colors used for highlighting are defined in the report's HTML
template. In this class, highlighting will just be categorized in terms of
good, bad, neutral and no highlighting. The report template will then decide
which colors to use to highlight good, bad and neutral code sections. A
legend is also provided in the report to show what each color means. A label
can be assigned to each category using this method. For example, calling
```
myreport.set_mark_name(myreport.COLOR_BAD, "Finding")
```
will label the color used for "bad" code sections with the word "Finding".
Args:
marking: The marking to assign a name to. Must be Report.COLOR_GOOD,
Report.COLOR_BAD or Report.COLOR_NEUTRAL.
label: The label associated with the color category. It is shown in the
legend that the report provides.
"""
if marking not in [
self.COLOR_GOOD,
self.COLOR_BAD,
self.COLOR_NEUTRAL,
self.COLOR_NONE,
]:
raise ValueError("Invalid marking type.")
self.colorname[marking] = label
def mark(self, lines: Union[list, int], marking):
"""
Highlights the given lines with the given color category.
The colors used for highlighting are defined in the report's HTML template.
In this class, highlighting will just be categorized in terms of good, bad,
neutral and no highlighting. The report template will then decide which
colors to use to highlight good, bad and neutral code sections. For example,
calling
```
myreport.mark([5, 6, 7], myreport.COLOR_BAD)
```
will mark lines 5 to 7 as "bad code" and the report will highlight these
lines in a suitable color (e.g. red).
Args:
lines: The lines to highlight.
marking: The color category to mark the lines with.
"""
inlines = [lines] if isinstance(lines, int) else lines
if not inlines:
return
if marking not in [
self.COLOR_GOOD,
self.COLOR_BAD,
self.COLOR_NEUTRAL,
self.COLOR_NONE,
]:
raise ValueError("Invalid marking type.")
for linenumber in inlines:
if linenumber > len(self.lines) or linenumber < 1:
raise ValueError(
"Invalid line number for "
+ self.filepath
+ ": "
+ str(linenumber)
+ ". Line number must be within 1 to "
+ str(len(self.lines) + 1)
+ "."
)
# First line starts with 1 and not 0.
self.lines[linenumber - 1][self.COLOR] = marking
def identifier(self):
"""
Provides a unique identifier for the file.
Oftentimes, multiple issues reference the same code section in the same
original file and highlight the section in the same way. This identifier is
used to detect that and avoid duplicate files in the final report that
waste storage.
Returns:
Hash representing the file's configuration including original filepath,
highlighted lines and used color categories.
"""
filepath = str(Path(self.filepath).absolute())
range = self.__range
range = f"{range[0]:08d}{range[1]:08d}" if range else "None"
color = [f"{i:08d}" + line[self.COLOR] for i, line in enumerate(self.lines)]
color = "".join(color)
return hash(filepath + range + color)
@classmethod
def get_requirements(cls, settings: Settings):
if "GENERATE_REPORT" in settings.FEATURES:
return [
("jinja2", None, None),
]
return []
def __init__(self, settings: Settings, appname: str, version: str) -> None:
"""
Initializes the report.
Args:
settings: The settings instance to use.
appname: The name of the application / python package.
version: The version of the application / python package.
"""
self.active = "GENERATE_REPORT" in settings.FEATURES
self._sections = {}
self._files = {}
self._appname = appname
self._version = version
self._settings = settings
if self.active:
import jinja2
self._timestamp = datetime.now().astimezone()
self._environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(str(self._settings.REPORT_TEMPLATE_DIR)),
autoescape=True,
)
self._maintemplate = self._environment.get_template("main.jinja")
self._filetemplate = self._environment.get_template("file.jinja")
def render(self):
"""
Exports the report as HTML files.
The HTML files will be stored in the directory given by REPORT_FILES_DIR.
"""
if not self.active:
print(f"Skipping report generation.")
return
outputdir = Path(self._settings.REPORT_HTML).parent
# Create output directories.
mkdirs_if_not_exists(outputdir)
mkdirs_if_not_exists(self._settings.REPORT_FILES_DIR)
# Copy style sheets to output directory.
for f in glob.glob(str(self._settings.REPORT_TEMPLATE_DIR / "*.css")):
shutil.copy(f, self._settings.REPORT_FILES_DIR)
styledir = self._settings.REPORT_FILES_DIR.absolute()
filelist = [str(self._settings.REPORT_HTML.absolute())]
# Write main report file.
with open(self._settings.REPORT_HTML, "wb") as f:
output = self._maintemplate.render(
appname=self._appname,
version=self._version,
timestamp=self._timestamp,
report=self._sections,
summary={heading: self.summary(heading) for heading in self._sections},
style_dir=os.path.relpath(styledir, outputdir.absolute()),
)
f.write(output.encode("utf-8"))
# Write files containing code snippets.
for file in self._files.values():
filename = (outputdir / Path(file.outputpath)).absolute()
filedir = filename.parent
filelist.append(str(filename.absolute()))
with open(filename, "wb") as f:
output = self._filetemplate.render(
appname=self._appname,
version=self._version,
timestamp=self._timestamp,
file=file,
style_dir=os.path.relpath(styledir, filedir.absolute()),
)
f.write(output.encode("utf-8"))
f.close()
# Remove report files that are not needed anymore.
# Although one could just remove the entire report folder, it is easier to
# delete superfluous files only, because it allows to regenerate the report with
# the report opened in a browser. The user then just needs to refresh the page.
# Deleting the folder is not allowed when the report has been opened in a
# browser, because the file is then denoted as "in use by another process".
for existing in glob.glob(str(self._settings.REPORT_FILES_DIR / "*.html")):
if str(Path(existing).absolute()) not in filelist:
remove_if_exists(existing)
def add(self, section: str, data: Union[File, Table, List]):
"""
Adds a section with the given name to the report.
A section is described by one of the subclasses. For example, Report.List or
Report.Table. Multiple instances may be added to the same section.
Args:
section: The name of the section to place the data in.
data: The data representing the section, e.g. an instance of Report.List.
"""
if isinstance(data, self.File):
index = len(self._files)
ident = data.identifier()
# Avoid multiple files with the same content.
if ident in self._files:
data.outputpath = self._files[ident].outputpath
return
reportdir = self._settings.REPORT_HTML.parent
filesdir = self._settings.REPORT_FILES_DIR
reldir = filesdir.relative_to(reportdir)
data.outputpath = str(reldir / (str(index) + ".html"))
self._files[ident] = data
return
if section not in self._sections:
self._sections[section] = [data]
else:
self._sections[section].append(data)
def summary(self, section: str) -> dict:
"""
Provides a summary metric / total value for the section with the given name.
An example for a summary may be the total test coverage in percent. The summary
is typically shown next to the section headline for quick reference.
Args:
section: Name of the section to return the summary for.
Returns:
A dictionary with three keys (Report.SUMMARY_NAME, Report.SUMMARY_VALUE and
report.SUMMARY_UNIT) containing the name of the metric used to summarize
the section, the value of that metric and the unit of that metric,
respectively.
"""
if (
len(self._sections[section]) == 1
and self._sections[section][0].summary
and isinstance(self._sections[section][0].summary, tuple)
):
return {
self.SUMMARY_NAME: self._sections[section][0].summary[0],
self.SUMMARY_VALUE: self._sections[section][0].summary[1],
self.SUMMARY_UNIT: self._sections[section][0].summary[2],
}
return {
self.SUMMARY_NAME: "Issues",
self.SUMMARY_VALUE: sum([entry.count for entry in self._sections[section]]),
self.SUMMARY_UNIT: "",
}
def get_total(self, section: str):
"""
Returns the value of the summary metric (see also Report.summary method).
Args:
section: The name of the section to get the summary metric for.
Returns:
Value of the summary metric.
"""
return self.summary(section)[self.SUMMARY_VALUE]
def remove(self):
"""
Removes the report.
"""
self.clean()
remove_if_exists(self._settings.REPORT_HTML.parent)
remove_if_exists(self._settings.REPORT_FILES_DIR)
def clean(self):
"""
Removes temporary files used for the report.
"""
remove_if_exists(self._settings.TMP_DIR)
class Meta:
"""
Class for reading package meta information from pyproject.toml.
This is useful for third-party tools like sphinx to perform
automatic configuration.
"""
def __init__(self, configfile: Union[Path, str]):
"""
Initializes the build with the package name from config file.
Args:
configfile: The name of the config file to pull the package
name from.
"""
self.configfile = str(configfile)
def get(self, keyword: str):
"""
Returns the value for the given key.
Args:
keyword: The name of the variable to be retrieved.
Returns:
The value in the config file stored under the given key.
"""
with open(self.configfile, "r", encoding="utf8") as f:
regex = r"[ ]*=[ ]*\"([^\n]+)?((\n[ \t]+([^\n]+))*)\""
buf = f.read()
match = re.search(keyword + regex, buf)
if match is None:
raise LookupError(f'Could not determine "{keyword}".')
matchstr = (match.group(1) or "") + (match.group(2) or "")
lines = matchstr.split("\n")
out = [entry.strip() for entry in lines if entry.strip()]
return out if len(out) > 1 else out[0]
def getAuthors(self):
"""
Returns the names of all authors
Returns:
The names of all authors.
"""
with open(self.configfile, "r", encoding="utf8") as f:
buf = f.read()
match = re.search(r"authors[ ]*=[ ]*\[.*?\]", buf, flags=re.MULTILINE | re.DOTALL)
if match is None:
raise LookupError(f'Could not determine authors.')
matchstr = match.group(0)
names = list(set(re.findall(r"name[ ]*=[ ]*\"([^\"]+)", matchstr)))
return names
def getCopyright(self):
"""
Generate a copyright string for documentation.
Returns:
String with copyright notice.
"""
from datetime import timezone
date = datetime.now(timezone.utc)
return str(date.year) + ", " + ", ".join(self.getAuthors())
class AbsBadge:
"""
Class for generating badges that can be displayed on PyPi
As of 2022-03-20, PyPi does not allow relative images paths. Therefore, the images
need to be hosted somewhere else and included in the readme as an absolute
http://... link. The badges on PyPi should only show the state of the most recent
release available on PyPi. Therefore, one cannot use a link to the current version
on github, because the state might be different. Likewise, at the state of building
the commit hash is not known. Therefore, the images need to be available somewhere
else. This is done by using the simple https://shields.io/ api.
"""
def __init__(self, settings: Settings) -> None:
"""
Initialize the class with settings.
Args:
settings: The settings instance to use.
"""
self._settings = settings
meta = Meta(settings.CONFIGFILE)
self._readmefilename = meta.get("readme")
self._rel_abs_map = dict()
with open(self._readmefilename, "r") as file: