-
Notifications
You must be signed in to change notification settings - Fork 24
/
update.py
executable file
·1326 lines (1018 loc) · 40.3 KB
/
update.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
#!/usr/bin/env python3.10
import copy
import datetime
import os
import re
import shutil
import subprocess
import sys
import zipfile
from io import StringIO
from optparse import OptionParser
from pathlib import Path
from urllib.request import urlretrieve
import requests
from lxml import html
# Which branches were already done.
updated_branches = set()
def _updateCheckout(branch, update):
# We cannot use Nuitka directory change yet here.
old_cwd = os.getcwd()
os.chdir(os.path.dirname(__file__))
try:
if os.path.exists(f"Nuitka-{branch}") and not update:
return
if branch in updated_branches:
return
if os.path.exists(f"Nuitka-{branch}"):
shutil.rmtree(f"Nuitka-{branch}")
print(f"Updating {branch} checkout...")
sys.stdout.flush()
urlretrieve(
f"https://github.com/Nuitka/Nuitka/archive/{branch}.zip", "nuitka.zip.tmp"
)
with zipfile.ZipFile("nuitka.zip.tmp") as archive:
archive.extractall(".")
os.unlink("nuitka.zip.tmp")
finally:
os.chdir(old_cwd)
updated_branches.add(branch)
def updateNuitkaMain(update):
_updateCheckout("main", update=update)
def updateNuitkaDevelop(update):
_updateCheckout("develop", update=update)
def importNuitka():
# TODO: Add an option to use other branches.
updateNuitkaDevelop(update=False)
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), "Nuitka-develop"))
)
import nuitka.containers.OrderedSets
del sys.path[0]
return nuitka
importNuitka()
# isort:start
from nuitka.tools.quality.auto_format.AutoFormat import (
withFileOpenedAndAutoFormatted,
)
from nuitka.tools.release.Documentation import checkRstLint
from nuitka.Tracing import my_print
from nuitka.utils.FileOperations import (
deleteFile,
getFileContents,
getFileList,
putTextFileContents,
)
from nuitka.utils.Hashing import getHashFromValues
from nuitka.utils.Jinja2 import getTemplate
from nuitka.utils.ReExecute import callExecProcess
from nuitka.utils.Rest import makeTable
in_devcontainer = os.getenv("REMOTE_CONTAINERS_DISPLAY_SOCK") is not None
def updateDownloadPage():
page_source = requests.get("https://nuitka.net/releases/").text
tree = html.parse(StringIO(page_source))
link_names = tree.xpath("//@href")
max_pre_release = ""
max_stable_release = ""
def numberize(value):
if value == "":
return []
value = (
value.replace("~pre", ".")
.replace("pre", ".")
.replace("~rc", ".")
.replace("rc", ".")
.replace("~nd", "")
)
parts = []
current = ""
for v in value:
if v in ".-+":
parts.append(current)
current = ""
elif v.isdigit() and (current.isdigit() or not current):
current += v
elif v.isdigit():
parts.append(current)
current = v
elif current == "":
current = v
elif current.isdigit():
parts.append(current)
current = v
elif current.isalpha() and v.isalpha():
current += v
else:
assert False, (value, v)
if current != "":
parts.append(current)
parts = [int(part) if part.isdigit() else part for part in parts]
if "ds" in parts:
parts.remove("ds")
assert parts, value
return parts
for filename in link_names:
# Navigation links
if filename.startswith("?C") or filename == "/":
continue
if filename.startswith("0.3"):
continue
if filename.startswith("0.4"):
continue
if "CPython" in filename or "shedskin" in filename or "PySide" in filename:
continue
assert filename.lower().startswith("nuitka"), filename
if filename.endswith(".msi"):
continue
if not filename.endswith(".zip.sig"):
continue
# print "FILE", filename
filename = filename[len("nuitka_") : -len(".zip.sig")]
# print "VER", filename
if "pre" in filename or "rc" in filename:
max_pre_release = max(max_pre_release, filename, key=numberize)
else:
max_stable_release = max(max_stable_release, filename, key=numberize)
def makePlain(value):
value = (
value.replace("+ds", "")
.replace("~pre", "pre")
.replace("~rc", "rc")
.split("-")[0]
)
return value
my_print(
"Max pre-release is %s %s " % (max_pre_release, makePlain(max_pre_release))
)
my_print(
"Max stable release is %s %s "
% (max_stable_release, makePlain(max_stable_release))
)
output = ""
def extractDebVersion(path):
match = re.search(r"nuitka_(.*)_all\.deb", path)
return match.group(1)
def makeRepositoryUrl(path):
return f"https://nuitka.net/{path}"
deb_info = {}
for line in output.split("\n"):
if not line:
continue
parts = line.split(os.path.sep)
assert parts[0] == "deb"
category = parts[1]
code_name = parts[2]
filename = parts[-1]
deb_info[category, code_name] = (
extractDebVersion(filename),
makeRepositoryUrl(line),
)
def checkOBS(repo_name):
url = (
"https://download.opensuse.org/repositories/home:/kayhayen/%s/noarch/"
% repo_name
)
command = "curl -s %s" % url
output = subprocess.check_output(command.split())
output = output.decode("utf8").split("\n")
candidates = []
for line in output:
if ".rpm" not in line:
continue
if "unstable" in line:
continue
if "experimental" in line:
continue
# spell-checker: ignore mirrorlist
match = re.search(
r'href="(?:\./)?nuitka-(.*).noarch\.rpm(?:\.mirrorlist)?"', line
)
try:
candidates.append(match.group(1))
except Exception:
print("problem with line %r from '%s'" % (line, url))
raise
def numberize(x):
if x.startswith("lp"):
x = x[2:]
if x.startswith("bp"):
x = x[2:]
return int(x)
def splitVersion(v):
for w in v.split("."):
yield from w.split("rc")
def compareVersion(v):
v = v.split("-")
v = tuple(tuple(numberize(x) for x in splitVersion(value)) for value in v)
return v
max_release = max(candidates, key=compareVersion)
candidates = []
for line in output:
if ".rpm" not in line:
continue
if "unstable" not in line:
continue
match = re.search(
r'href="(?:\./)?nuitka-unstable-(.*).noarch\.rpm(?:\.mirrorlist)?"',
line,
)
try:
candidates.append(match.group(1))
except Exception:
print("problem with line %r from '%s'" % (line, url))
raise
max_prerelease = max(candidates, key=compareVersion)
assert "6.7" not in max_prerelease, command
my_print("Repo %s %s" % (repo_name, max_prerelease))
return max_release, max_prerelease
min_rhel = 7
max_rhel = 8
min_fedora = 36
max_fedora = 36
rhel_rpm = {}
for rhel_number in range(min_rhel, max_rhel + 1):
stable, develop = checkOBS("RedHat_RHEL-%d" % rhel_number)
rhel_rpm["stable", rhel_number] = stable
rhel_rpm["develop", rhel_number] = develop
max_centos6_release, max_centos6_prerelease = checkOBS("CentOS_CentOS-6")
max_centos7_release, max_centos7_prerelease = checkOBS("CentOS_7")
max_centos8_release, max_centos8_prerelease = checkOBS("CentOS_8")
centos_rpm = {}
centos_rpm["stable", 6] = max_centos6_release
centos_rpm["develop", 6] = max_centos6_prerelease
centos_rpm["stable", 7] = max_centos7_release
centos_rpm["develop", 7] = max_centos7_prerelease
centos_rpm["stable", 8] = max_centos8_release
centos_rpm["develop", 8] = max_centos8_prerelease
fedora_rpm = {}
for fedora_number in range(min_fedora, max_fedora + 1):
stable, develop = checkOBS("Fedora_%d" % fedora_number)
fedora_rpm["stable", fedora_number] = stable
fedora_rpm["develop", fedora_number] = develop
opensuse_rpm = {}
min_leap_minor = 4
max_leap_minor = 4
for leap_minor in range(min_leap_minor, max_leap_minor + 1):
stable, develop = checkOBS(f"openSUSE_Leap_15.{leap_minor}")
opensuse_rpm["stable", leap_minor] = stable
opensuse_rpm["develop", leap_minor] = develop
max_sle_150_release, max_sle_150_prerelease = checkOBS("SLE_15")
findings = {
"plain_prerelease": makePlain(max_pre_release),
"deb_prerelease": max_pre_release,
"plain_stable": makePlain(max_stable_release),
"deb_stable": max_stable_release,
}
templates = {}
def makeFedoraText(fedora_number, release):
version = fedora_rpm[release, fedora_number]
return f"""Nuitka {version.split("-", 1)[0]}"""
def makeCentOSText(centos_number, release):
version = centos_rpm[release, centos_number]
return f"""Nuitka {version.split("-", 1)[0]}"""
def makeRHELText(rhel_number, release):
version = rhel_rpm[release, rhel_number]
return f"""Nuitka {version.split("-", 1)[0]}"""
def makeLeapText(leap_number, release):
version = opensuse_rpm[release, leap_number]
return f"""Nuitka {version.split("-", 1)[0]}"""
def makeVersionText(version):
return f"""Nuitka {version.split("-", 1)[0]}"""
def makeRepoLinkText(repo_name):
return f"""`repository file <https://download.opensuse.org/repositories/home:/kayhayen/{repo_name}/home:kayhayen.repo>`__"""
fedora_data = [
(
f"Fedora {fedora_number}",
makeRepoLinkText(f"Fedora_{fedora_number}"),
makeFedoraText(fedora_number, "stable"),
makeFedoraText(fedora_number, "develop"),
)
for fedora_number in range(max_fedora, min_fedora - 1, -1)
]
fedora_table = makeTable(
[["Fedora Version", "RPM Repository", "Stable", "Develop"]] + fedora_data
)
centos_data = [
(
"CentOS 8",
makeRepoLinkText("CentOS_8"),
makeCentOSText(8, "stable"),
makeCentOSText(8, "develop"),
),
(
"CentOS 7",
makeRepoLinkText("CentOS_7"),
makeCentOSText(7, "stable"),
makeCentOSText(7, "develop"),
),
(
"CentOS 6",
makeRepoLinkText("CentOS_CentOS-6"),
makeCentOSText(6, "stable"),
makeCentOSText(6, "develop"),
),
]
centos_table = makeTable(
[["CentOS Version", "RPM Repository", "Stable", "Develop"]] + centos_data
)
rhel_data = [
(
f"RHEL {rhel_number}",
makeRepoLinkText("RedHat_RHEL-%d" % rhel_number),
makeRHELText(rhel_number, "stable"),
makeRHELText(rhel_number, "develop"),
)
for rhel_number in range(max_rhel, min_rhel - 1, -1)
]
rhel_table = makeTable(
[["RHEL Version", "RPM Repository", "Stable", "Develop"]] + rhel_data
)
suse_data = [
(
f"openSUSE Leap 15.{leap_minor}",
makeRepoLinkText(f"openSUSE_Leap_15.{leap_minor}"),
makeLeapText(leap_minor, "stable"),
makeLeapText(leap_minor, "develop"),
)
for leap_minor in range(min_leap_minor, max_leap_minor + 1)
]
suse_data.insert(
0,
(
"SLE 15",
makeRepoLinkText("SLE_15"),
makeVersionText(max_sle_150_release),
makeVersionText(max_sle_150_prerelease),
),
)
suse_table = makeTable(
[["SUSE Version", "RPM Repository", "Stable", "Develop"]] + suse_data
)
plain_prerelease = makePlain(max_pre_release)
plain_stable = makePlain(max_stable_release)
source_table = makeTable(
[["Branch", "zip", "tar.gz", "tar.bz2"]]
+ [
(
"Stable",
f"`Nuitka {plain_stable}.zip <https://nuitka.net/releases/Nuitka-{plain_stable}.zip>`__",
f"`Nuitka {plain_stable}.tar.gz <https://nuitka.net/releases/Nuitka-{plain_stable}.tar.gz>`__",
f"`Nuitka {plain_stable}.tar.bz2 <https://nuitka.net/releases/Nuitka-{plain_stable}.tar.bz2>`__",
),
(
"Develop",
f"`Nuitka {plain_prerelease}.zip <https://nuitka.net/releases/Nuitka-{plain_prerelease}.zip>`__",
f"`Nuitka {plain_prerelease}.tar.gz <https://nuitka.net/releases/Nuitka-{plain_prerelease}.tar.gz>`__",
f"`Nuitka {plain_prerelease}.tar.bz2 <https://nuitka.net/releases/Nuitka-{plain_prerelease}.tar.bz2>`__",
),
]
)
major, minor = plain_stable.split(".")[:2]
major = int(major)
minor = int(minor)
plain_stable_minor = "%d.%d" % (major, minor)
if minor == 9:
major += 1
minor = 0
else:
minor += 1
plain_stable_next = "%d.%d" % (major, minor)
with withFileOpenedAndAutoFormatted("site/dynamic.inc") as output_file:
output_file.write(
"""
.. |NUITKA_VERSION| replace:: %s
.. |NUITKA_VERSION_MINOR| replace:: %s
.. |NUITKA_VERSION_NEXT| replace:: %s
"""
% (plain_stable, plain_stable_minor, plain_stable_next),
)
with withFileOpenedAndAutoFormatted("site/doc/fedora-downloads.inc") as output_file:
output_file.write(fedora_table)
with withFileOpenedAndAutoFormatted("site/doc/centos-downloads.inc") as output_file:
output_file.write(centos_table)
with withFileOpenedAndAutoFormatted("site/doc/rhel-downloads.inc") as output_file:
output_file.write(rhel_table)
with withFileOpenedAndAutoFormatted("site/doc/suse-downloads.inc") as output_file:
output_file.write(suse_table)
with withFileOpenedAndAutoFormatted("site/doc/source-downloads.inc") as output_file:
output_file.write(source_table)
# slugify is copied from
# http://code.activestate.com/recipes/
# 577257-slugify-make-a-string-usable-in-a-url-or-filename/
_slugify_strip_re = re.compile(r"[^\w\s-]")
_slugify_hyphenate_re = re.compile(r"[-\s]+")
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
From Django's "django/template/defaultfilters.py".
"""
if type(value) is str:
import unidecode
value = unidecode.unidecode(value)
value = str(_slugify_strip_re.sub("", value).strip().lower())
return _slugify_hyphenate_re.sub("-", value)
def _splitRestByChapter(lines):
marker = "****"
section_markers = []
for count, line in enumerate(lines):
if line.startswith(marker) and lines[count + 2].startswith(marker):
section_markers.append((count, lines[count + 1].strip()))
for count, (section_start_line, title) in enumerate(section_markers):
try:
end_line = section_markers[count + 1][0]
except IndexError:
end_line = None
yield title, lines[section_start_line + 3 : end_line]
def updateReleasePosts():
_updateReleasePosts("site/changelog/Changelog.rst")
_updateReleasePosts("site/changelog/Changelog-1.x.rst")
_updateReleasePosts("site/changelog/Changelog-0.x.rst")
def _updateReleasePosts(changelog_filename):
count = 0
for title, lines in _splitRestByChapter(open(changelog_filename).readlines()):
title = title.lstrip()
count += 1
# Ignore draft for pages.
if "Draft" in title:
continue
slug = slugify(title)
# For the pages except very first, use a leading sentence.
if "release-01-releasing" not in slug:
lines = (
[
"""\
This is to inform you about the new stable release
of `Nuitka <https://nuitka.net>`__. It is the extremely
compatible Python compiler, `"download now" </doc/download.html>`_.\n""",
"\n",
]
+ lines
)
else:
lines.append(
"""
But yes, lets see what happens. Oh, and you will find its `latest
version here </doc/download.html>`_.
Kay Hayen
"""
)
if "release-038" in slug:
slug += "---windows-support"
if "release-02" in slug:
slug = slug.replace("nuitka-release", "release-nuitka")
if "release-011" in slug:
slug = "minor-" + slug.replace("nuitka-release", "release-nuitka")
if "release-01-releasing" in slug:
slug = "releasing-nuitka-to-the-world"
output_path = "site/posts"
txt_path = os.path.join(output_path, f"{slug}.rst")
if os.path.exists(txt_path):
pub_date = open(txt_path).readline().split(maxsplit=2)[2].strip()
else:
pub_date = datetime.datetime.now() + datetime.timedelta(days=1)
pub_date = pub_date.strftime("%Y/%m/%d %H:%M")
lines = [
".. post:: %s\n" % pub_date,
" :tags: compiler, Python, Nuitka\n",
" :author: Kay Hayen\n",
"\n",
title.strip() + "\n",
"~~~~~\n",
"\n",
] + lines
with withFileOpenedAndAutoFormatted(txt_path) as output_file:
output_file.write("".join(lines))
def updateDocs():
updateReleasePosts()
_translations = ("zh_CN/", "de_DE/")
def _getLanguageFromFilename(filename):
filename_relative = os.path.relpath(filename, "output")
if filename_relative.startswith(("zh_CN/", "de_DE/")):
return filename_relative[3:5].upper(), filename_relative[6:]
else:
return "EN", filename_relative
def _getTranslationFileSet(filename):
language, filename_translation = _getLanguageFromFilename(filename)
filename_translations = {
os.path.join("output", translation, filename_translation)
for translation in _translations
if os.path.exists(os.path.join("output", translation, filename_translation))
}
filename_translations.add(os.path.join("output", filename_translation))
return language, filename_translations
js_order = [
"documentation_options.js",
"jquery.js",
"_sphinx_javascript_frameworks_compat.js",
"doctools.js",
"sphinx_highlight.js",
"theme.js",
"clipboard.min.js",
"copybutton.js",
"translations.js",
]
def _makeJsCombined(js_filenames):
js_filenames = list(js_filenames)
if "_static/jquery.js" not in js_filenames:
js_filenames.append("_static/jquery.js")
js_filenames.sort(key=lambda x: js_order.index(os.path.basename(x)))
js_set_contents = (
"\n".join(getFileContents(f"output/{js_name}") for js_name in js_filenames)
+ """
jQuery(function () {
SphinxRtdTheme.Navigation.enable(true);
});
"""
+ """
(function() {
var id = '82f00db2-cffd-11ee-882e-0242ac130002';
var ci_search = document.createElement('script');
ci_search.type = 'text/javascript';
ci_search.async = true;
ci_search.src = 'https://cse.expertrec.com/api/js/ci_common.js?id=' + id;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ci_search, s);
})();
"""
)
js_set_output_filename = "/_static/combined_%s.js" % getHashFromValues(
js_set_contents
)
filename = f"output{js_set_output_filename}"
if not os.path.exists(filename):
putTextFileContents(filename, js_set_contents)
return js_set_output_filename
def runPostProcessing():
# Compress the CSS and JS files into one file, clean up links, and
# do other touch ups. spell-checker: ignore searchindex,searchtools
for delete_filename in ("searchindex.js", "searchtools.js", "search.html"):
deleteFile(os.path.join("output", delete_filename), must_exist=False)
for translation in _translations:
deleteFile(
os.path.join("output", translation, delete_filename), must_exist=False
)
# Force working on the root document first.
file_list = getFileList("output", only_suffixes=".html")
file_list.remove("output/index.html")
file_list.insert(0, "output/index.html")
root_doc = None
for filename in file_list:
doc = html.fromstring(getFileContents(filename, mode="rb"))
if root_doc is None:
root_doc = doc
# Repair favicon extension not cooperation with ablog extension,
# copy over the root_doc links.
fav_icons = doc.xpath("//head/link[@rel='icon']")
if not fav_icons:
(head_node,) = doc.xpath("head")
for fav_icon in root_doc.xpath("//head/link[@rel='icon']"):
fav_icon = copy.deepcopy(fav_icon)
fav_icon.attrib["href"] = "/" + fav_icon.attrib["href"]
head_node.append(fav_icon)
# Check copybutton.js
has_highlight = doc.xpath("//div[@class='highlight']")
has_inline_tabs = doc.xpath("//*[@class='sd-tab-label']")
# Detect if asciinema is used in the page
has_asciinema = False
for script_tag in doc.xpath("//script"):
if script_tag.text and "AsciinemaPlayer" in script_tag.text:
has_asciinema = True
for search_link in doc.xpath("//link[@rel='search']"):
search_link.getparent().remove(search_link)
for current_link in doc.xpath("//a[@class='current reference internal']"):
current_link.attrib["href"] = "/" + os.path.relpath(filename, "output")
for current_link in doc.xpath("//a[@class='reference internal']"):
if current_link.attrib["href"] == "index.html":
current_link.attrib["href"] = "/" + os.path.relpath(
os.path.dirname(filename), "output"
)
for current_link in doc.xpath(
"//ul[contains(@class, 'hub-toc')]//a[@class='reference internal']"
):
if current_link.attrib["href"] == "/":
parent_tag = current_link.getparent()
assert parent_tag.tag == "p", parent_tag
parent_tag.attrib["class"] = "hub-nav-current"
for child in current_link:
current_link.remove(child)
parent_tag.append(child)
parent_tag.remove(current_link)
for current_hub_card in doc.xpath(
"//div[contains(@class, 'hub-card-set')]//div[contains(@class, 'sd-card-body')]"
):
has_arrow_div = current_hub_card.xpath("div[@class='hub-circle-button']")
if not has_arrow_div:
hub_card_div = html.fromstring(
"""<div class="hub-card-contents"></div>"""
)
for child in current_hub_card:
current_hub_card.remove(child)
hub_card_div.append(child)
current_hub_card.append(hub_card_div)
current_hub_card.append(
html.fromstring(
"""<div class="hub-circle-button"><i class="fa fa-arrow-circle-right" aria-hidden="true" style="font-size: 25px;"></i></div>"""
)
)
current_hub_card.attrib["class"] = (
current_hub_card.attrib["class"] + " hub-card"
)
for current_hub_title in doc.xpath(
"//div[contains(@class, 'hub-card-set')]//div[contains(@class, 'sd-card-title')]"
):
for first_child in current_hub_title:
if first_child.tag == "a":
for sub_child in first_child:
first_child.remove(sub_child)
current_hub_title.insert(0, sub_child)
first_child.attrib["class"] = (
current_hub_card.attrib["class"] + " hub-card-link"
)
break
css_links = doc.xpath("//link[@rel='stylesheet']")
assert css_links
# Remove version trick from links, we don't need it really.
for css_link in css_links:
css_link.attrib["href"] = css_link.get("href").split("?")[0]
bread_crumbs_hr = doc.xpath("//div[@role='navigation']/hr")
if bread_crumbs_hr:
bread_crumbs_hr[0].getparent().remove(bread_crumbs_hr[0])
if css_filenames := [
os.path.normpath(
f'output/{os.path.relpath(os.path.dirname(filename), "output")}/{css_link.get("href")}'
)
for css_link in css_links
if "combined_" not in css_link.get("href")
if "copybutton" not in css_link.get("href") or has_highlight
if "my_theme" not in css_link.get("href") or not in_devcontainer
if "asciinema" not in css_link.get("href")
]:
output_filename = "/_static/css/combined_%s.css" % getHashFromValues(
*css_filenames
)
if not os.path.exists(output_filename):
merged_css = "\n".join(
getFileContents(css_filename)
for css_filename in sorted(css_filenames, key=lambda x: "my_" in x)
)
# Do not display fonts on mobile devices.
merged_css = re.sub(
r"@font-face\{(?!.*?awesome)(.*?)\}",
r"@media(min-width:901px){@font-face{\1}}",
merged_css,
flags=re.S,
)
merged_css = re.sub(
r"@font-face\{([^)]*?Lato)(.*?)\}",
r"",
merged_css,
flags=re.S,
)
merged_css = merged_css.replace("Lato", "ui-sans-serif")
merged_css = re.sub(
r"@font-face\{([^)]*?Roboto Slab)(.*?)\}",
r"",
merged_css,
flags=re.S,
)
merged_css = merged_css.replace(
"Roboto Slab",
"Rockwell, 'Rockwell Nova','Roboto Slab','DejaVu Serif','Sitka Small',serif",
)
merged_css = re.sub(
r"@font-face\{(.*?)\}",
r"@font-face{font-display:swap;\1}",
merged_css,
flags=re.S,
)
merged_css = merged_css.replace(
"@media(min-width: 1200px)", "@media(min-width: 1500px)"
)
merged_css = merged_css.replace(
"@media(min-width: 992px)", "@media(min-width: 1192px)"
)
# Strip comments and trailing whitespace (created by that in part)
merged_css = re.sub(r"/\*.*?\*/", "", merged_css, flags=re.S)
merged_css = re.sub(r"\s+\n", r"\n", merged_css, flags=re.M)
putTextFileContents(
filename=f"output{output_filename}", contents=merged_css
)
css_links[0].attrib["href"] = output_filename
for css_link in css_links[1:]:
if in_devcontainer and "my_theme" in css_link.attrib["href"]:
continue
if "asciinema" in css_link.attrib["href"] and has_asciinema:
continue
css_link.getparent().remove(css_link)
for link in doc.xpath("//a[not(contains(@class, 'intern'))]"):
if (
link.attrib["href"].startswith("http:")
or link.attrib["href"].startswith("https:")
) and "nuitka.net" not in link.attrib["href"]:
link.attrib["target"] = "_blank"
for link in doc.xpath("//link[@rel='canonical']"):
if link.attrib["href"].endswith("/index.html"):
link.attrib["href"] = link.attrib["href"][:-11]
# Make internal links more canonical, no index.html, no trailing #
for link in doc.xpath("//a[not(contains(@class, 'extern'))]"):
link_target = link.attrib["href"]
if link_target.startswith("http"):
continue
if link_target.endswith("/index.html"):
link_target = link_target[:-11]
if link_target.endswith("#"):
link_target = link_target[:-1]
if not link_target:
link_target = "/"
link.attrib["href"] = link_target
has_top_nav = doc.xpath("//div[@class='top_nav']")
top_link_nav = None
if not has_top_nav:
try:
h1 = doc.xpath("//h1")[0]
except IndexError:
pass
else:
top_nav = html.fromstring("""<div class="top_nav"></div>""")
h1.getparent().insert(h1.getparent().index(h1), top_nav)
(top_link_nav,) = doc.xpath("//nav[@class='top_link_nav']")
top_link_nav.getparent().remove(top_link_nav)
top_nav.append(top_link_nav)
social_container = doc.xpath("//div[@class='share-button-container']")[
0
]
social_container.getparent().remove(social_container)
top_link_nav.append(social_container)
try:
blog_container = doc.xpath("//div[@class='blog-post-box']")[0]
except IndexError:
pass
else:
blog_container.getparent().remove(blog_container)
top_nav.getparent().insert(
top_nav.getparent().index(top_nav) + 1, blog_container
)
for node in doc.xpath("//div[@class='wy-side-nav-search']"):
node.getparent().remove(node)
script_tag_first = None
js_filenames = []
for script_tag in doc.xpath("//script"):
if "src" in script_tag.attrib:
script_tag.attrib["src"] = script_tag.get("src").split("?")[0]
else:
if (