Prefer `contextlib.chdir to sphinx.util.osutil.cd`

This commit is contained in:
Adam Turner
2023-03-05 15:25:47 +00:00
parent 219d71315c
commit f435fc05e6
8 changed files with 67 additions and 21 deletions

View File

@@ -22,6 +22,11 @@ The following is a list of deprecated interfaces.
- Removed
- Alternatives
* - ``sphinx.util.osutil.cd``
- 6.1
- 8.0
- ``contextlib.chdir``
* - ``sphinx.util.save_traceback``
- 6.1
- 8.0

View File

@@ -17,7 +17,12 @@ from os import path
import sphinx
from sphinx.cmd.build import build_main
from sphinx.util.console import blue, bold, color_terminal, nocolor # type: ignore
from sphinx.util.osutil import cd, rmtree
from sphinx.util.osutil import rmtree
try:
from contextlib import chdir # type: ignore[attr-defined]
except ImportError:
from sphinx.util.osutil import _chdir as chdir
BUILDERS = [
("", "html", "to make standalone HTML files"),
@@ -96,7 +101,7 @@ class Make:
else:
makecmd = self.makecmd
try:
with cd(self.builddir_join('latex')):
with chdir(self.builddir_join('latex')):
return subprocess.call([makecmd, 'all-pdf'])
except OSError:
print('Error: Failed to run: %s' % makecmd)
@@ -111,7 +116,7 @@ class Make:
else:
makecmd = self.makecmd
try:
with cd(self.builddir_join('latex')):
with chdir(self.builddir_join('latex')):
return subprocess.call([makecmd, 'all-pdf'])
except OSError:
print('Error: Failed to run: %s' % makecmd)
@@ -121,7 +126,7 @@ class Make:
if self.run_generic_build('texinfo') > 0:
return 1
try:
with cd(self.builddir_join('texinfo')):
with chdir(self.builddir_join('texinfo')):
return subprocess.call([self.makecmd, 'info'])
except OSError:
print('Error: Failed to run: %s' % self.makecmd)

View File

@@ -13,10 +13,15 @@ from sphinx.errors import ConfigError, ExtensionError
from sphinx.locale import _, __
from sphinx.util import logging
from sphinx.util.i18n import format_date
from sphinx.util.osutil import cd, fs_encoding
from sphinx.util.osutil import fs_encoding
from sphinx.util.tags import Tags
from sphinx.util.typing import NoneType
try:
from contextlib import chdir # type: ignore[attr-defined]
except ImportError:
from sphinx.util.osutil import _chdir as chdir
if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.environment import BuildEnvironment
@@ -342,7 +347,7 @@ def eval_config_file(filename: str, tags: Tags | None) -> dict[str, Any]:
namespace['__file__'] = filename
namespace['tags'] = tags
with cd(path.dirname(filename)):
with chdir(path.dirname(filename)):
# during executing config file, current dir is changed to ``confdir``.
try:
with open(filename, 'rb') as f:

View File

@@ -11,7 +11,9 @@ import sys
import unicodedata
from io import StringIO
from os import path
from typing import Any, Generator, Iterator
from typing import Any, Iterator
from sphinx.deprecation import _deprecation_warning
try:
# for ALT Linux (#6712)
@@ -146,14 +148,26 @@ def abspath(pathdir: str) -> str:
return pathdir
class _chdir:
"""Remove this fall-back once support for Python 3.10 is removed."""
def __init__(self, target_dir: str, /):
self.path = target_dir
self._dirs: list[str] = []
def __enter__(self):
self._dirs.append(os.getcwd())
os.chdir(self.path)
def __exit__(self, _exc_type, _exc_value, _traceback, /):
os.chdir(self._dirs.pop())
@contextlib.contextmanager
def cd(target_dir: str) -> Generator[None, None, None]:
cwd = os.getcwd()
try:
os.chdir(target_dir)
def cd(target_dir: str) -> Iterator[None]:
if sys.version_info[:2] >= (3, 11):
_deprecation_warning(__name__, 'cd', 'contextlib.chdir', remove=(8, 0))
with _chdir(target_dir):
yield
finally:
os.chdir(cwd)
class FileAvoidWrite:

View File

@@ -9,7 +9,11 @@ from subprocess import CalledProcessError
import pytest
from sphinx.builders.gettext import Catalog, MsgOrigin
from sphinx.util.osutil import cd
try:
from contextlib import chdir
except ImportError:
from sphinx.util.osutil import _chdir as chdir
def test_Catalog_duplicated_message():
@@ -51,7 +55,7 @@ def test_build_gettext(app):
def test_msgfmt(app):
app.builder.build_all()
(app.outdir / 'en' / 'LC_MESSAGES').makedirs()
with cd(app.outdir):
with chdir(app.outdir):
try:
args = ['msginit', '--no-translator', '-i', 'markup.pot', '--locale', 'en_US']
subprocess.run(args, capture_output=True, check=True)

View File

@@ -14,11 +14,16 @@ from sphinx.builders.latex import default_latex_documents
from sphinx.config import Config
from sphinx.errors import SphinxError
from sphinx.testing.util import strip_escseq
from sphinx.util.osutil import cd, ensuredir
from sphinx.util.osutil import ensuredir
from sphinx.writers.latex import LaTeXTranslator
from .test_build_html import ENV_WARNINGS
try:
from contextlib import chdir
except ImportError:
from sphinx.util.osutil import _chdir as chdir
LATEX_ENGINES = ['pdflatex', 'lualatex', 'xelatex']
DOCCLASSES = ['howto', 'manual']
STYLEFILES = ['article.cls', 'fancyhdr.sty', 'titlesec.sty', 'amsmath.sty',
@@ -47,7 +52,7 @@ def kpsetest(*filenames):
def compile_latex_document(app, filename='python.tex'):
# now, try to run latex over it
try:
with cd(app.outdir):
with chdir(app.outdir):
ensuredir(app.config.latex_engine)
# keep a copy of latex file for this engine in case test fails
copyfile(filename, app.config.latex_engine + '/' + filename)

View File

@@ -23,7 +23,11 @@ from sphinx.ext.autosummary.generate import (
from sphinx.ext.autosummary.generate import main as autogen_main
from sphinx.testing.util import assert_node, etree_parse
from sphinx.util.docutils import new_document
from sphinx.util.osutil import cd
try:
from contextlib import chdir
except ImportError:
from sphinx.util.osutil import _chdir as chdir
html_warnfile = StringIO()
@@ -589,7 +593,7 @@ def test_invalid_autosummary_generate(app, status, warning):
def test_autogen(rootdir, tempdir):
with cd(rootdir / 'test-templating'):
with chdir(rootdir / 'test-templating'):
args = ['-o', tempdir, '-t', '.', 'autosummary_templating.txt']
autogen_main(args)
assert (tempdir / 'sphinx.application.TemplateBridge.rst').exists()

View File

@@ -9,7 +9,11 @@ from textwrap import dedent
import pytest
import sphinx
from sphinx.util.osutil import cd
try:
from contextlib import chdir
except ImportError:
from sphinx.util.osutil import _chdir as chdir
@pytest.fixture()
@@ -24,7 +28,7 @@ def setup_command(request, tempdir, rootdir):
pkgrootdir = tempdir / 'test-setup'
(rootdir / 'test-setup').copytree(pkgrootdir)
with cd(pkgrootdir):
with chdir(pkgrootdir):
pythonpath = os.path.dirname(os.path.dirname(sphinx.__file__))
if os.getenv('PYTHONPATH'):
pythonpath = os.getenv('PYTHONPATH') + os.pathsep + pythonpath