-
Notifications
You must be signed in to change notification settings - Fork 25
/
tasks.py
790 lines (693 loc) · 20.5 KB
/
tasks.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
# Invoke is broken on Python 3.11
# https://github.com/pyinvoke/invoke/issues/833#issuecomment-1293148106
import inspect
import os
import re
import sys
import tempfile
from enum import Enum
from typing import Optional
if not hasattr(inspect, "getargspec"):
inspect.getargspec = inspect.getfullargspec
import invoke
from invoke import task
# Specifying encoding because Windows crashes otherwise when running Invoke
# tasks below:
# UnicodeEncodeError: 'charmap' codec can't encode character '\ufffd'
# in position 16: character maps to <undefined>
# People say, it might also be possible to export PYTHONIOENCODING=utf8 but this
# seems to work.
# FIXME: If you are a Windows user and expert, please advise on how to do this
# properly.
sys.stdout = open(1, "w", encoding="utf-8", closefd=False, buffering=1)
# To prevent all tasks from building to the same virtual environment.
# All values correspond to the configuration in the tox.ini config file.
class ToxEnvironment(str, Enum):
DEVELOPMENT = "development"
CHECK = "check"
DOCUMENTATION = "documentation"
RELEASE = "release"
RELEASE_LOCAL = "release-local"
PYINSTALLER = "pyinstaller"
def run_invoke(
context,
cmd,
environment: Optional[dict] = None,
warn: bool = False,
) -> invoke.runners.Result:
def one_line_command(string):
return re.sub("\\s+", " ", string).strip()
return context.run(
one_line_command(cmd),
env=environment,
hide=False,
warn=warn,
pty=False,
echo=True,
)
def run_invoke_with_tox(
context,
environment_type: ToxEnvironment,
command: str,
) -> invoke.runners.Result:
assert isinstance(environment_type, ToxEnvironment)
assert isinstance(command, str)
tox_py_version = f"py{sys.version_info.major}{sys.version_info.minor}"
return run_invoke(
context,
f"""
tox
-e {tox_py_version}-{environment_type.value} --
{command}
""",
)
@task
def clean(context):
# https://unix.stackexchange.com/a/689930/77389
clean_command = """
rm -rfv output/ docs/sphinx/build/
"""
run_invoke(context, clean_command)
@task
def clean_itest_artifacts(context):
# https://unix.stackexchange.com/a/689930/77389
find_command = """
git clean -dfX tests/integration/
"""
# The command sometimes exits with 1 even if the files are deleted.
# warn=True ensures that the execution continues.
run_invoke(context, find_command, warn=True)
@task(aliases=["s"])
def server(context, input_path=".", config=None):
assert os.path.isdir(input_path), input_path
if config is not None:
assert os.path.isfile(config), config
config_argument = f"--config {config}" if config is not None else ""
run_invoke_with_tox(
context,
ToxEnvironment.DEVELOPMENT,
f"""
python -m strictdoc.cli.main
server {input_path} {config_argument} --reload
""",
)
@task(aliases=["d"])
def docs(context):
run_invoke_with_tox(
context,
ToxEnvironment.DOCUMENTATION,
"""
python3 strictdoc/cli/main.py
export .
--formats=html
--output-dir output/strictdoc_website
--project-title "StrictDoc"
""",
)
assert os.path.isdir(
"strictdoc-project.github.io/"
), "Expecting the documentation to be cloned."
assert os.path.isdir(
"strictdoc-project.github.io/.git/"
), "Expecting the documentation to be a valid Git repository."
run_invoke_with_tox(
context,
ToxEnvironment.DOCUMENTATION,
"""
cp -rv output/strictdoc_website/html/* strictdoc-project.github.io/
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.DOCUMENTATION,
"""
python3 strictdoc/cli/main.py
export ./
--formats=rst
--output-dir output/sphinx
--project-title "StrictDoc"
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.DOCUMENTATION,
"""
cp -r output/sphinx/rst/docs/* docs/sphinx/source/ &&
cp -r output/sphinx/rst/docs_extra/* docs/sphinx/source/ &&
mkdir -p docs/sphinx/source/_assets/ &&
cp -v docs/_assets/* docs/sphinx/source/_assets/
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.DOCUMENTATION,
"""
make --directory docs/sphinx html latexpdf SPHINXOPTS="-W --keep-going"
""",
)
run_invoke(
context,
(
"""
open docs/sphinx/build/latex/strictdoc.pdf
"""
),
)
@task(aliases=["tu"])
def test_unit(context, focus=None):
focus_argument = f"-k {focus}" if focus is not None else ""
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
f"""
pytest tests/unit/ {focus_argument} -o cache_dir=build/pytest_unit
""",
)
@task
def test_unit_server(context, focus=None):
focus_argument = f"-k {focus}" if focus is not None else ""
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
f"""
pytest tests/unit_server/ {focus_argument} -o cache_dir=build/pytest_unit_server
""",
)
@task(aliases=["te"])
def test_end2end(
context,
focus=None,
exit_first=False,
parallelize=False,
long_timeouts=False,
headless=False,
shard=None,
):
long_timeouts_argument = (
"--strictdoc-long-timeouts" if long_timeouts else ""
)
parallelize_argument = ""
if parallelize:
print( # noqa: T201
"warning: "
"Running parallelized end-2-end tests is supported "
"but is not stable."
)
parallelize_argument = "--numprocesses=2 --strictdoc-parallelize"
assert shard is None or re.match(
r"[1-9][0-9]*/[1-9][0-9]*", shard
), f"--shard argument has an incorrect format: {shard}."
shard_argument = f"--strictdoc-shard={shard}" if shard else ""
focus_argument = f"-k {focus}" if focus is not None else ""
exit_first_argument = "--exitfirst" if exit_first else ""
headless_argument = "--headless2" if headless else ""
test_command = f"""
pytest
--failed-first
--capture=no
--reuse-session
{parallelize_argument}
{shard_argument}
{focus_argument}
{exit_first_argument}
{long_timeouts_argument}
{headless_argument}
-o cache_dir=build/pytest_end2end
tests/end2end
"""
# On Windows, GitHub Actions fails with:
# response = {'status': 500, 'value':
# '{"value":{"error":"unknown error",
# "message":"unknown error: cannot find Chrome binary", # noqa: ERA001
# This very likely has to do with PATH isolation that Tox does.
# FIXME: If you are a Windows expert, please fix this to run on Tox.
if os.name == "nt":
run_invoke(context, test_command)
return
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
test_command,
)
@task
def test_unit_coverage(context):
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
coverage run
--rcfile=.coveragerc
--branch
--omit=.venv*/*
-m pytest
-o cache_dir=build/pytest_unit_with_coverage
tests/unit/
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
coverage report --sort=cover
""",
)
@task(test_unit_coverage)
def test_coverage_report(context):
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
coverage html
""",
)
@task(aliases=["ti"])
def test_integration(
context,
focus=None,
debug=False,
no_parallelization=False,
fail_first=False,
strictdoc=None,
html2pdf=False,
environment=ToxEnvironment.CHECK,
):
clean_itest_artifacts(context)
cwd = os.getcwd()
if strictdoc is None:
strictdoc_exec = f'python3 \\"{cwd}/strictdoc/cli/main.py\\"'
else:
strictdoc_exec = strictdoc
debug_opts = "-vv --show-all" if debug else ""
focus_or_none = f"--filter {focus}" if focus else ""
fail_first_argument = "--max-failures 1" if fail_first else ""
# HTML2PDF tests are running Chrome Driver which does not seem to be
# parallelizable, or at least not in the way StrictDoc uses it.
# If HTML2PDF option is provided, do not parallelize and only run the
# HTML2PDF-specific tests.
chromedriver_param = ""
if not html2pdf:
parallelize_opts = "" if not no_parallelization else "--threads 1"
html2pdf_param = ""
test_folder = f"{cwd}/tests/integration"
else:
parallelize_opts = "--threads 1"
html2pdf_param = "--param TEST_HTML2PDF=1"
chromedriver_path = os.environ.get("CHROMEWEBDRIVER")
if chromedriver_path is not None:
# NOTE: isfile() check does not work on GitHub Actions / Linux,
# the exists() check works.
assert os.path.exists(chromedriver_path), chromedriver_path
chromedriver_param = f"--param CHROMEDRIVER={os.path.join(chromedriver_path, 'chromedriver')}"
test_folder = f"{cwd}/tests/integration/features/html2pdf"
strictdoc_cache_dir = os.path.join(tempfile.gettempdir(), "strictdoc_cache")
itest_command = f"""
lit
--param STRICTDOC_EXEC="{strictdoc_exec}"
--param STRICTDOC_CACHE_DIR="{strictdoc_cache_dir}"
{html2pdf_param}
{chromedriver_param}
-v
{debug_opts}
{focus_or_none}
{fail_first_argument}
{parallelize_opts}
{test_folder}
"""
# It looks like LIT does not open the RUN: subprocesses in the same
# environment from which it itself is run from. This issue has been known by
# us for a couple of years by now. Not using Tox on Windows for the time
# being.
if os.name == "nt":
run_invoke(context, itest_command)
return
run_invoke_with_tox(
context,
environment,
itest_command,
)
@task
def lint_black(context):
result: invoke.runners.Result = run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
black
*.py
developer/
strictdoc/
tests/unit/
tests/integration/*.py
tests/end2end/
--color --line-length 80 2>&1
""",
)
# black always exits with 0, so we handle the output.
if "reformatted" in result.stdout:
print("invoke: black found issues") # noqa: T201
result.exited = 1
raise invoke.exceptions.UnexpectedExit(result)
@task
def lint_ruff_format(context):
result: invoke.runners.Result = run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
ruff
format
*.py
developer/
strictdoc/
tests/unit/
tests/integration/*.py
tests/end2end/
""",
)
# Ruff always exits with 0, so we handle the output.
if "reformatted" in result.stdout:
print("invoke: ruff format found issues") # noqa: T201
result.exited = 1
raise invoke.exceptions.UnexpectedExit(result)
@task(aliases=["lr"])
def lint_ruff(context):
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
ruff check . --fix --cache-dir build/ruff
""",
)
# @sdoc[SDOC-SRS-43]
@task(aliases=["lm"])
def lint_mypy(context):
# These checks do not seem to be useful:
# - import
# - misc
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
mypy strictdoc/
--show-error-codes
--disable-error-code=import
--disable-error-code=misc
--cache-dir=build/mypy
--strict
--python-version=3.8
""",
)
# # @sdoc[/SDOC-SRS-43]
@task(aliases=["l"])
def lint(context):
lint_ruff_format(context)
lint_ruff(context)
lint_mypy(context)
@task(aliases=["t"])
def test(context):
test_unit_coverage(context)
test_unit_server(context)
test_integration(context)
test_integration(context, html2pdf=True)
@task(aliases=["c"])
def check(context):
lint(context)
test(context)
# https://github.com/github-changelog-generator/github-changelog-generator
# gem install github_changelog_generator
@task
def changelog(context, github_token):
# The alpha release tags are excluded from the changelog.
command = f"""
github_changelog_generator
--token {github_token}
--user strictdoc-project
--exclude-tags-regex ".*a\\d+"
--project strictdoc
"""
run_invoke(context, command)
@task
def dump_grammar(context, output_file):
command = f"""
python3 strictdoc/cli/main.py dump-grammar {output_file}
"""
run_invoke(context, command)
@task
def check_dead_links(context):
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
python3 tools/link_health.py docs/strictdoc_01_user_guide.sdoc
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
python3 tools/link_health.py docs/strictdoc_02_faq.sdoc
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
python3 tools/link_health.py docs/strictdoc_03_development_plan.sdoc
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
python3 tools/link_health.py docs/strictdoc_10_contributing.sdoc
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
python3 tools/link_health.py docs/strictdoc_20_L1_Open_Requirements_Tool.sdoc
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
python3 tools/link_health.py docs/strictdoc_21_L2_StrictDoc_Requirements.sdoc
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.CHECK,
"""
python3 tools/link_health.py docs/strictdoc_25_design.sdoc
""",
)
@task
def release_local(context):
run_invoke(
context,
"""
rm -rfv dist/ build/
""",
)
run_invoke(
context,
"""
pip uninstall strictdoc -y
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.RELEASE_LOCAL,
"""
python -m build
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.RELEASE_LOCAL,
"""
twine check dist/*
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.RELEASE_LOCAL,
"""
pip install dist/*.tar.gz
""",
)
test_integration(
context, strictdoc="strictdoc", environment=ToxEnvironment.RELEASE_LOCAL
)
@task
def release(context, test_pypi=False, username=None, password=None):
"""
A release can be made to PyPI or test package index (TestPyPI):
https://pypi.org/project/strictdoc/
https://test.pypi.org/project/strictdoc/
"""
# When a username is provided, we also need password, and then we don't use
# tokens set up on a local machine.
assert username is None or password is not None
repository_argument_or_none = (
""
if username
else (
"--repository strictdoc_test"
if test_pypi
else "--repository strictdoc_release"
)
)
user_password = f"-u{username} -p{password}" if username is not None else ""
run_invoke(
context,
"""
rm -rfv dist/
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.RELEASE,
"""
python3 -m build
""",
)
run_invoke_with_tox(
context,
ToxEnvironment.RELEASE,
"""
twine check dist/*
""",
)
# The token is in a core developer's .pypirc file.
# https://test.pypi.org/manage/account/token/
# https://packaging.python.org/en/latest/specifications/pypirc/#pypirc
run_invoke_with_tox(
context,
ToxEnvironment.RELEASE,
f"""
twine upload dist/strictdoc-*.tar.gz
{repository_argument_or_none}
{user_password}
""",
)
@task
def release_pyinstaller(context):
path_to_pyi_dist = "/tmp/strictdoc"
# The --hidden-import strictdoc.server.app flag is needed because without
# it, the following is produced:
# ERROR: Error loading ASGI app. Could not import
# module "strictdoc.server.app".
# Solution found here: https://stackoverflow.com/a/71340437/598057
# This behavior is not surprising because that's how the uvicorn loads the
# application separately from the parent process.
command = f"""
pyinstaller
--clean
--name strictdoc
--noconfirm
--additional-hooks-dir developer/pyinstaller_hooks
--distpath {path_to_pyi_dist}
--hidden-import strictdoc.server.app
--add-data strictdoc/export/html2pdf/html2pdf.py:.
--add-data strictdoc/export/html/templates:templates/html
--add-data strictdoc/export/rst/templates:templates/rst
--add-data strictdoc/export/html/_static:_static
--add-data strictdoc/export/html/_static_extra:_static_extra
strictdoc/cli/main.py
"""
run_invoke_with_tox(
context,
ToxEnvironment.PYINSTALLER,
"""
pyinstaller --version
""",
)
run_invoke_with_tox(context, ToxEnvironment.PYINSTALLER, command)
@task
def watch(context, sdocs_path="."):
strictdoc_command = f"""
python strictdoc/cli/main.py
export
{sdocs_path}
--output-dir output/
--experimental-enable-file-traceability
"""
run_invoke_with_tox(
context,
ToxEnvironment.DEVELOPMENT,
f"""
{strictdoc_command}
""",
)
paths_to_watch = "."
run_invoke_with_tox(
context,
ToxEnvironment.DEVELOPMENT,
f"""
watchmedo shell-command
--patterns="*.py;*.sdoc;*.jinja;*.html;*.css;*.js"
--recursive
--ignore-pattern='output/;tests/integration'
--command='{strictdoc_command}'
--drop
{paths_to_watch}
""",
)
@task
def run(context, command):
run_invoke_with_tox(
context,
ToxEnvironment.DEVELOPMENT,
f"""
{command}
""",
)
@task
def nuitka(context):
run_invoke(
context,
f"""
PYTHONPATH="{os.getcwd()}"
python -m nuitka
--static-libpython=no
--standalone
--include-module=textx
--include-module=strictdoc.server.app
--include-module=docutils
--include-module=docutils.readers.standalone
--include-module=docutils.parsers.rst
--include-data-dir=strictdoc/export/html/templates=templates/html
--include-data-dir=strictdoc/export/rst/templates=templates/rst
--include-data-dir=strictdoc/export/html/_static=_static
--include-data-dir=strictdoc/export/html/_static_extra/mathjax=_static_extra/mathjax
--include-package-data=docutils
strictdoc/cli/main.py
""",
)
# https://github.com/jrfonseca/gprof2dot
# pip install gprof2dot
@task()
def performance(context):
command = """
python -m cProfile -o output/profile.prof
strictdoc/cli/main.py export . --no-parallelization &&
gprof2dot -f pstats output/profile.prof | dot -Tpng -o output/output.png
"""
run_invoke(context, command)
@task(performance)
def performance_snakeviz(context):
command = """
snakeviz output/profile.prof
"""
run_invoke(context, command)
@task()
def autouid(context):
run_invoke(
context,
"""
python strictdoc/cli/main.py
manage auto-uid
drafts/requirements
""",
)