Remove unneeded content from within `with` statements

This commit is contained in:
Adam Turner 2025-01-04 06:36:34 +00:00
parent f63784310c
commit e17ed74fe0
10 changed files with 56 additions and 52 deletions

View File

@ -137,15 +137,16 @@ class ChangesBuilder(Builder):
__('could not read %r for changelog creation'), docname __('could not read %r for changelog creation'), docname
) )
continue continue
text = ''.join(hl(i + 1, line) for (i, line) in enumerate(lines))
ctx = {
'filename': str(self.env.doc2path(docname, False)),
'text': text,
}
rendered = self.templates.render('changes/rstsource.html', ctx)
targetfn = os.path.join(self.outdir, 'rst', os_path(docname)) + '.html' targetfn = os.path.join(self.outdir, 'rst', os_path(docname)) + '.html'
ensuredir(os.path.dirname(targetfn)) ensuredir(os.path.dirname(targetfn))
with open(targetfn, 'w', encoding='utf-8') as f: with open(targetfn, 'w', encoding='utf-8') as f:
text = ''.join(hl(i + 1, line) for (i, line) in enumerate(lines)) f.write(rendered)
ctx = {
'filename': str(self.env.doc2path(docname, False)),
'text': text,
}
f.write(self.templates.render('changes/rstsource.html', ctx))
themectx = { themectx = {
'theme_' + key: val for (key, val) in self.theme.get_options({}).items() 'theme_' + key: val for (key, val) in self.theme.get_options({}).items()
} }

View File

@ -198,14 +198,14 @@ def should_write(filepath: str, new_content: str) -> bool:
try: try:
with open(filepath, encoding='utf-8') as oldpot: with open(filepath, encoding='utf-8') as oldpot:
old_content = oldpot.read() old_content = oldpot.read()
old_header_index = old_content.index('"POT-Creation-Date:') old_header_index = old_content.index('"POT-Creation-Date:')
new_header_index = new_content.index('"POT-Creation-Date:') new_header_index = new_content.index('"POT-Creation-Date:')
old_body_index = old_content.index('"PO-Revision-Date:') old_body_index = old_content.index('"PO-Revision-Date:')
new_body_index = new_content.index('"PO-Revision-Date:') new_body_index = new_content.index('"PO-Revision-Date:')
return ( return (
old_content[:old_header_index] != new_content[:new_header_index] old_content[:old_header_index] != new_content[:new_header_index]
or new_content[new_body_index:] != old_content[old_body_index:] or new_content[new_body_index:] != old_content[old_body_index:]
) )
except ValueError: except ValueError:
pass pass

View File

@ -224,10 +224,10 @@ class LiteralIncludeReader:
try: try:
with open(filename, encoding=self.encoding, errors='strict') as f: with open(filename, encoding=self.encoding, errors='strict') as f:
text = f.read() text = f.read()
if 'tab-width' in self.options: if 'tab-width' in self.options:
text = text.expandtabs(self.options['tab-width']) text = text.expandtabs(self.options['tab-width'])
return text.splitlines(True) return text.splitlines(True)
except OSError as exc: except OSError as exc:
msg = __("Include file '%s' not found or reading it failed") % filename msg = __("Include file '%s' not found or reading it failed") % filename
raise OSError(msg) from exc raise OSError(msg) from exc

View File

@ -642,7 +642,7 @@ def find_autosummary_in_files(
for filename in filenames: for filename in filenames:
with open(filename, encoding='utf-8', errors='ignore') as f: with open(filename, encoding='utf-8', errors='ignore') as f:
lines = f.read().splitlines() lines = f.read().splitlines()
documented.extend(find_autosummary_in_lines(lines, filename=filename)) documented.extend(find_autosummary_in_lines(lines, filename=filename))
return documented return documented

View File

@ -304,7 +304,8 @@ def render_math(
def render_maths_to_base64(image_format: str, generated_path: str) -> str: def render_maths_to_base64(image_format: str, generated_path: str) -> str:
with open(generated_path, 'rb') as f: with open(generated_path, 'rb') as f:
encoded = base64.b64encode(f.read()).decode(encoding='utf-8') content = f.read()
encoded = base64.b64encode(content).decode(encoding='utf-8')
if image_format == 'png': if image_format == 'png':
return f'data:image/png;base64,{encoded}' return f'data:image/png;base64,{encoded}'
if image_format == 'svg': if image_format == 'svg':

View File

@ -403,9 +403,10 @@ class SphinxFileOutput(FileOutput):
and os.path.exists(self.destination_path) and os.path.exists(self.destination_path)
): ):
with open(self.destination_path, encoding=self.encoding) as f: with open(self.destination_path, encoding=self.encoding) as f:
# skip writing: content not changed on_disk = f.read()
if f.read() == data: # skip writing: content not changed
return data if on_disk == data:
return data
return super().write(data) return super().write(data)

View File

@ -227,8 +227,8 @@ class FileAvoidWrite:
try: try:
with open(self._path, encoding='utf-8') as old_f: with open(self._path, encoding='utf-8') as old_f:
old_content = old_f.read() old_content = old_f.read()
if old_content == buf: if old_content == buf:
return return
except OSError: except OSError:
pass pass

View File

@ -100,7 +100,7 @@ class RemoteImageHandler(http.server.BaseHTTPRequestHandler):
if self.path == '/sphinx.png': if self.path == '/sphinx.png':
with open('tests/roots/test-local-logo/images/img.png', 'rb') as f: with open('tests/roots/test-local-logo/images/img.png', 'rb') as f:
content = f.read() content = f.read()
content_type = 'image/png' content_type = 'image/png'
if content: if content:
self.send_response(200, 'OK') self.send_response(200, 'OK')

View File

@ -86,12 +86,12 @@ def test_custom_templates(make_app, apidoc):
# Assert that the legacy filename is discovered # Assert that the legacy filename is discovered
with open(builddir / 'mypackage.txt', encoding='utf-8') as f: with open(builddir / 'mypackage.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'The legacy package template was found!' in txt assert 'The legacy package template was found!' in txt
# Assert that the new filename is preferred # Assert that the new filename is preferred
with open(builddir / 'mypackage.mymodule.txt', encoding='utf-8') as f: with open(builddir / 'mypackage.mymodule.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'The Jinja module template was found!' in txt assert 'The Jinja module template was found!' in txt
@pytest.mark.apidoc( @pytest.mark.apidoc(
@ -107,17 +107,17 @@ def test_pep_0420_enabled(make_app, apidoc):
with open(outdir / 'a.b.c.rst', encoding='utf-8') as f: with open(outdir / 'a.b.c.rst', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert 'automodule:: a.b.c.d\n' in rst assert 'automodule:: a.b.c.d\n' in rst
assert 'automodule:: a.b.c\n' in rst assert 'automodule:: a.b.c\n' in rst
with open(outdir / 'a.b.e.rst', encoding='utf-8') as f: with open(outdir / 'a.b.e.rst', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert 'automodule:: a.b.e.f\n' in rst assert 'automodule:: a.b.e.f\n' in rst
with open(outdir / 'a.b.x.rst', encoding='utf-8') as f: with open(outdir / 'a.b.x.rst', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert 'automodule:: a.b.x.y\n' in rst assert 'automodule:: a.b.x.y\n' in rst
assert 'automodule:: a.b.x\n' not in rst assert 'automodule:: a.b.x\n' not in rst
app = make_app('text', srcdir=outdir) app = make_app('text', srcdir=outdir)
app.build() app.build()
@ -131,15 +131,15 @@ def test_pep_0420_enabled(make_app, apidoc):
with open(builddir / 'a.b.c.txt', encoding='utf-8') as f: with open(builddir / 'a.b.c.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'a.b.c package\n' in txt assert 'a.b.c package\n' in txt
with open(builddir / 'a.b.e.txt', encoding='utf-8') as f: with open(builddir / 'a.b.e.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'a.b.e.f module\n' in txt assert 'a.b.e.f module\n' in txt
with open(builddir / 'a.b.x.txt', encoding='utf-8') as f: with open(builddir / 'a.b.x.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'a.b.x namespace\n' in txt assert 'a.b.x namespace\n' in txt
@pytest.mark.apidoc( @pytest.mark.apidoc(
@ -157,15 +157,15 @@ def test_pep_0420_enabled_separate(make_app, apidoc):
with open(outdir / 'a.b.c.rst', encoding='utf-8') as f: with open(outdir / 'a.b.c.rst', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert '.. toctree::\n :maxdepth: 4\n\n a.b.c.d\n' in rst assert '.. toctree::\n :maxdepth: 4\n\n a.b.c.d\n' in rst
with open(outdir / 'a.b.e.rst', encoding='utf-8') as f: with open(outdir / 'a.b.e.rst', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert '.. toctree::\n :maxdepth: 4\n\n a.b.e.f\n' in rst assert '.. toctree::\n :maxdepth: 4\n\n a.b.e.f\n' in rst
with open(outdir / 'a.b.x.rst', encoding='utf-8') as f: with open(outdir / 'a.b.x.rst', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert '.. toctree::\n :maxdepth: 4\n\n a.b.x.y\n' in rst assert '.. toctree::\n :maxdepth: 4\n\n a.b.x.y\n' in rst
app = make_app('text', srcdir=outdir) app = make_app('text', srcdir=outdir)
app.build() app.build()
@ -181,15 +181,15 @@ def test_pep_0420_enabled_separate(make_app, apidoc):
with open(builddir / 'a.b.c.txt', encoding='utf-8') as f: with open(builddir / 'a.b.c.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'a.b.c package\n' in txt assert 'a.b.c package\n' in txt
with open(builddir / 'a.b.e.f.txt', encoding='utf-8') as f: with open(builddir / 'a.b.e.f.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'a.b.e.f module\n' in txt assert 'a.b.e.f module\n' in txt
with open(builddir / 'a.b.x.txt', encoding='utf-8') as f: with open(builddir / 'a.b.x.txt', encoding='utf-8') as f:
txt = f.read() txt = f.read()
assert 'a.b.x namespace\n' in txt assert 'a.b.x namespace\n' in txt
@pytest.mark.apidoc(coderoot='test-apidoc-pep420/a') @pytest.mark.apidoc(coderoot='test-apidoc-pep420/a')
@ -214,9 +214,9 @@ def test_pep_0420_disabled_top_level_verify(make_app, apidoc):
with open(outdir / 'c.rst', encoding='utf-8') as f: with open(outdir / 'c.rst', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert 'c package\n' in rst assert 'c package\n' in rst
assert 'automodule:: c.d\n' in rst assert 'automodule:: c.d\n' in rst
assert 'automodule:: c\n' in rst assert 'automodule:: c\n' in rst
app = make_app('text', srcdir=outdir) app = make_app('text', srcdir=outdir)
app.build() app.build()
@ -238,8 +238,8 @@ def test_trailing_underscore(make_app, apidoc):
builddir = outdir / '_build' / 'text' builddir = outdir / '_build' / 'text'
with open(builddir / 'package_.txt', encoding='utf-8') as f: with open(builddir / 'package_.txt', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert 'package_ package\n' in rst assert 'package_ package\n' in rst
assert 'package_.module_ module\n' in rst assert 'package_.module_ module\n' in rst
@pytest.mark.apidoc( @pytest.mark.apidoc(
@ -349,7 +349,7 @@ def test_extension_parsed(apidoc):
with open(outdir / 'conf.py', encoding='utf-8') as f: with open(outdir / 'conf.py', encoding='utf-8') as f:
rst = f.read() rst = f.read()
assert 'sphinx.ext.mathjax' in rst assert 'sphinx.ext.mathjax' in rst
@pytest.mark.apidoc( @pytest.mark.apidoc(

View File

@ -84,11 +84,12 @@ def run_extract() -> None:
log = _get_logger() log = _get_logger()
with open('sphinx/__init__.py', encoding='utf-8') as f: with open('sphinx/__init__.py', encoding='utf-8') as f:
for line in f.read().splitlines(): lines = f.readlines()
if line.startswith('__version__ = '): for line in lines:
# remove prefix; strip whitespace; remove quotation marks if line.startswith('__version__ = '):
sphinx_version = line[14:].strip()[1:-1] # remove prefix; strip whitespace; remove quotation marks
break sphinx_version = line[14:].strip()[1:-1]
break
catalogue = Catalog(project='Sphinx', version=sphinx_version, charset='utf-8') catalogue = Catalog(project='Sphinx', version=sphinx_version, charset='utf-8')