Skip to content

Commit 411aba6

Browse files
authored
Merge pull request #886 from sphinx-contrib/use-pathlib-part1
Use pathlib (Part 1)
2 parents 8eac40c + 387dc84 commit 411aba6

File tree

89 files changed

+301
-372
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+301
-372
lines changed

sphinxcontrib/confluencebuilder/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# SPDX-License-Identifier: BSD-2-Clause
22
# Copyright Sphinx Confluence Builder Contributors (AUTHORS)
33

4-
from os import path
4+
from pathlib import Path
55
from sphinx.util import docutils
66
from sphinxcontrib.confluencebuilder.builder import ConfluenceBuilder
77
from sphinxcontrib.confluencebuilder.config import handle_config_inited
@@ -58,9 +58,9 @@ def setup(app):
5858
app.add_builder(SingleConfluenceBuilder)
5959

6060
# register this extension's locale
61-
package_dir = path.abspath(path.dirname(__file__))
62-
locale_dir = path.join(package_dir, 'locale')
63-
app.add_message_catalog(MESSAGE_CATALOG_NAME, locale_dir)
61+
package_dir = Path(__file__).parent.resolve()
62+
locale_dir = package_dir / 'locale'
63+
app.add_message_catalog(MESSAGE_CATALOG_NAME, str(locale_dir))
6464

6565
# ##########################################################################
6666

sphinxcontrib/confluencebuilder/builder.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@
55
from collections import defaultdict
66
from docutils import nodes
77
from docutils.io import StringOutput
8+
from pathlib import Path
89
from os import path
910
from sphinx import addnodes
1011
from sphinx import version_info as sphinx_version_info
1112
from sphinx.builders import Builder
1213
from sphinx.locale import _ as SL
13-
from sphinx.util.osutil import ensuredir
1414
from sphinxcontrib.confluencebuilder.assets import ConfluenceAssetManager
1515
from sphinxcontrib.confluencebuilder.assets import ConfluenceSupportedImages
1616
from sphinxcontrib.confluencebuilder.compat import docutils_findall as findall
@@ -41,7 +41,6 @@
4141
from sphinxcontrib.confluencebuilder.util import first
4242
from sphinxcontrib.confluencebuilder.util import handle_cli_file_subset
4343
from sphinxcontrib.confluencebuilder.writer import ConfluenceWriter
44-
import os
4544
import tempfile
4645

4746

@@ -78,6 +77,7 @@ def __init__(self, app, env=None):
7877
self.nav_prev = {}
7978
self.omitted_docnames = []
8079
self.orphan_docnames = []
80+
self.out_dir = Path(self.outdir)
8181
self.parent_id = None
8282
self.publish_allowlist = None
8383
self.publish_denylist = None
@@ -135,7 +135,7 @@ def init(self):
135135
# files are build -- use this to hint to using a temporary directory
136136
# on the same partition the output directory to help prevent issues.
137137
self._imgmath_tempdir = tempfile.mkdtemp(
138-
prefix='.imgmath-', dir=self.outdir)
138+
prefix='.imgmath-', dir=self.out_dir)
139139

140140
if self.config.confluence_publish:
141141
process_ask_configs(self.config)
@@ -469,15 +469,15 @@ def write_doc(self, docname, doctree):
469469
destination = StringOutput(encoding='utf-8')
470470

471471
self.writer.write(doctree, destination)
472-
outfilename = path.join(self.outdir, self.file_transform(docname))
472+
out_file = self.out_dir / self.file_transform(docname)
473473
if self.writer.output is not None:
474-
ensuredir(path.dirname(outfilename))
474+
out_file.parent.mkdir(parents=True, exist_ok=True)
475475
try:
476-
with open(outfilename, 'w', encoding='utf-8') as file:
476+
with out_file.open('w', encoding='utf-8') as file:
477477
if self.writer.output:
478478
file.write(self.writer.output)
479479
except OSError as err:
480-
self.warn(f'error writing file {outfilename}: {err}')
480+
self.warn(f'error writing file {out_file}: {err}')
481481

482482
self._cache_info.track_page_hash(docname)
483483

@@ -760,10 +760,10 @@ def finish(self):
760760
if self._check_publish_skip(docname):
761761
self.verbose(docname + ' skipped due to configuration')
762762
continue
763-
docfile = path.join(self.outdir, self.file_transform(docname))
763+
docfile = self.out_dir / self.file_transform(docname)
764764

765765
try:
766-
with open(docfile, encoding='utf-8') as file:
766+
with docfile.open(encoding='utf-8') as file:
767767
output = file.read()
768768
self.publish_doc(docname, output)
769769
except OSError as err:
@@ -774,10 +774,10 @@ def finish(self):
774774
self.info('done')
775775

776776
if self.config.confluence_publish_intersphinx:
777-
inv = path.join(self.outdir, 'objects.inv')
778-
if os.path.exists(inv):
777+
inventory_db = self.out_dir / 'objects.inv'
778+
if inventory_db.is_file():
779779
self.verbose('registering intersphinx database attachment')
780-
self.assets.add(inv, self.config.root_doc)
780+
self.assets.add(str(inventory_db), self.config.root_doc)
781781
else:
782782
self.verbose('no generated intersphinx database detected')
783783

@@ -948,9 +948,9 @@ def _generate_special_document(self, docname, generator):
948948
self.config.confluence_footer_data)
949949

950950
# generate/replace the document in the output directory
951-
fname = path.join(self.outdir, docname + self.file_suffix)
951+
out_file = self.out_dir / (docname + self.file_suffix)
952952
try:
953-
with open(fname, 'w', encoding='utf-8') as f:
953+
with out_file.open('w', encoding='utf-8') as f:
954954
f.write(self._cached_header_data)
955955
generator(self, docname, f)
956956
f.write(self._cached_footer_data)

sphinxcontrib/confluencebuilder/env.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
# SPDX-License-Identifier: BSD-2-Clause
22
# Copyright Sphinx Confluence Builder Contributors (AUTHORS)
33

4+
from pathlib import Path
45
from sphinxcontrib.confluencebuilder.util import ConfluenceUtil
56
import json
6-
import os
77

88

99
# base filename for cache information
@@ -21,16 +21,14 @@
2121

2222
class ConfluenceCacheInfo:
2323
def __init__(self, builder):
24-
outdir = builder.outdir
25-
2624
self.builder = builder
2725
self.env = builder.env
2826
self._active_dochash = {}
2927
self._active_hash = None
3028
self._active_pids = {}
31-
self._cache_cfg_file = os.path.join(outdir, ENV_CACHE_CONFIG)
32-
self._cache_hash_file = os.path.join(outdir, ENV_CACHE_DOCHASH)
33-
self._cache_publish_file = os.path.join(outdir, ENV_CACHE_PUBLISH)
29+
self._cache_cfg_file = builder.out_dir / ENV_CACHE_CONFIG
30+
self._cache_hash_file = builder.out_dir / ENV_CACHE_DOCHASH
31+
self._cache_publish_file = builder.out_dir / ENV_CACHE_PUBLISH
3432
self._cached_dochash = {}
3533
self._cached_hash = None
3634
self._cached_pids = {}
@@ -76,13 +74,13 @@ def is_outdated(self, docname):
7674

7775
# if there is not output file, considered outdated
7876
dst_filename = self.builder.file_transform(docname)
79-
dst_file = os.path.join(self.builder.outdir, dst_filename)
80-
if not os.path.exists(dst_file):
77+
dst_file = self.builder.out_dir / dst_filename
78+
if not dst_file.is_file():
8179
return True
8280

8381
# if there is not source file (removed document), considered outdated
84-
src_file = self.env.doc2path(docname)
85-
if not os.path.exists(src_file):
82+
src_file = Path(self.env.doc2path(docname))
83+
if not src_file.is_file():
8684
return True
8785

8886
# check if the hashes do not match; if not, this document is outdated
@@ -173,23 +171,23 @@ def load_cache(self):
173171
"""
174172

175173
try:
176-
with open(self._cache_cfg_file, encoding='utf-8') as f:
174+
with self._cache_cfg_file.open(encoding='utf-8') as f:
177175
self._cached_hash = json.load(f).get('hash')
178176
except FileNotFoundError:
179177
pass
180178
except OSError as e:
181179
self.builder.warn('failed to load cache (config): ' + e)
182180

183181
try:
184-
with open(self._cache_hash_file, encoding='utf-8') as f:
182+
with self._cache_hash_file.open(encoding='utf-8') as f:
185183
self._cached_dochash = json.load(f)
186184
except FileNotFoundError:
187185
pass
188186
except OSError as e:
189187
self.builder.warn('failed to load cache (hashes): ' + e)
190188

191189
try:
192-
with open(self._cache_publish_file, encoding='utf-8') as f:
190+
with self._cache_publish_file.open(encoding='utf-8') as f:
193191
self._cached_pids = json.load(f)
194192
except FileNotFoundError:
195193
pass
@@ -213,19 +211,19 @@ def save_cache(self):
213211
new_dochashs.update(self._active_dochash)
214212

215213
try:
216-
with open(self._cache_cfg_file, 'w', encoding='utf-8') as f:
214+
with self._cache_cfg_file.open('w', encoding='utf-8') as f:
217215
json.dump(new_cfg, f)
218216
except OSError as e:
219217
self.builder.warn('failed to save cache (config): ' + e)
220218

221219
try:
222-
with open(self._cache_hash_file, 'w', encoding='utf-8') as f:
220+
with self._cache_hash_file.open('w', encoding='utf-8') as f:
223221
json.dump(new_dochashs, f)
224222
except OSError as e:
225223
self.builder.warn('failed to save cache (hashes): ' + e)
226224

227225
try:
228-
with open(self._cache_publish_file, 'w', encoding='utf-8') as f:
226+
with self._cache_publish_file.open('w', encoding='utf-8') as f:
229227
json.dump(self._active_pids, f)
230228
except OSError as e:
231229
self.builder.warn('failed to save cache (pids): ' + e)

sphinxcontrib/confluencebuilder/intersphinx.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
# Copyright Sphinx Confluence Builder Contributors (AUTHORS)
33
# Copyright 2007-2020 by the Sphinx team (sphinx-doc/sphinx#AUTHORS)
44

5-
from os import path
65
from sphinxcontrib.confluencebuilder.logger import ConfluenceLogger as logger
76
import re
87
import requests
@@ -32,7 +31,8 @@ def escape(string):
3231
else:
3332
pages_part = 'pages/viewpage.action?pageId={}'
3433

35-
with open(path.join(builder.outdir, INVENTORY_FILENAME), 'wb') as f:
34+
inventory_db = builder.out_dir / INVENTORY_FILENAME
35+
with inventory_db.open('wb') as f:
3636
# header
3737
f.write((
3838
'# Sphinx inventory version 2\n'

sphinxcontrib/confluencebuilder/svg.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,10 @@
33

44
from hashlib import sha256
55
from sphinx.util.images import guess_mimetype
6-
from sphinx.util.osutil import ensuredir
76
from sphinxcontrib.confluencebuilder.logger import ConfluenceLogger as logger
87
from sphinxcontrib.confluencebuilder.util import convert_length
98
from sphinxcontrib.confluencebuilder.util import extract_length
109
from sphinxcontrib.confluencebuilder.util import find_env_abspath
11-
import os
1210
import xml.etree.ElementTree as xml_et
1311

1412

@@ -194,23 +192,23 @@ def confluence_supported_svg(builder, node):
194192
return
195193

196194
fname = sha256(svg_data).hexdigest() + '.svg'
197-
outfn = os.path.join(builder.outdir, builder.imagedir, 'svgs', fname)
195+
out_file = builder.out_dir / builder.imagedir / 'svgs' / fname
198196

199197
# write the new svg file (if needed)
200-
if not os.path.isfile(outfn):
198+
if not out_file.is_file():
201199
logger.verbose('generating compatible svg of: %s' % uri)
202-
logger.verbose('generating compatible svg to: %s' % outfn)
200+
logger.verbose(f'generating compatible svg to: {out_file}')
203201

204-
ensuredir(os.path.dirname(outfn))
202+
out_file.parent.mkdir(parents=True, exist_ok=True)
205203
try:
206-
with open(outfn, 'wb') as f:
204+
with out_file.open('wb') as f:
207205
f.write(svg_data)
208206
except (IOError, OSError) as err:
209207
builder.warn('error writing svg: %s' % err)
210208
return
211209

212210
# replace the required node attributes
213-
node['uri'] = outfn
211+
node['uri'] = str(out_file)
214212

215213
if 'height' in node:
216214
del node['height']

sphinxcontrib/confluencebuilder/transmute/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
# Copyright Sphinx Confluence Builder Contributors (AUTHORS)
33

44
from docutils import nodes
5-
from os import path
65
from sphinx.util.math import wrap_displaymath
76
from sphinxcontrib.confluencebuilder.compat import docutils_findall as findall
87
from sphinxcontrib.confluencebuilder.logger import ConfluenceLogger
@@ -136,7 +135,7 @@ def __init__(self, builder):
136135

137136
new_node = nodes.image(
138137
candidates={'?'},
139-
uri=path.join(builder.outdir, mf),
138+
uri=str(builder.out_dir / mf),
140139
**node.attributes)
141140

142141
if depth is not None:

tests/__main__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
# SPDX-License-Identifier: BSD-2-Clause
22
# Copyright Sphinx Confluence Builder Contributors (AUTHORS)
33

4+
from pathlib import Path
45
from tests.lib import enable_sphinx_info
56
import argparse
67
import fnmatch
7-
import os
88
import sys
99
import unittest
1010

@@ -50,8 +50,8 @@ def main():
5050
unittest.TestCase.shortDescription = lambda _: None
5151

5252
# discover unit tests
53-
test_base = os.path.dirname(os.path.realpath(__file__))
54-
unit_tests_dir = os.path.join(test_base, 'unit-tests')
53+
test_base = Path(__file__).parent.resolve()
54+
unit_tests_dir = test_base / 'unit-tests'
5555
unit_tests = loader.discover(unit_tests_dir)
5656

5757
# check if a unit test name was provided

tests/lib/__init__.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from contextlib import contextmanager
55
from contextlib import suppress
66
from copy import deepcopy
7+
from pathlib import Path
78
from sphinx.application import Sphinx
89
from sphinx.util.console import color_terminal
910
from sphinx.util.console import nocolor
@@ -510,13 +511,14 @@ def prepare_dirs(container=None, postfix=None):
510511
while frame and not frame.f_code.co_name.startswith('test_'):
511512
frame = frame.f_back
512513
container = frame.f_code.co_name if frame else 'unknown'
513-
lib_dir = os.path.dirname(os.path.realpath(__file__))
514-
test_dir = os.path.join(lib_dir, os.pardir)
515-
base_dir = os.path.join(test_dir, os.pardir)
516-
output_dir = os.path.join(base_dir, 'output')
517-
container_dir = os.path.abspath(os.path.join(output_dir, container))
514+
515+
lib_dir = Path(__file__).parent.resolve()
516+
test_dir = lib_dir.parent
517+
base_dir = test_dir.parent
518+
output_dir = base_dir / 'output'
519+
container_dir = output_dir / container
518520
if postfix:
519-
container_dir += postfix
521+
container_dir = container_dir.parent / (container_dir.name + postfix)
520522

521523
shutil.rmtree(container_dir, ignore_errors=True)
522524

@@ -551,7 +553,7 @@ def prepare_sphinx(src_dir, config=None, out_dir=None, extra_config=None,
551553
conf = dict(config) if config else {}
552554
if extra_config:
553555
conf.update(extra_config)
554-
conf_dir = src_dir if config is None else None
556+
conf_dir = str(src_dir) if config is None else None
555557
warnerr = not relax
556558

557559
sts = None
@@ -570,14 +572,14 @@ def prepare_sphinx(src_dir, config=None, out_dir=None, extra_config=None,
570572
if not out_dir:
571573
out_dir = prepare_dirs()
572574

573-
doctrees_dir = os.path.join(out_dir, '.doctrees')
575+
doctrees_dir = out_dir / '.doctrees'
574576

575577
with docutils_namespace():
576578
app = Sphinx(
577-
src_dir, # output for document sources
579+
str(src_dir), # output for document sources
578580
conf_dir, # configuration directory
579-
out_dir, # output for generated documents
580-
doctrees_dir, # output for doctree files
581+
str(out_dir), # output for generated documents
582+
str(doctrees_dir), # output for doctree files
581583
builder, # builder to execute
582584
confoverrides=conf, # load provided configuration (volatile)
583585
status=sts, # status output
@@ -617,7 +619,7 @@ def prepare_sphinx_filenames(src_dir, filenames, configs=None):
617619
"""
618620
files = []
619621
for filename in filenames:
620-
files.append(os.path.join(src_dir, filename + '.rst'))
622+
files.append(str(src_dir / (filename + '.rst')))
621623

622624
if configs:
623625
root_doc = 'index'

0 commit comments

Comments
 (0)