FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
docsbuild-scripts/build_docs.py at main · python/docsbuild-scripts · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
python
/
docsbuild-scripts
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
68
Star
84
Code
Issues
8
Pull requests
2
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
docsbuild-scripts
/
build_docs.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
executable file
·
1591 lines (1359 loc) · 53.1 KB
Breadcrumbs
docsbuild-scripts
/
build_docs.py
Copy path
File metadata and controls
executable file
·
1591 lines (1359 loc) · 53.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""Build the Python docs for various branches and various languages.
Without any arguments builds docs for all active versions and
languages.
Environment variables for:
- `SENTRY_DSN` (Error reporting)
- `FASTLY_SERVICE_ID` / `FASTLY_TOKEN` (CDN purges)
- `PYTHON_DOCS_ENABLE_ANALYTICS` (Enable Plausible for online docs)
are read from the site configuration path for your platform
(/etc/xdg/docsbuild-scripts on linux) if available,
and can be overriden by writing a file to the user config dir
for your platform ($HOME/.config/docsbuild-scripts on linux).
The contents of the file is parsed as toml:
```toml
[env]
SENTRY_DSN = "https://0a0a0a0a0a0a0a0a0a0a0a@sentry.io/69420"
FASTLY_SERVICE_ID = "deadbeefdeadbeefdead"
FASTLY_TOKEN = "secureme!"
PYTHON_DOCS_ENABLE_ANALYTICS = "1"
```
Languages are stored in `config.toml` while versions are discovered
from peps.python.org (generated by `python-releases.toml`).
-q selects "quick build", which means to build only HTML.
Translations are fetched from GitHub repositories according to PEP
545. `--languages` allows selecting translations, like `--languages
en` to just build the English documents.
This script was originally created by Georg Brandl in March 2010.
Modified by Benjamin Peterson to do CDN cache invalidation.
Modified by Julien Palard to build translations.
"""
from
__future__
import
annotations
import
argparse
import
concurrent
.
futures
import
dataclasses
import
datetime
as
dt
import
filecmp
import
json
import
logging
import
logging
.
handlers
import
os
import
re
import
shlex
import
shutil
import
stat
import
subprocess
import
sys
import
venv
from
bisect
import
bisect_left
as
bisect
from
contextlib
import
contextmanager
,
suppress
from
pathlib
import
Path
from
string
import
Template
from
time
import
perf_counter
,
sleep
from
urllib
.
parse
import
urljoin
import
jinja2
import
platformdirs
import
tomlkit
import
urllib3
import
zc
.
lockfile
TYPE_CHECKING
=
False
if
TYPE_CHECKING
:
from
collections
.
abc
import
Collection
,
Iterator
,
Sequence
,
Set
from
typing
import
Literal
try
:
from
os
import
EX_OK
from
os
import
EX_SOFTWARE
as
EX_FAILURE
except
ImportError
:
EX_OK
,
EX_FAILURE
=
0
,
1
try
:
import
sentry_sdk
except
ImportError
:
sentry_sdk
=
None
HERE
=
Path
(
__file__
).
resolve
().
parent
@
dataclasses
.
dataclass
(
frozen
=
True
,
slots
=
True
)
class
Versions
:
_seq
:
Sequence
[
Version
]
def
__iter__
(
self
)
->
Iterator
[
Version
]:
return
iter
(
self
.
_seq
)
def
__reversed__
(
self
)
->
Iterator
[
Version
]:
return
reversed
(
self
.
_seq
)
@
classmethod
def
from_json
(
cls
,
data
:
dict
)
->
Versions
:
"""Load versions from the devguide's JSON representation."""
permitted
=
", "
.
join
(
sorted
(
Version
.
STATUSES
|
Version
.
SYNONYMS
.
keys
()))
versions
=
[]
for
name
,
release
in
data
.
items
():
branch
=
release
[
"branch"
]
status
=
release
[
"status"
]
if
status
in
Version
.
SKIP_STATUSES
:
logging
.
info
(
"Skipping %s with status %r"
,
name
,
status
)
continue
status
=
Version
.
SYNONYMS
.
get
(
status
,
status
)
if
status
not
in
Version
.
STATUSES
:
logging
.
warning
(
"Saw invalid version status %r, expected to be one of %s. Context: %s"
,
status
,
permitted
,
release
,
)
continue
versions
.
append
(
Version
(
name
=
name
,
status
=
status
,
branch_or_tag
=
branch
))
return
cls
(
sorted
(
versions
,
key
=
Version
.
as_tuple
))
def
filter
(
self
,
branches
:
Sequence
[
str
]
=
())
->
Sequence
[
Version
]:
"""Filter the given versions.
If *branches* is given, only *versions* matching *branches* are returned.
Else all live versions are returned (this means no EOL and no
security-fixes branches).
"""
if
branches
:
branches
=
frozenset
(
branches
)
return
[
v
for
v
in
self
if
{
v
.
name
,
v
.
branch_or_tag
}
&
branches
]
return
[
v
for
v
in
self
if
v
.
status
not
in
{
"EOL"
,
"security-fixes"
}]
@
property
def
current_stable
(
self
)
->
Version
:
"""Find the current stable CPython version."""
return
max
((
v
for
v
in
self
if
v
.
status
==
"stable"
),
key
=
Version
.
as_tuple
)
@
property
def
current_dev
(
self
)
->
Version
:
"""Find the current CPython version in development."""
return
max
(
self
,
key
=
Version
.
as_tuple
)
@
dataclasses
.
dataclass
(
frozen
=
True
,
kw_only
=
True
,
slots
=
True
)
class
Version
:
"""Represents a CPython version and its documentation build dependencies."""
name
:
str
status
:
Literal
[
"in development"
,
"pre-release"
,
"stable"
,
"security-fixes"
,
"EOL"
,
]
branch_or_tag
:
str
STATUSES
=
{
"in development"
,
"pre-release"
,
"stable"
,
"security-fixes"
,
"EOL"
,
}
# Statuses for versions we don't build docs for at all.
SKIP_STATUSES
=
{
"planned"
}
# Those synonyms map branch status vocabulary found in the devguide
# with our vocabulary.
SYNONYMS
=
{
"feature"
:
"in development"
,
"bugfix"
:
"stable"
,
"security"
:
"security-fixes"
,
"end-of-life"
:
"EOL"
,
"prerelease"
:
"pre-release"
,
}
def
__eq__
(
self
,
other
:
Version
)
->
bool
:
return
self
.
name
==
other
.
name
@
property
def
requirements
(
self
)
->
list
[
str
]:
"""Generate the right requirements for this version.
Since CPython 3.8 a Doc/requirements.txt file can be used.
In case the Doc/requirements.txt is absent or wrong (a
sub-dependency broke), use this function to override it.
See https://github.com/python/cpython/issues/91294
See https://github.com/python/cpython/issues/91483
"""
dependencies
=
[
"-rrequirements.txt"
,
"jieba"
,
# To improve zh search.
"PyStemmer~=2.2.0"
,
# To improve performance for word stemming.
]
if
self
.
as_tuple
()
>=
(
3
,
11
):
return
dependencies
if
self
.
as_tuple
()
>=
(
3
,
8
):
# Restore the imghdr module for Python 3.8-3.10.
# Use setuptools with pkg_resources
return
dependencies
+
[
"standard-imghdr"
,
"setuptools<82"
]
# Requirements/constraints for Python 3.7 and older, pre-requirements.txt
reqs
=
[
"alabaster<0.7.12"
,
"blurb<1.2"
,
"docutils<=0.17.1"
,
"jieba"
,
"jinja2<3.1"
,
"python-docs-theme<=2023.3.1"
,
"sphinxcontrib-applehelp<=1.0.2"
,
"sphinxcontrib-devhelp<=1.0.2"
,
"sphinxcontrib-htmlhelp<=2.0"
,
"sphinxcontrib-jsmath<=1.0.1"
,
"sphinxcontrib-qthelp<=1.0.3"
,
"sphinxcontrib-serializinghtml<=1.1.5"
,
"standard-imghdr"
,
]
if
self
.
name
in
{
"3.7"
,
"3.6"
,
"2.7"
}:
return
reqs
+
[
"sphinx==2.3.1"
]
if
self
.
name
==
"3.5"
:
return
reqs
+
[
"sphinx==1.8.4"
,
"standard-pipes"
]
raise
ValueError
(
"unreachable"
)
@
property
def
changefreq
(
self
)
->
str
:
"""Estimate this version change frequency, for the sitemap."""
return
{
"EOL"
:
"never"
,
"security-fixes"
:
"yearly"
}.
get
(
self
.
status
,
"daily"
)
def
as_tuple
(
self
)
->
tuple
[
int
, ...]:
"""This version name as tuple, for easy comparisons."""
return
version_to_tuple
(
self
.
name
)
@
property
def
url
(
self
)
->
str
:
"""The doc URL of this version in production."""
return
f"https://docs.python.org/
{
self
.
name
}
/"
@
property
def
title
(
self
)
->
str
:
"""The title of this version's doc, for the sidebar."""
return
f"Python
{
self
.
name
}
(
{
self
.
status
}
)"
@
property
def
picker_label
(
self
)
->
str
:
"""Forge the label of a version picker."""
if
self
.
status
==
"in development"
:
return
f"dev (
{
self
.
name
}
)"
if
self
.
status
==
"pre-release"
:
return
f"pre (
{
self
.
name
}
)"
return
self
.
name
@
dataclasses
.
dataclass
(
frozen
=
True
,
slots
=
True
)
class
Languages
:
_seq
:
Sequence
[
Language
]
def
__iter__
(
self
)
->
Iterator
[
Language
]:
return
iter
(
self
.
_seq
)
def
__reversed__
(
self
)
->
Iterator
[
Language
]:
return
reversed
(
self
.
_seq
)
@
classmethod
def
from_json
(
cls
,
defaults
:
dict
,
languages
:
dict
)
->
Languages
:
default_translated_name
=
defaults
.
get
(
"translated_name"
,
""
)
default_in_prod
=
defaults
.
get
(
"in_prod"
,
True
)
default_sphinxopts
=
defaults
.
get
(
"sphinxopts"
, [])
default_html_only
=
defaults
.
get
(
"html_only"
,
False
)
langs
=
[
Language
(
iso639_tag
=
iso639_tag
,
name
=
section
[
"name"
],
translated_name
=
section
.
get
(
"translated_name"
,
default_translated_name
),
in_prod
=
section
.
get
(
"in_prod"
,
default_in_prod
),
sphinxopts
=
section
.
get
(
"sphinxopts"
,
default_sphinxopts
),
html_only
=
section
.
get
(
"html_only"
,
default_html_only
),
)
for
iso639_tag
,
section
in
languages
.
items
()
]
return
cls
(
langs
)
def
filter
(
self
,
language_tags
:
Sequence
[
str
]
=
())
->
Sequence
[
Language
]:
"""Filter a sequence of languages according to --languages."""
if
language_tags
:
language_tags
=
frozenset
(
language_tags
)
return
[
l
for
l
in
self
if
l
.
tag
in
language_tags
]
# NoQA: E741
return
list
(
self
)
@
dataclasses
.
dataclass
(
order
=
True
,
frozen
=
True
,
kw_only
=
True
)
class
Language
:
iso639_tag
:
str
name
:
str
translated_name
:
str
in_prod
:
bool
sphinxopts
:
Sequence
[
str
]
html_only
:
bool
=
False
@
property
def
tag
(
self
)
->
str
:
return
self
.
iso639_tag
.
replace
(
"_"
,
"-"
).
lower
()
@
property
def
switcher_label
(
self
)
->
str
:
if
self
.
translated_name
:
return
f"
{
self
.
name
}
|
{
self
.
translated_name
}
"
return
self
.
name
@
dataclasses
.
dataclass
(
frozen
=
True
,
kw_only
=
True
,
slots
=
True
)
class
BuildMetadata
:
_version
:
Version
_language
:
Language
@
property
def
sphinxopts
(
self
)
->
Sequence
[
str
]:
return
self
.
_language
.
sphinxopts
@
property
def
iso639_tag
(
self
)
->
str
:
return
self
.
_language
.
iso639_tag
@
property
def
html_only
(
self
)
->
bool
:
return
self
.
_language
.
html_only
or
not
self
.
_language
.
in_prod
@
property
def
url
(
self
):
"""The URL of this version in production."""
if
self
.
is_translation
:
return
f"https://docs.python.org/
{
self
.
version
}
/
{
self
.
language
}
/"
return
f"https://docs.python.org/
{
self
.
version
}
/"
@
property
def
branch_or_tag
(
self
)
->
str
:
return
self
.
_version
.
branch_or_tag
@
property
def
status
(
self
)
->
str
:
return
self
.
_version
.
status
@
property
def
is_eol
(
self
)
->
bool
:
return
self
.
_version
.
status
==
"EOL"
@
property
def
dependencies
(
self
)
->
list
[
str
]:
return
self
.
_version
.
requirements
@
property
def
version
(
self
):
return
self
.
_version
.
name
@
property
def
version_tuple
(
self
):
return
self
.
_version
.
as_tuple
()
@
property
def
language
(
self
):
return
self
.
_language
.
tag
@
property
def
is_translation
(
self
):
return
self
.
language
!=
"en"
@
property
def
slug
(
self
)
->
str
:
return
f"
{
self
.
language
}
/
{
self
.
version
}
"
@
property
def
venv_name
(
self
)
->
str
:
return
f"venv-
{
self
.
version
}
"
@
property
def
locale_repo_url
(
self
)
->
str
:
return
f"https://github.com/python/python-docs-
{
self
.
language
}
.git"
def
run
(
cmd
:
Sequence
[
str
|
Path
],
cwd
:
Path
|
None
=
None
)
->
subprocess
.
CompletedProcess
:
"""Like subprocess.run, with logging before and after the command execution."""
cmd
=
list
(
map
(
str
,
cmd
))
cmdstring
=
shlex
.
join
(
cmd
)
logging
.
debug
(
"Run: '%s'"
,
cmdstring
)
result
=
subprocess
.
run
(
cmd
,
cwd
=
cwd
,
stdin
=
subprocess
.
PIPE
,
stderr
=
subprocess
.
STDOUT
,
stdout
=
subprocess
.
PIPE
,
encoding
=
"utf-8"
,
errors
=
"backslashreplace"
,
check
=
False
,
)
if
result
.
returncode
:
# Log last 20 lines, those are likely the interesting ones.
logging
.
error
(
"Run: '%s' KO:
\n
%s"
,
cmdstring
,
"
\n
"
.
join
(
f"
{
line
}
"
for
line
in
result
.
stdout
.
split
(
"
\n
"
)[
-
20
:]),
)
result
.
check_returncode
()
return
result
def
run_with_logging
(
cmd
:
Sequence
[
str
|
Path
],
cwd
:
Path
|
None
=
None
)
->
None
:
"""Like subprocess.check_call, with logging before the command execution."""
cmd
=
list
(
map
(
str
,
cmd
))
logging
.
debug
(
"Run: '%s'"
,
shlex
.
join
(
cmd
))
with
subprocess
.
Popen
(
cmd
,
cwd
=
cwd
,
stdin
=
subprocess
.
PIPE
,
stderr
=
subprocess
.
STDOUT
,
stdout
=
subprocess
.
PIPE
,
encoding
=
"utf-8"
,
)
as
p
:
try
:
for
line
in
p
.
stdout
or
():
logging
.
debug
(
">>>> %s"
,
line
.
rstrip
())
except
:
p
.
kill
()
raise
if
return_code
:=
p
.
poll
():
raise
subprocess
.
CalledProcessError
(
return_code
,
cmd
[
0
])
def
changed_files
(
left
:
Path
,
right
:
Path
)
->
int
:
"""Compute the number of different files in the two directory trees."""
def
traverse
(
dircmp_result
:
filecmp
.
dircmp
)
->
int
:
changed
=
len
(
dircmp_result
.
diff_files
)
changed
+=
sum
(
map
(
traverse
,
dircmp_result
.
subdirs
.
values
()))
return
changed
return
traverse
(
filecmp
.
dircmp
(
left
,
right
))
@
dataclasses
.
dataclass
class
Repository
:
"""Git repository abstraction for our specific needs."""
remote
:
str
directory
:
Path
def
run
(
self
,
*
args
:
str
)
->
subprocess
.
CompletedProcess
:
"""Run git command in the clone repository."""
return
run
((
"git"
,
"-C"
,
self
.
directory
)
+
args
)
def
get_ref
(
self
,
pattern
:
str
)
->
str
:
"""Return the reference of a given tag or branch."""
try
:
# Maybe it's a branch
return
self
.
run
(
"show-ref"
,
"-s"
,
f"origin/
{
pattern
}
"
).
stdout
.
strip
()
except
subprocess
.
CalledProcessError
:
# Maybe it's a tag
return
self
.
run
(
"show-ref"
,
"-s"
,
f"tags/
{
pattern
}
"
).
stdout
.
strip
()
def
fetch
(
self
)
->
subprocess
.
CompletedProcess
:
"""Try (and retry) to run git fetch."""
try
:
return
self
.
run
(
"fetch"
)
except
subprocess
.
CalledProcessError
as
err
:
logging
.
error
(
"'git fetch' failed (%s), retrying..."
,
err
.
stderr
)
sleep
(
5
)
return
self
.
run
(
"fetch"
)
def
switch
(
self
,
branch_or_tag
:
str
)
->
None
:
"""Reset and cleans the repository to the given branch or tag."""
self
.
run
(
"reset"
,
"--hard"
,
self
.
get_ref
(
branch_or_tag
),
"--"
)
self
.
run
(
"clean"
,
"-dfqx"
)
def
clone
(
self
)
->
bool
:
"""Maybe clone the repository, if not already cloned."""
if
(
self
.
directory
/
".git"
).
is_dir
():
return
False
# Already cloned
logging
.
info
(
"Cloning %s into %s"
,
self
.
remote
,
self
.
directory
)
self
.
directory
.
mkdir
(
mode
=
0o775
,
parents
=
True
,
exist_ok
=
True
)
run
((
"git"
,
"clone"
,
self
.
remote
,
self
.
directory
))
return
True
def
update
(
self
)
->
None
:
self
.
clone
()
or
self
.
fetch
()
def
version_to_tuple
(
version
:
str
)
->
tuple
[
int
, ...]:
"""Transform a version string to a tuple, for easy comparisons."""
return
tuple
(
int
(
part
)
for
part
in
version
.
split
(
"."
))
def
tuple_to_version
(
version_tuple
:
tuple
[
int
, ...])
->
str
:
"""Reverse version_to_tuple."""
return
"."
.
join
(
str
(
part
)
for
part
in
version_tuple
)
def
locate_nearest_version
(
available_versions
:
Collection
[
str
],
target_version
:
str
)
->
str
:
"""Look for the nearest version of target_version in available_versions.
Versions are to be given as tuples, like (3, 7) for 3.7.
>>> locate_nearest_version(["2.7", "3.6", "3.7", "3.8"], "3.9")
'3.8'
>>> locate_nearest_version(["2.7", "3.6", "3.7", "3.8"], "3.5")
'3.6'
>>> locate_nearest_version(["2.7", "3.6", "3.7", "3.8"], "2.6")
'2.7'
>>> locate_nearest_version(["2.7", "3.6", "3.7", "3.8"], "3.10")
'3.8'
>>> locate_nearest_version(["2.7", "3.6", "3.7", "3.8"], "3.7")
'3.7'
"""
available_versions_tuples
=
sorted
(
map
(
version_to_tuple
,
set
(
available_versions
)))
target_version_tuple
=
version_to_tuple
(
target_version
)
try
:
found
=
available_versions_tuples
[
bisect
(
available_versions_tuples
,
target_version_tuple
)
]
except
IndexError
:
found
=
available_versions_tuples
[
-
1
]
return
tuple_to_version
(
found
)
@
contextmanager
def
edit
(
file
:
Path
):
"""Context manager to edit a file "in place", use it as:
with edit("/etc/hosts") as (i, o):
for line in i:
o.write(line.replace("localhoat", "localhost"))
"""
temporary
=
file
.
with_name
(
file
.
name
+
".tmp"
)
with
suppress
(
FileNotFoundError
):
temporary
.
unlink
()
with
open
(
file
,
encoding
=
"UTF-8"
)
as
input_file
:
with
open
(
temporary
,
"w"
,
encoding
=
"UTF-8"
)
as
output_file
:
yield
input_file
,
output_file
temporary
.
rename
(
file
)
@
contextmanager
def
wait_for_lock
(
path
:
Path
,
timeout
:
float
=
600
,
poll_interval
:
float
=
10
)
->
Iterator
[
None
]:
"""Context manager to hold *path* as a lock file, waiting up to *timeout* seconds for it."""
deadline
=
perf_counter
()
+
timeout
while
True
:
try
:
lock
=
zc
.
lockfile
.
LockFile
(
path
)
break
except
zc
.
lockfile
.
LockError
as
err
:
if
perf_counter
()
>=
deadline
:
raise
TimeoutError
(
f"Gave up waiting for lock
{
path
.
name
}
after
{
timeout
}
seconds"
)
from
err
logging
.
info
(
"Waiting for lock %s..."
,
path
.
name
)
sleep
(
poll_interval
)
try
:
yield
finally
:
lock
.
close
()
def
setup_switchers
(
script_content
:
bytes
,
html_root
:
Path
)
->
None
:
"""Setup cross-links between CPython versions:
- Cross-link various languages in a language switcher
- Cross-link various versions in a version switcher
"""
switchers_path
=
html_root
/
"_static"
/
"switchers.js"
switchers_path
.
write_bytes
(
script_content
)
for
file
in
html_root
.
glob
(
"**/*.html"
):
depth
=
len
(
file
.
relative_to
(
html_root
).
parts
)
-
1
src
=
f"
{
'../'
*
depth
}
_static/switchers.js"
script
=
f' <script type="text/javascript" src="
{
src
}
"></script>
\n
'
with
edit
(
file
)
as
(
ifile
,
ofile
):
for
line
in
ifile
:
if
line
==
script
:
continue
if
line
==
" </body>
\n
"
:
ofile
.
write
(
script
)
ofile
.
write
(
line
)
def
head
(
text
:
str
,
lines
:
int
=
10
)
->
str
:
"""Return the first *lines* lines from the given text."""
return
"
\n
"
.
join
(
text
.
split
(
"
\n
"
)[:
lines
])
def
version_info
()
->
None
:
"""Handler for --version."""
try
:
platex_version
=
head
(
subprocess
.
check_output
((
"platex"
,
"--version"
),
text
=
True
),
lines
=
3
,
)
except
FileNotFoundError
:
platex_version
=
"Not installed."
try
:
xelatex_version
=
head
(
subprocess
.
check_output
((
"xelatex"
,
"--version"
),
text
=
True
),
lines
=
2
,
)
except
FileNotFoundError
:
xelatex_version
=
"Not installed."
print
(
f"""
# platex
{
platex_version
}
# xelatex
{
xelatex_version
}
"""
)
@
dataclasses
.
dataclass
class
DocBuilder
:
"""Builder for a CPython version and a language."""
build_meta
:
BuildMetadata
cpython_repo
:
Repository
docs_by_version_content
:
bytes
switchers_content
:
bytes
built_venvs
:
set
[
Path
]
build_root
:
Path
www_root
:
Path
select_output
:
Literal
[
"no-html"
,
"only-html"
,
"only-html-en"
]
|
None
quick
:
bool
group
:
str
log_directory
:
Path
skip_cache_invalidation
:
bool
theme
:
str
@
property
def
html_only
(
self
)
->
bool
:
return
(
self
.
select_output
in
{
"only-html"
,
"only-html-en"
}
or
self
.
quick
or
self
.
build_meta
.
html_only
)
@
property
def
includes_html
(
self
)
->
bool
:
"""Does the build we are running include HTML output?"""
return
self
.
select_output
!=
"no-html"
def
run
(
self
,
http
:
urllib3
.
PoolManager
,
force_build
:
bool
)
->
bool
|
None
:
"""Build and publish a Python doc, for a language, and a version."""
start_time
=
perf_counter
()
start_timestamp
=
dt
.
datetime
.
now
(
tz
=
dt
.
UTC
).
replace
(
microsecond
=
0
)
logging
.
info
(
"Running."
)
try
:
if
self
.
build_meta
.
html_only
and
not
self
.
includes_html
:
logging
.
info
(
"Skipping non-HTML build (language is HTML-only)."
)
return
None
# skipped
self
.
cpython_repo
.
switch
(
self
.
build_meta
.
branch_or_tag
)
if
self
.
build_meta
.
is_translation
:
self
.
clone_translation
()
if
trigger_reason
:=
self
.
should_rebuild
(
force_build
):
self
.
build_venv
()
self
.
build
()
self
.
copy_build_to_webroot
(
http
)
self
.
save_state
(
build_start
=
start_timestamp
,
build_duration
=
perf_counter
()
-
start_time
,
trigger
=
trigger_reason
,
)
else
:
return
None
# skipped
except
TimeoutError
as
err
:
# Another builder held the publish lock for too long; the docs
# were built fine and will be published on the next run.
logging
.
error
(
"%s"
,
err
)
if
sentry_sdk
:
sentry_sdk
.
capture_exception
(
err
)
return
False
except
Exception
as
err
:
logging
.
exception
(
"Badly handled exception, human, please help."
)
if
sentry_sdk
:
sentry_sdk
.
capture_exception
(
err
)
return
False
return
True
@
property
def
locale_dir
(
self
)
->
Path
:
return
self
.
build_root
/
self
.
build_meta
.
version
/
"locale"
@
property
def
checkout
(
self
)
->
Path
:
"""Path to CPython git clone."""
return
self
.
build_root
/
_checkout_name
(
self
.
select_output
)
def
clone_translation
(
self
)
->
None
:
self
.
translation_repo
.
update
()
self
.
translation_repo
.
switch
(
self
.
translation_branch
)
@
property
def
translation_repo
(
self
)
->
Repository
:
"""See PEP 545 for translations repository naming convention."""
locale_clone_dir
=
self
.
locale_dir
/
self
.
build_meta
.
iso639_tag
/
"LC_MESSAGES"
return
Repository
(
self
.
build_meta
.
locale_repo_url
,
locale_clone_dir
)
@
property
def
translation_branch
(
self
)
->
str
:
"""Some CPython versions may be untranslated, being either too old or
too new.
This function looks for remote branches on the given repo, and
returns the name of the nearest existing branch.
It could be enhanced to also search for tags.
"""
remote_branches
=
self
.
translation_repo
.
run
(
"branch"
,
"-r"
).
stdout
branches
=
re
.
findall
(
r"/([0-9]+\.[0-9]+)$"
,
remote_branches
,
re
.
M
)
return
locate_nearest_version
(
branches
,
self
.
build_meta
.
version
)
def
build
(
self
)
->
None
:
"""Build this version/language doc."""
logging
.
info
(
"Build start."
)
start_time
=
perf_counter
()
sphinxopts
=
list
(
self
.
build_meta
.
sphinxopts
)
if
self
.
build_meta
.
is_translation
:
sphinxopts
.
extend
((
f"-D locale_dirs=
{
self
.
locale_dir
}
"
,
f"-D language=
{
self
.
build_meta
.
iso639_tag
}
"
,
"-D gettext_compact=0"
,
"-D translation_progress_classes=1"
,
))
if
self
.
build_meta
.
is_eol
:
sphinxopts
.
append
(
"-D html_context.outdated=1"
)
if
self
.
build_meta
.
status
in
(
"in development"
,
"pre-release"
):
maketarget
=
"autobuild-dev"
else
:
maketarget
=
"autobuild-stable"
if
self
.
html_only
:
maketarget
+=
"-html"
logging
.
info
(
"Running make %s"
,
maketarget
)
python
=
self
.
venv
/
"bin"
/
"python"
sphinxbuild
=
self
.
venv
/
"bin"
/
"sphinx-build"
blurb
=
self
.
venv
/
"bin"
/
"blurb"
if
self
.
includes_html
:
site_url
=
self
.
build_meta
.
url
# Define a tag to enable opengraph socialcards previews
# (used in Doc/conf.py and requires matplotlib)
sphinxopts
+=
(
"-t create-social-cards"
,
f"-D ogp_site_url=
{
site_url
}
"
,
)
if
self
.
build_meta
.
version_tuple
<
(
3
,
8
):
# Disable CPython switchers, we handle them now:
text
=
(
self
.
checkout
/
"Doc"
/
"Makefile"
).
read_text
(
encoding
=
"utf-8"
)
text
=
text
.
replace
(
" -A switchers=1"
,
""
)
(
self
.
checkout
/
"Doc"
/
"Makefile"
).
write_text
(
text
,
encoding
=
"utf-8"
)
self
.
setup_indexsidebar
()
if
self
.
build_meta
.
version_tuple
<
(
3
,
10
):
# The Makefile is broken, and the fix,
# python/cpython#145571 didn't make it into 3.9 in time
(
self
.
checkout
/
"Doc"
/
"dist"
).
mkdir
(
exist_ok
=
True
)
run_with_logging
((
"make"
,
"-C"
,
self
.
checkout
/
"Doc"
,
f"PYTHON=
{
python
}
"
,
f"SPHINXBUILD=
{
sphinxbuild
}
"
,
f"BLURB=
{
blurb
}
"
,
f"VENVDIR=
{
self
.
venv
}
"
,
f"SPHINXOPTS=
{
' '
.
join
(
sphinxopts
)
}
"
,
"SPHINXERRORHANDLING="
,
maketarget
,
))
self
.
log_directory
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
chgrp
(
self
.
log_directory
,
group
=
self
.
group
,
recursive
=
True
)
if
self
.
includes_html
:
setup_switchers
(
self
.
switchers_content
,
self
.
checkout
/
"Doc"
/
"build"
/
"html"
)
logging
.
info
(
"Build done (%s)."
,
format_seconds
(
perf_counter
()
-
start_time
))
def
build_venv
(
self
)
->
None
:
"""Build a venv for the specific Python version.
The venv is created at most once per run, reused by later builds
of the same version, and removed at the end of the run: reusing
a venv across runs can silently keep outdated packages, because
pip considers a requirement satisfied when the installed version
number matches, even if the requirement is a direct URL now
pointing at different code.
"""
venv_name
=
self
.
build_meta
.
venv_name
if
self
.
select_output
is
not
None
:
# Never share a venv with a concurrent differently-selected
# build, which may recreate it mid-build.
venv_name
+=
f"-
{
self
.
select_output
}
"
venv_path
=
self
.
build_root
/
venv_name
if
venv_path
in
self
.
built_venvs
:
self
.
venv
=
venv_path
return
requirements
=
list
(
self
.
build_meta
.
dependencies
)
if
self
.
includes_html
:
# opengraph previews
requirements
.
append
(
"matplotlib>=3"
)
venv
.
create
(
venv_path
,
symlinks
=
os
.
name
!=
"nt"
,
with_pip
=
True
,
clear
=
True
,
upgrade_deps
=
True
,
)
python
=
venv_path
/
"bin"
/
"python"
if
(
self
.
checkout
/
"Doc"
/
"pylock.toml"
).
is_file
():
requirements
.
remove
(
"-rrequirements.txt"
)
run
(
(
python
,
"-m"
,
"pip"
,
"install"
,
"-rpylock.toml"
),
cwd
=
self
.
checkout
/
"Doc"
,
)
run
(
(
python
,
"-m"
,
"pip"
,
"install"
,
self
.
theme
,
*
requirements
),
cwd
=
self
.
checkout
/
"Doc"
,
)
run
((
python
,
"-m"
,
"pip"
,
"freeze"
,
"--all"
))
self
.
built_venvs
.
add
(
venv_path
)
self
.
venv
=
venv_path
def
setup_indexsidebar
(
self
)
->
None
:
"""Copy indexsidebar.html for Sphinx."""
tmpl_src
=
HERE
/
"templates"
tmpl_dst
=
self
.
checkout
/
"Doc"
/
"tools"
/
"templates"
dbv_path
=
tmpl_dst
/
"_docs_by_version.html"
shutil
.
copy
(
tmpl_src
/
"indexsidebar.html"
,
tmpl_dst
/
"indexsidebar.html"
)
if
not
self
.
build_meta
.
is_eol
:
dbv_path
.
write_bytes
(
self
.
docs_by_version_content
)
else
:
shutil
.
copy
(
tmpl_src
/
"_docs_by_version.html"
,
dbv_path
)
def
copy_build_to_webroot
(
self
,
http
:
urllib3
.
PoolManager
)
->
None
:
"""Copy a given build to the appropriate webroot with appropriate rights."""
logging
.
info
(
"Publishing start."
)
start_time
=
perf_counter
()
self
.
www_root
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
if
not
self
.
build_meta
.
is_translation
:
target
=
self
.
www_root
/
self
.
build_meta
.
version
else
:
language_dir
=
self
.
www_root
/
self
.
build_meta
.
language
language_dir
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
chgrp
(
language_dir
,
group
=
self
.
group
,
recursive
=
True
)
language_dir
.
chmod
(
0o775
)
target
=
language_dir
/
self
.
build_meta
.
version
# Builds run concurrently but may publish the same language/version to
# the same directory, so serialise publishes per target.
# Contention is expected, but brief, so wait instead of dying.
with
wait_for_lock
(
HERE
/
f"publish-
{
self
.
build_meta
.
language
}
-
{
self
.
build_meta
.
version
}
.lock"
):
target
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
try
:
target
.
chmod
(
0o775
)
except
PermissionError
as
err
:
logging
.
warning
(
"Can't change mod of %s: %s"
,
target
,
str
(
err
))
chgrp
(
target
,
group
=
self
.
group
,
recursive
=
True
)
changed
=
0
if
self
.
includes_html
:
# Copy built HTML files to webroot (default /srv/docs.python.org)
changed
+=
changed_files
(
self
.
checkout
/
"Doc"
/
"build"
/
"html"
,
target
)
logging
.
info
(
"Copying HTML files to %s"
,
target
)
chgrp
(
self
.
checkout
/
"Doc"
/
"build"
/
"html/"
,
group
=
self
.
group
,
recursive
=
True
,
)
chmod_make_readable
(
self
.
checkout
/
"Doc"
/
"build"
/
"html"
)
run
((
"rsync"
,
"-a"
,
"--delete-delay"
,
"--filter"
,
"P archives/"
,
str
(
self
.
checkout
/
"Doc"
/
"build"
/
"html"
)
+
"/"
,
target
,
))
dist_dir
=
self
.
checkout
/
"Doc"
/
"dist"
if
dist_dir
.
is_dir
():
# Copy archive files to /archives/
logging
.
debug
(
"Copying dist files."
)
chgrp
(
dist_dir
,
group
=
self
.
group
,
recursive
=
True
)
chmod_make_readable
(
dist_dir
)
archives_dir
=
target
/
"archives"
archives_dir
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
archives_dir
.
chmod
(
archives_dir
.
stat
().
st_mode
|
stat
.
S_IROTH
|
stat
.
S_IXOTH
)
chgrp
(
archives_dir
,
group
=
self
.
group
)
changed
+=
1
for
dist_file
in
dist_dir
.
iterdir
():
shutil
.
copy2
(
dist_file
,
archives_dir
/
dist_file
.
name
)
changed
+=
1
logging
.
info
(
"%s files changed"
,
changed
)
if
changed
and
not
self
.
skip_cache_invalidation
:
purge_surrogate_key
(
http
,
self
.
build_meta
.
slug
)
logging
.
info
(
"Publishing done (%s)."
,
format_seconds
(
perf_counter
()
-
start_time
)
)
def
should_rebuild
(
self
,
force
:
bool
)
->
str
|
Literal
[
False
]:
state
=
self
.
load_state
()
if
not
state
:
logging
.
info
(
"Should rebuild: no previous state found."
)
return
"no previous state"
cpython_sha
=
self
.
cpython_repo
.
run
(
"rev-parse"
,
"HEAD"
).
stdout
.
strip
()
if
self
.
build_meta
.
is_translation
:
translation_sha
=
self
.
translation_repo
.
run
(
"rev-parse"
,
"HEAD"
).
stdout
.
strip
()
if
translation_sha
!=
state
[
"translation_sha"
]:
logging
.
info
(
"Should rebuild: new translations (from %s to %s)"
,
state
[
"translation_sha"
],
translation_sha
,
)
return
"new translations"
if
cpython_sha
!=
state
[
"cpython_sha"
]:
diff
=
self
.
cpython_repo
.
run
(
"diff"
,
"--name-only"
,
state
[
"cpython_sha"
],
cpython_sha
).
stdout
if
"Doc/"
in
diff
or
"Misc/NEWS.d/"
in
diff
:
logging
.
info
(
"Should rebuild: Doc/ has changed (from %s to %s)"
,
state
[
"cpython_sha"
],
cpython_sha
,
)
return
"Doc/ has changed"
if
force
:
logging
.
info
(
"Should rebuild: forced."
)
return
"forced"
logging
.
info
(
"Nothing changed, no rebuild needed."
)
return
False
def
load_state
(
self
)
->
dict
:
if
self
.
select_output
is
not
None
:
state_file
=
self
.
build_root
/
f"state-
{
self
.
select_output
}
.toml"
else
:
state_file
=
self
.
build_root
/
"state.toml"
try
:
return
tomlkit
.
loads
(
state_file
.
read_text
(
encoding
=
"UTF-8"
))[
f"/
{
self
.
build_meta
.
slug
}
/"
]
except
(
KeyError
,
FileNotFoundError
):
return
{}
def
save_state
(
self
,
build_start
:
dt
.
datetime
,
build_duration
:
float
,
trigger
:
str
)
->
None
:
"""Save current CPython sha1 and current translation sha1.
Using this we can deduce if a rebuild is needed or not.
"""
if
self
.
select_output
is
not
None
:
state_file
=
self
.
build_root
/
f"state-
{
self
.
select_output
}
.toml"
else
:
state_file
=
self
.
build_root
/
"state.toml"
try
:
states
=
tomlkit
.
parse
(
state_file
.
read_text
(
encoding
=
"UTF-8"
))
except
FileNotFoundError
:
states
=
tomlkit
.
document
()
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL