diff options
| author | Adam Turner <9087854+aa-turner@users.noreply.github.com> | 2023-03-05 15:25:47 +0000 |
|---|---|---|
| committer | Adam Turner <9087854+aa-turner@users.noreply.github.com> | 2023-03-05 18:49:17 +0000 |
| commit | f435fc05e68654a0cb1f36aecaf5100fcf171ee8 (patch) | |
| tree | 4eb4a96a94df16296e81ca091e0ebc7cd85c8d12 | |
| parent | 219d71315cd59685f4f99c8def4e8f692611e6c8 (diff) | |
| download | sphinx-git-f435fc05e68654a0cb1f36aecaf5100fcf171ee8.tar.gz | |
Prefer ``contextlib.chdir`` to ``sphinx.util.osutil.cd``
| -rw-r--r-- | doc/extdev/deprecated.rst | 5 | ||||
| -rw-r--r-- | sphinx/cmd/make_mode.py | 13 | ||||
| -rw-r--r-- | sphinx/config.py | 9 | ||||
| -rw-r--r-- | sphinx/util/osutil.py | 28 | ||||
| -rw-r--r-- | tests/test_build_gettext.py | 8 | ||||
| -rw-r--r-- | tests/test_build_latex.py | 9 | ||||
| -rw-r--r-- | tests/test_ext_autosummary.py | 8 | ||||
| -rw-r--r-- | tests/test_setup_command.py | 8 |
8 files changed, 67 insertions, 21 deletions
diff --git a/doc/extdev/deprecated.rst b/doc/extdev/deprecated.rst index 8d4667beb..61cfbe317 100644 --- a/doc/extdev/deprecated.rst +++ b/doc/extdev/deprecated.rst @@ -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 diff --git a/sphinx/cmd/make_mode.py b/sphinx/cmd/make_mode.py index 6624903f9..cceca85c2 100644 --- a/sphinx/cmd/make_mode.py +++ b/sphinx/cmd/make_mode.py @@ -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) diff --git a/sphinx/config.py b/sphinx/config.py index 9cfbedb39..94f605dcb 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -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: diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py index 15f5b408a..0ba1a6862 100644 --- a/sphinx/util/osutil.py +++ b/sphinx/util/osutil.py @@ -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: diff --git a/tests/test_build_gettext.py b/tests/test_build_gettext.py index a4551ad53..ebd46275a 100644 --- a/tests/test_build_gettext.py +++ b/tests/test_build_gettext.py @@ -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) diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py index 5e254d6bf..e97f8da38 100644 --- a/tests/test_build_latex.py +++ b/tests/test_build_latex.py @@ -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) diff --git a/tests/test_ext_autosummary.py b/tests/test_ext_autosummary.py index 200661dfe..f8c2de495 100644 --- a/tests/test_ext_autosummary.py +++ b/tests/test_ext_autosummary.py @@ -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() diff --git a/tests/test_setup_command.py b/tests/test_setup_command.py index 3690bbfcc..897718874 100644 --- a/tests/test_setup_command.py +++ b/tests/test_setup_command.py @@ -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 |
