Skip to content

Commit e23245a

Browse files
committed
Little tad cleaner way to insert script before body.
1 parent d546822 commit e23245a

File tree

1 file changed

+29
-28
lines changed

1 file changed

+29
-28
lines changed

build_docs.py

Lines changed: 29 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,12 @@
3232
"""
3333

3434
from bisect import bisect_left as bisect
35+
from contextlib import contextmanager, suppress
3536
import filecmp
3637
import logging
3738
import logging.handlers
3839
import os
39-
import pathlib
40+
from pathlib import Path
4041
import re
4142
from shlex import quote
4243
import shutil
@@ -157,7 +158,7 @@ def changed_files(left, right):
157158
changed = []
158159

159160
def traverse(dircmp_result):
160-
base = pathlib.Path(dircmp_result.left).relative_to(left)
161+
base = Path(dircmp_result.left).relative_to(left)
161162
changed.extend(str(base / file) for file in dircmp_result.diff_files)
162163
for dircomp in dircmp_result.subdirs.values():
163164
traverse(dircomp)
@@ -255,38 +256,38 @@ def translation_branch(locale_repo, locale_clone_dir, needed_version):
255256
return locate_nearest_version(branches, needed_version)
256257

257258

259+
@contextmanager
260+
def edit(file):
261+
"""Context manager to edit a file "in place", use it as:
262+
with edit("/etc/hosts") as i, o:
263+
for line in i:
264+
o.write(line.replace("localhoat", "localhost"))
265+
"""
266+
temporary = file.with_name(file.name + ".tmp")
267+
with suppress(OSError):
268+
os.unlink(temporary)
269+
with open(file) as input_file:
270+
with open(temporary, "w") as output_file:
271+
yield input_file, output_file
272+
os.rename(temporary, file)
273+
274+
258275
def setup_switchers(html_root):
259276
"""Setup cross-links between cpython versions:
260277
- Cross-link various languages in a language switcher
261278
- Cross-link various versions in a version switcher
262279
"""
263280
shutil.copy("switchers.js", os.path.join(html_root, "_static"))
264-
shell_out(
265-
" ".join(
266-
[
267-
"sed",
268-
"-i",
269-
quote(
270-
r's#\(^ *\)</body>$#\1<script type="text/javascript" src="_static/switchers.js"></script>\n\0#'
271-
),
272-
os.path.join(html_root, "*.html"),
273-
]
274-
),
275-
shell=True,
276-
)
277-
shell_out(
278-
" ".join(
279-
[
280-
"sed",
281-
"-i",
282-
quote(
283-
r's#\(^ *\)</body>$#\1<script type="text/javascript" src="../_static/switchers.js"></script>\n\0#'
284-
),
285-
os.path.join(html_root, "*/*.html"),
286-
]
287-
),
288-
shell=True,
289-
)
281+
for file in Path(html_root).glob("**/*.html"):
282+
depth = len(file.relative_to(html_root).parts) - 1
283+
script = f""" <script type="text/javascript" src="{'../' * depth}_static/switchers.js"></script>\n"""
284+
with edit(file) as (i, o):
285+
for line in i:
286+
if line == script:
287+
continue
288+
if line == " </body>\n":
289+
o.write(script)
290+
o.write(line)
290291

291292

292293
def build_one(

0 commit comments

Comments
 (0)