Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

URI-escape image filenames #10268

Merged
merged 23 commits into from Oct 13, 2022
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion sphinx/builders/_epub_base.py
Expand Up @@ -6,6 +6,7 @@
from os import path
from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
from urllib.parse import quote
AA-Turner marked this conversation as resolved.
Show resolved Hide resolved

from docutils import nodes
from docutils.nodes import Element, Node
Expand Down Expand Up @@ -524,7 +525,7 @@ def build_content(self) -> None:
type='epub', subtype='unknown_project_files')
continue
filename = filename.replace(os.sep, '/')
item = ManifestItem(html.escape(filename),
item = ManifestItem(html.escape(quote(filename)),
html.escape(self.make_id(filename)),
html.escape(self.media_types[ext]))
metadata['manifest_items'].append(item)
Expand Down
2 changes: 1 addition & 1 deletion sphinx/writers/html.py
Expand Up @@ -620,7 +620,7 @@ def visit_image(self, node: Element) -> None:
# rewrite the URI if the environment knows about it
if olduri in self.builder.images:
node['uri'] = posixpath.join(self.builder.imgpath,
self.builder.images[olduri])
urllib.parse.quote(self.builder.images[olduri]))

if 'scale' in node:
# Try to figure out image height and width. Docutils does that too,
Expand Down
2 changes: 1 addition & 1 deletion sphinx/writers/html5.py
Expand Up @@ -567,7 +567,7 @@ def visit_image(self, node: Element) -> None:
# rewrite the URI if the environment knows about it
if olduri in self.builder.images:
node['uri'] = posixpath.join(self.builder.imgpath,
self.builder.images[olduri])
urllib.parse.quote(self.builder.images[olduri]))

if 'scale' in node:
# Try to figure out image height and width. Docutils does that too,
Expand Down
11 changes: 7 additions & 4 deletions sphinx/writers/latex.py
Expand Up @@ -1267,14 +1267,17 @@ def visit_image(self, node: Element) -> None:
if include_graphics_options:
options = '[%s]' % ','.join(include_graphics_options)
base, ext = path.splitext(uri)

if self.in_title and base:
# Lowercase tokens forcely because some fncychap themes capitalize
# the options of \sphinxincludegraphics unexpectedly (ex. WIDTH=...).
self.body.append(r'\lowercase{\sphinxincludegraphics%s}{{%s}%s}' %
(options, base, ext))
cmd = r'\lowercase{\sphinxincludegraphics%s}{{%s}%s}' % (options, base, ext)
else:
self.body.append(r'\sphinxincludegraphics%s{{%s}%s}' %
(options, base, ext))
cmd = r'\sphinxincludegraphics%s{{%s}%s}' % (options, base, ext)
# escape filepath for includegraphics, https://tex.stackexchange.com/a/202714/41112
if '#' in base:
cmd = r'{\catcode`\#=12' + cmd + '}'
self.body.append(cmd)
self.body.extend(post)

def depart_image(self, node: Element) -> None:
Expand Down
3 changes: 3 additions & 0 deletions tests/roots/test-root/images.txt
Expand Up @@ -23,3 +23,6 @@ Sphinx image handling

.. an image with more than 1 dot in its file name
.. image:: img.foo.png

.. an image with a character that is valid in a local file path but not a URL
.. image:: img_#1.png
Binary file added tests/roots/test-root/img_#1.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions tests/test_build_html.py
Expand Up @@ -1397,6 +1397,15 @@ def test_html_remote_images(app, status, warning):
assert not (app.outdir / 'python-logo.png').exists()


@pytest.mark.sphinx('html')
def test_html_encoded_image(app, status, warning):
app.builder.build_all()

result = (app.outdir / 'images.html').read_text()
assert ('<img alt="_images/img_%231.png" src="_images/img_%231.png" />' in result)
assert (app.outdir / '_images/img_#1.png').exists()


@pytest.mark.sphinx('html', testroot='remote-logo')
def test_html_remote_logo(app, status, warning):
app.builder.build_all()
Expand Down
4 changes: 2 additions & 2 deletions tests/test_build_latex.py
Expand Up @@ -58,8 +58,8 @@ def compile_latex_document(app, filename='python.tex'):
except OSError as exc: # most likely the latex executable was not found
raise pytest.skip.Exception from exc
except CalledProcessError as exc:
print(exc.stdout)
print(exc.stderr)
print(exc.stdout.decode('utf8'))
print(exc.stderr.decode('utf8'))
raise AssertionError('%s exited with return code %s' % (app.config.latex_engine,
exc.returncode))

Expand Down
8 changes: 4 additions & 4 deletions tests/test_environment.py
Expand Up @@ -54,19 +54,19 @@ def test_images(app):
htmlbuilder.imgpath = 'dummy'
htmlbuilder.post_process_images(tree)
assert set(htmlbuilder.images.keys()) == \
{'subdir/img.png', 'img.png', 'subdir/simg.png', 'svgimg.svg', 'img.foo.png'}
{'subdir/img.png', 'img.png', 'subdir/simg.png', 'svgimg.svg', 'img.foo.png', 'img_#1.png'}
assert set(htmlbuilder.images.values()) == \
{'img.png', 'img1.png', 'simg.png', 'svgimg.svg', 'img.foo.png'}
{'img.png', 'img1.png', 'simg.png', 'svgimg.svg', 'img.foo.png', 'img_#1.png'}

latexbuilder = LaTeXBuilder(app, app.env)
latexbuilder.init()
latexbuilder.post_process_images(tree)
assert set(latexbuilder.images.keys()) == \
{'subdir/img.png', 'subdir/simg.png', 'img.png', 'img.pdf',
'svgimg.pdf', 'img.foo.png'}
'svgimg.pdf', 'img.foo.png', 'img_#1.png'}
assert set(latexbuilder.images.values()) == \
{'img.pdf', 'img.png', 'img1.png', 'simg.png',
'svgimg.pdf', 'img.foo.png'}
'svgimg.pdf', 'img.foo.png', 'img_#1.png'}


@pytest.mark.sphinx('dummy')
Expand Down