Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions sphinx/builders/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ def build(

with (
progress_message(__('pickling environment')),
open(os.path.join(self.doctreedir, ENV_PICKLE_FILENAME), 'wb') as f,
open(self.doctreedir / ENV_PICKLE_FILENAME, 'wb') as f,
):
pickle.dump(self.env, f, pickle.HIGHEST_PROTOCOL)

Expand Down Expand Up @@ -622,7 +622,7 @@ def read_doc(self, docname: str, *, _cache: bool = True) -> None:
env.prepare_settings(docname)

# Add confdir/docutils.conf to dependencies list if exists
docutilsconf = os.path.join(self.confdir, 'docutils.conf')
docutilsconf = self.confdir / 'docutils.conf'
if os.path.isfile(docutilsconf):
env.note_dependency(docutilsconf)

Expand Down Expand Up @@ -674,7 +674,7 @@ def write_doctree(
doctree.settings.env = None
doctree.settings.record_dependencies = None

doctree_filename = os.path.join(self.doctreedir, docname + '.doctree')
doctree_filename = self.doctreedir / f'{docname}.doctree'
ensuredir(os.path.dirname(doctree_filename))
with open(doctree_filename, 'wb') as f:
pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL)
Expand Down
36 changes: 19 additions & 17 deletions sphinx/builders/_epub_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import os.path
import re
import time
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple
from urllib.parse import quote
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
Expand All @@ -19,12 +20,12 @@
from sphinx.builders.html._build_info import BuildInfo
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util._pathlib import _StrPath
from sphinx.util.display import status_iterator
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.osutil import copyfile, ensuredir, relpath

if TYPE_CHECKING:
from pathlib import Path
from typing import Any

from docutils.nodes import Element, Node
Expand Down Expand Up @@ -158,7 +159,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
guide_titles = GUIDE_TITLES
media_types = MEDIA_TYPES
refuri_re = REFURI_RE
template_dir = ''
template_dir: _StrPath = _StrPath()
doctype = ''

def init(self) -> None:
Expand Down Expand Up @@ -417,7 +418,7 @@ def copy_image_files_pil(self) -> None:
The method tries to read and write the files with Pillow, converting
the format and resizing the image if necessary/possible.
"""
ensuredir(os.path.join(self.outdir, self.imagedir))
ensuredir(self.outdir / self.imagedir)
for src in status_iterator(
self.images,
__('copying images... '),
Expand All @@ -427,12 +428,12 @@ def copy_image_files_pil(self) -> None:
):
dest = self.images[src]
try:
img = Image.open(os.path.join(self.srcdir, src))
img = Image.open(self.srcdir / src)
except OSError:
if not self.is_vector_graphics(src):
logger.warning(
__('cannot read image file %r: copying it instead'),
os.path.join(self.srcdir, src),
self.srcdir / src,
)
try:
copyfile(
Expand All @@ -443,7 +444,7 @@ def copy_image_files_pil(self) -> None:
except OSError as err:
logger.warning(
__('cannot copy image file %r: %s'),
os.path.join(self.srcdir, src),
self.srcdir / src,
err,
)
continue
Expand All @@ -459,11 +460,11 @@ def copy_image_files_pil(self) -> None:
nh = round((height * nw) / width)
img = img.resize((nw, nh), Image.BICUBIC)
try:
img.save(os.path.join(self.outdir, self.imagedir, dest))
img.save(self.outdir / self.imagedir / dest)
except OSError as err:
logger.warning(
__('cannot write image file %r: %s'),
os.path.join(self.srcdir, src),
self.srcdir / src,
err,
)

Expand Down Expand Up @@ -511,7 +512,7 @@ def build_mimetype(self) -> None:
"""Write the metainfo file mimetype."""
logger.info(__('writing mimetype file...'))
copyfile(
os.path.join(self.template_dir, 'mimetype'),
self.template_dir / 'mimetype',
self.outdir / 'mimetype',
force=True,
)
Expand All @@ -522,7 +523,7 @@ def build_container(self, outname: str = 'META-INF/container.xml') -> None:
outdir = self.outdir / 'META-INF'
ensuredir(outdir)
copyfile(
os.path.join(self.template_dir, 'container.xml'),
self.template_dir / 'container.xml',
outdir / 'container.xml',
force=True,
)
Expand Down Expand Up @@ -577,9 +578,10 @@ def build_content(self) -> None:
if not self.use_index:
self.ignored_files.append('genindex' + self.out_suffix)
for root, dirs, files in os.walk(self.outdir):
root_path = Path(root)
dirs.sort()
for fn in sorted(files):
filename = relpath(os.path.join(root, fn), self.outdir)
filename = relpath(root_path / fn, self.outdir)
if filename in self.ignored_files:
continue
ext = os.path.splitext(filename)[-1]
Expand Down Expand Up @@ -684,7 +686,7 @@ def build_content(self) -> None:

# write the project file
copy_asset_file(
os.path.join(self.template_dir, 'content.opf.jinja'),
self.template_dir / 'content.opf.jinja',
self.outdir,
context=metadata,
force=True,
Expand Down Expand Up @@ -778,7 +780,7 @@ def build_toc(self) -> None:
level = max(item['level'] for item in self.refnodes)
level = min(level, self.config.epub_tocdepth)
copy_asset_file(
os.path.join(self.template_dir, 'toc.ncx.jinja'),
self.template_dir / 'toc.ncx.jinja',
self.outdir,
context=self.toc_metadata(level, navpoints),
force=True,
Expand All @@ -792,10 +794,10 @@ def build_epub(self) -> None:
"""
outname = self.config.epub_basename + '.epub'
logger.info(__('writing %s file...'), outname)
epub_filename = os.path.join(self.outdir, outname)
epub_filename = self.outdir / outname
with ZipFile(epub_filename, 'w', ZIP_DEFLATED) as epub:
epub.write(os.path.join(self.outdir, 'mimetype'), 'mimetype', ZIP_STORED)
epub.write(self.outdir / 'mimetype', 'mimetype', ZIP_STORED)
for filename in ('META-INF/container.xml', 'content.opf', 'toc.ncx'):
epub.write(os.path.join(self.outdir, filename), filename, ZIP_DEFLATED)
epub.write(self.outdir / filename, filename, ZIP_DEFLATED)
for filename in self.files:
epub.write(os.path.join(self.outdir, filename), filename, ZIP_DEFLATED)
epub.write(self.outdir / filename, filename, ZIP_DEFLATED)
15 changes: 7 additions & 8 deletions sphinx/builders/changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import html
import os.path
from pathlib import Path
from typing import TYPE_CHECKING

from sphinx import package_dir
Expand All @@ -13,7 +14,7 @@
from sphinx.theming import HTMLThemeFactory
from sphinx.util import logging
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.osutil import ensuredir, os_path
from sphinx.util.osutil import ensuredir

if TYPE_CHECKING:
from collections.abc import Set
Expand Down Expand Up @@ -103,9 +104,9 @@ def write_documents(self, _docnames: Set[str]) -> None:
'show_copyright': self.config.html_show_copyright,
'show_sphinx': self.config.html_show_sphinx,
}
with open(os.path.join(self.outdir, 'index.html'), 'w', encoding='utf8') as f:
with open(self.outdir / 'index.html', 'w', encoding='utf8') as f:
f.write(self.templates.render('changes/frameset.html', ctx))
with open(os.path.join(self.outdir, 'changes.html'), 'w', encoding='utf8') as f:
with open(self.outdir / 'changes.html', 'w', encoding='utf8') as f:
f.write(self.templates.render('changes/versionchanges.html', ctx))

hltext = [
Expand Down Expand Up @@ -141,24 +142,22 @@ def hl(no: int, line: str) -> str:
'text': text,
}
rendered = self.templates.render('changes/rstsource.html', ctx)
targetfn = os.path.join(self.outdir, 'rst', os_path(docname)) + '.html'
targetfn = self.outdir / 'rst' / f'{docname}.html'
ensuredir(os.path.dirname(targetfn))
with open(targetfn, 'w', encoding='utf-8') as f:
f.write(rendered)
themectx = {
'theme_' + key: val for (key, val) in self.theme.get_options({}).items()
}
copy_asset_file(
os.path.join(
package_dir, 'themes', 'default', 'static', 'default.css.jinja'
),
Path(package_dir, 'themes', 'default', 'static', 'default.css.jinja'),
self.outdir,
context=themectx,
renderer=self.templates,
force=True,
)
copy_asset_file(
os.path.join(package_dir, 'themes', 'basic', 'static', 'basic.css'),
Path(package_dir, 'themes', 'basic', 'static', 'basic.css'),
self.outdir / 'basic.css',
force=True,
)
Expand Down
5 changes: 3 additions & 2 deletions sphinx/builders/epub3.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from sphinx.config import ENUM
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util._pathlib import _StrPath
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.osutil import make_filename

Expand Down Expand Up @@ -84,7 +85,7 @@ class Epub3Builder(_epub_base.EpubBuilder):
epilog = __('The ePub file is in %(outdir)s.')

supported_remote_images = False
template_dir = os.path.join(package_dir, 'templates', 'epub3')
template_dir = _StrPath(package_dir, 'templates', 'epub3')
doctype = DOCTYPE
html_tag = HTML_TAG
use_meta_charset = True
Expand Down Expand Up @@ -199,7 +200,7 @@ def build_navigation_doc(self) -> None:
refnodes = self.refnodes
navlist = self.build_navlist(refnodes)
copy_asset_file(
os.path.join(self.template_dir, 'nav.xhtml.jinja'),
self.template_dir / 'nav.xhtml.jinja',
self.outdir,
context=self.navigation_doc_metadata(navlist),
force=True,
Expand Down
14 changes: 7 additions & 7 deletions sphinx/builders/gettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,11 @@ def write_doc(self, docname: str, doctree: nodes.document) -> None:
ctime = time.strftime('%Y-%m-%d %H:%M%z', timestamp)


def should_write(filepath: str, new_content: str) -> bool:
def should_write(filepath: str | os.PathLike[str], new_content: str) -> bool:
if not os.path.exists(filepath):
return True
try:
with codecs.open(filepath, encoding='utf-8') as oldpot:
with codecs.open(str(filepath), encoding='utf-8') as oldpot:
old_content = oldpot.read()
old_header_index = old_content.index('"POT-Creation-Date:')
new_header_index = new_content.index('"POT-Creation-Date:')
Expand Down Expand Up @@ -252,11 +252,11 @@ def init(self) -> None:
def _collect_templates(self) -> set[str]:
template_files = set()
for template_path in self.config.templates_path:
tmpl_abs_path = os.path.join(self.app.srcdir, template_path)
tmpl_abs_path = self.app.srcdir / template_path
for dirpath, _dirs, files in walk(tmpl_abs_path):
for fn in files:
if fn.endswith('.html'):
filename = canon_path(os.path.join(dirpath, fn))
filename = Path(dirpath, fn).as_posix()
template_files.add(filename)
return template_files

Expand Down Expand Up @@ -312,7 +312,7 @@ def finish(self) -> None:
operator.itemgetter(0),
):
# noop if config.gettext_compact is set
ensuredir(os.path.join(self.outdir, os.path.dirname(textdomain)))
ensuredir(self.outdir / os.path.dirname(textdomain))

context['messages'] = list(catalog)
template_path = [
Expand All @@ -321,9 +321,9 @@ def finish(self) -> None:
renderer = GettextRenderer(template_path, outdir=self.outdir)
content = renderer.render('message.pot.jinja', context)

pofn = os.path.join(self.outdir, textdomain + '.pot')
pofn = self.outdir / f'{textdomain}.pot'
if should_write(pofn, content):
with codecs.open(pofn, 'w', encoding='utf-8') as pofile:
with codecs.open(str(pofn), 'w', encoding='utf-8') as pofile:
pofile.write(content)


Expand Down
23 changes: 10 additions & 13 deletions sphinx/builders/latex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def init_multilingual(self) -> None:

def write_stylesheet(self) -> None:
highlighter = highlighting.PygmentsBridge('latex', self.config.pygments_style)
stylesheet = os.path.join(self.outdir, 'sphinxhighlight.sty')
stylesheet = self.outdir / 'sphinxhighlight.sty'
with open(stylesheet, 'w', encoding='utf-8') as f:
f.write('\\NeedsTeXFormat{LaTeX2e}[1995/12/01]\n')
f.write(
Expand Down Expand Up @@ -318,7 +318,7 @@ def write_documents(self, _docnames: Set[str]) -> None:
if len(entry) > 5:
toctree_only = entry[5]
destination = SphinxFileOutput(
destination_path=os.path.join(self.outdir, targetname),
destination_path=self.outdir / targetname,
encoding='utf-8',
overwrite_if_changed=True,
)
Expand Down Expand Up @@ -444,21 +444,21 @@ def copy_support_files(self) -> None:
'xindy_lang_option': xindy_lang_option,
'xindy_cyrillic': xindy_cyrillic,
}
staticdirname = os.path.join(package_dir, 'texinputs')
for filename in Path(staticdirname).iterdir():
static_dir_name = Path(package_dir, 'texinputs')
for filename in Path(static_dir_name).iterdir():
if not filename.name.startswith('.'):
copy_asset_file(
os.path.join(staticdirname, filename),
static_dir_name / filename,
self.outdir,
context=context,
force=True,
)

# use pre-1.6.x Makefile for make latexpdf on Windows
if os.name == 'nt':
staticdirname = os.path.join(package_dir, 'texinputs_win')
static_dir_name = Path(package_dir, 'texinputs_win')
copy_asset_file(
os.path.join(staticdirname, 'Makefile.jinja'),
static_dir_name / 'Makefile.jinja',
self.outdir,
context=context,
force=True,
Expand Down Expand Up @@ -496,11 +496,11 @@ def copy_image_files(self) -> None:
except Exception as err:
logger.warning(
__('cannot copy image file %r: %s'),
os.path.join(self.srcdir, src),
self.srcdir / src,
err,
)
if self.config.latex_logo:
if not os.path.isfile(os.path.join(self.confdir, self.config.latex_logo)):
if not os.path.isfile(self.confdir / self.config.latex_logo):
raise SphinxError(
__('logo file %r does not exist') % self.config.latex_logo
)
Expand All @@ -523,11 +523,8 @@ def write_message_catalog(self) -> None:
if self.context['babel'] or self.context['polyglossia']:
context['addtocaptions'] = r'\addto\captions%s' % self.babel.get_language()

filename = os.path.join(
package_dir, 'templates', 'latex', 'sphinxmessages.sty.jinja'
)
copy_asset_file(
filename,
Path(package_dir, 'templates', 'latex', 'sphinxmessages.sty.jinja'),
self.outdir,
context=context,
renderer=LaTeXRenderer(),
Expand Down
Loading
Loading