mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
Migrate to py3 style type annotation: sphinx.util.osutil
This commit is contained in:
parent
17e26bf29f
commit
a3c9edfbe6
@ -19,14 +19,11 @@ import time
|
|||||||
import warnings
|
import warnings
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
from os import path
|
from os import path
|
||||||
|
from typing import Any, Generator, Iterator, List, Tuple, Type
|
||||||
|
|
||||||
from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
|
from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
|
||||||
from sphinx.testing.path import path as Path
|
from sphinx.testing.path import path as Path
|
||||||
|
|
||||||
if False:
|
|
||||||
# For type annotation
|
|
||||||
from typing import Any, Iterator, List, Tuple # NOQA
|
|
||||||
|
|
||||||
# Errnos that we need.
|
# Errnos that we need.
|
||||||
EEXIST = getattr(errno, 'EEXIST', 0) # RemovedInSphinx40Warning
|
EEXIST = getattr(errno, 'EEXIST', 0) # RemovedInSphinx40Warning
|
||||||
ENOENT = getattr(errno, 'ENOENT', 0) # RemovedInSphinx40Warning
|
ENOENT = getattr(errno, 'ENOENT', 0) # RemovedInSphinx40Warning
|
||||||
@ -41,19 +38,16 @@ EINVAL = getattr(errno, 'EINVAL', 0) # RemovedInSphinx40Warning
|
|||||||
SEP = "/"
|
SEP = "/"
|
||||||
|
|
||||||
|
|
||||||
def os_path(canonicalpath):
|
def os_path(canonicalpath: str) -> str:
|
||||||
# type: (str) -> str
|
|
||||||
return canonicalpath.replace(SEP, path.sep)
|
return canonicalpath.replace(SEP, path.sep)
|
||||||
|
|
||||||
|
|
||||||
def canon_path(nativepath):
|
def canon_path(nativepath: str) -> str:
|
||||||
# type: (str) -> str
|
|
||||||
"""Return path in OS-independent form"""
|
"""Return path in OS-independent form"""
|
||||||
return nativepath.replace(path.sep, SEP)
|
return nativepath.replace(path.sep, SEP)
|
||||||
|
|
||||||
|
|
||||||
def relative_uri(base, to):
|
def relative_uri(base: str, to: str) -> str:
|
||||||
# type: (str, str) -> str
|
|
||||||
"""Return a relative URL from ``base`` to ``to``."""
|
"""Return a relative URL from ``base`` to ``to``."""
|
||||||
if to.startswith(SEP):
|
if to.startswith(SEP):
|
||||||
return to
|
return to
|
||||||
@ -76,22 +70,19 @@ def relative_uri(base, to):
|
|||||||
return ('..' + SEP) * (len(b2) - 1) + SEP.join(t2)
|
return ('..' + SEP) * (len(b2) - 1) + SEP.join(t2)
|
||||||
|
|
||||||
|
|
||||||
def ensuredir(path):
|
def ensuredir(path: str) -> None:
|
||||||
# type: (str) -> None
|
|
||||||
"""Ensure that a path exists."""
|
"""Ensure that a path exists."""
|
||||||
os.makedirs(path, exist_ok=True)
|
os.makedirs(path, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
def walk(top, topdown=True, followlinks=False):
|
def walk(top: str, topdown: bool = True, followlinks: bool = False) -> Iterator[Tuple[str, List[str], List[str]]]: # NOQA
|
||||||
# type: (str, bool, bool) -> Iterator[Tuple[str, List[str], List[str]]]
|
|
||||||
warnings.warn('sphinx.util.osutil.walk() is deprecated for removal. '
|
warnings.warn('sphinx.util.osutil.walk() is deprecated for removal. '
|
||||||
'Please use os.walk() instead.',
|
'Please use os.walk() instead.',
|
||||||
RemovedInSphinx40Warning)
|
RemovedInSphinx40Warning)
|
||||||
return os.walk(top, topdown=topdown, followlinks=followlinks)
|
return os.walk(top, topdown=topdown, followlinks=followlinks)
|
||||||
|
|
||||||
|
|
||||||
def mtimes_of_files(dirnames, suffix):
|
def mtimes_of_files(dirnames: List[str], suffix: str) -> Iterator[float]:
|
||||||
# type: (List[str], str) -> Iterator[float]
|
|
||||||
for dirname in dirnames:
|
for dirname in dirnames:
|
||||||
for root, dirs, files in os.walk(dirname):
|
for root, dirs, files in os.walk(dirname):
|
||||||
for sfile in files:
|
for sfile in files:
|
||||||
@ -102,8 +93,7 @@ def mtimes_of_files(dirnames, suffix):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def movefile(source, dest):
|
def movefile(source: str, dest: str) -> None:
|
||||||
# type: (str, str) -> None
|
|
||||||
"""Move a file, removing the destination if it exists."""
|
"""Move a file, removing the destination if it exists."""
|
||||||
if os.path.exists(dest):
|
if os.path.exists(dest):
|
||||||
try:
|
try:
|
||||||
@ -113,16 +103,14 @@ def movefile(source, dest):
|
|||||||
os.rename(source, dest)
|
os.rename(source, dest)
|
||||||
|
|
||||||
|
|
||||||
def copytimes(source, dest):
|
def copytimes(source: str, dest: str) -> None:
|
||||||
# type: (str, str) -> None
|
|
||||||
"""Copy a file's modification times."""
|
"""Copy a file's modification times."""
|
||||||
st = os.stat(source)
|
st = os.stat(source)
|
||||||
if hasattr(os, 'utime'):
|
if hasattr(os, 'utime'):
|
||||||
os.utime(dest, (st.st_atime, st.st_mtime))
|
os.utime(dest, (st.st_atime, st.st_mtime))
|
||||||
|
|
||||||
|
|
||||||
def copyfile(source, dest):
|
def copyfile(source: str, dest: str) -> None:
|
||||||
# type: (str, str) -> None
|
|
||||||
"""Copy a file and its modification times, if possible.
|
"""Copy a file and its modification times, if possible.
|
||||||
|
|
||||||
Note: ``copyfile`` skips copying if the file has not been changed"""
|
Note: ``copyfile`` skips copying if the file has not been changed"""
|
||||||
@ -139,18 +127,15 @@ no_fn_re = re.compile(r'[^a-zA-Z0-9_-]')
|
|||||||
project_suffix_re = re.compile(' Documentation$')
|
project_suffix_re = re.compile(' Documentation$')
|
||||||
|
|
||||||
|
|
||||||
def make_filename(string):
|
def make_filename(string: str) -> str:
|
||||||
# type: (str) -> str
|
|
||||||
return no_fn_re.sub('', string) or 'sphinx'
|
return no_fn_re.sub('', string) or 'sphinx'
|
||||||
|
|
||||||
|
|
||||||
def make_filename_from_project(project):
|
def make_filename_from_project(project: str) -> str:
|
||||||
# type: (str) -> str
|
|
||||||
return make_filename(project_suffix_re.sub('', project)).lower()
|
return make_filename(project_suffix_re.sub('', project)).lower()
|
||||||
|
|
||||||
|
|
||||||
def ustrftime(format, *args):
|
def ustrftime(format: str, *args) -> str:
|
||||||
# type: (str, Any) -> str
|
|
||||||
"""[DEPRECATED] strftime for unicode strings."""
|
"""[DEPRECATED] strftime for unicode strings."""
|
||||||
warnings.warn('sphinx.util.osutil.ustrtime is deprecated for removal',
|
warnings.warn('sphinx.util.osutil.ustrtime is deprecated for removal',
|
||||||
RemovedInSphinx30Warning, stacklevel=2)
|
RemovedInSphinx30Warning, stacklevel=2)
|
||||||
@ -171,8 +156,7 @@ def ustrftime(format, *args):
|
|||||||
return r.encode().decode('unicode-escape')
|
return r.encode().decode('unicode-escape')
|
||||||
|
|
||||||
|
|
||||||
def relpath(path, start=os.curdir):
|
def relpath(path: str, start: str = os.curdir) -> str:
|
||||||
# type: (str, str) -> str
|
|
||||||
"""Return a relative filepath to *path* either from the current directory or
|
"""Return a relative filepath to *path* either from the current directory or
|
||||||
from an optional *start* directory.
|
from an optional *start* directory.
|
||||||
|
|
||||||
@ -189,8 +173,7 @@ safe_relpath = relpath # for compatibility
|
|||||||
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
|
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
|
||||||
|
|
||||||
|
|
||||||
def abspath(pathdir):
|
def abspath(pathdir: str) -> str:
|
||||||
# type: (str) -> str
|
|
||||||
if isinstance(pathdir, Path):
|
if isinstance(pathdir, Path):
|
||||||
return pathdir.abspath()
|
return pathdir.abspath()
|
||||||
else:
|
else:
|
||||||
@ -205,8 +188,7 @@ def abspath(pathdir):
|
|||||||
return pathdir
|
return pathdir
|
||||||
|
|
||||||
|
|
||||||
def getcwd():
|
def getcwd() -> str:
|
||||||
# type: () -> str
|
|
||||||
warnings.warn('sphinx.util.osutil.getcwd() is deprecated. '
|
warnings.warn('sphinx.util.osutil.getcwd() is deprecated. '
|
||||||
'Please use os.getcwd() instead.',
|
'Please use os.getcwd() instead.',
|
||||||
RemovedInSphinx40Warning)
|
RemovedInSphinx40Warning)
|
||||||
@ -214,8 +196,7 @@ def getcwd():
|
|||||||
|
|
||||||
|
|
||||||
@contextlib.contextmanager
|
@contextlib.contextmanager
|
||||||
def cd(target_dir):
|
def cd(target_dir: str) -> Generator[None, None, None]:
|
||||||
# type: (str) -> Iterator[None]
|
|
||||||
cwd = os.getcwd()
|
cwd = os.getcwd()
|
||||||
try:
|
try:
|
||||||
os.chdir(target_dir)
|
os.chdir(target_dir)
|
||||||
@ -236,19 +217,16 @@ class FileAvoidWrite:
|
|||||||
|
|
||||||
Objects can be used as context managers.
|
Objects can be used as context managers.
|
||||||
"""
|
"""
|
||||||
def __init__(self, path):
|
def __init__(self, path: str) -> None:
|
||||||
# type: (str) -> None
|
|
||||||
self._path = path
|
self._path = path
|
||||||
self._io = None # type: StringIO
|
self._io = None # type: StringIO
|
||||||
|
|
||||||
def write(self, data):
|
def write(self, data: str) -> None:
|
||||||
# type: (str) -> None
|
|
||||||
if not self._io:
|
if not self._io:
|
||||||
self._io = StringIO()
|
self._io = StringIO()
|
||||||
self._io.write(data)
|
self._io.write(data)
|
||||||
|
|
||||||
def close(self):
|
def close(self) -> None:
|
||||||
# type: () -> None
|
|
||||||
"""Stop accepting writes and write file, if needed."""
|
"""Stop accepting writes and write file, if needed."""
|
||||||
if not self._io:
|
if not self._io:
|
||||||
raise Exception('FileAvoidWrite does not support empty files.')
|
raise Exception('FileAvoidWrite does not support empty files.')
|
||||||
@ -267,16 +245,14 @@ class FileAvoidWrite:
|
|||||||
with open(self._path, 'w') as f:
|
with open(self._path, 'w') as f:
|
||||||
f.write(buf)
|
f.write(buf)
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self) -> "FileAvoidWrite":
|
||||||
# type: () -> FileAvoidWrite
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __exit__(self, type, value, traceback):
|
def __exit__(self, exc_type: Type[Exception], exc_value: Exception, traceback: Any) -> bool: # NOQA
|
||||||
# type: (str, str, str) -> None
|
|
||||||
self.close()
|
self.close()
|
||||||
|
return True
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name: str) -> Any:
|
||||||
# type: (str) -> Any
|
|
||||||
# Proxy to _io instance.
|
# Proxy to _io instance.
|
||||||
if not self._io:
|
if not self._io:
|
||||||
raise Exception('Must write to FileAvoidWrite before other '
|
raise Exception('Must write to FileAvoidWrite before other '
|
||||||
@ -285,8 +261,7 @@ class FileAvoidWrite:
|
|||||||
return getattr(self._io, name)
|
return getattr(self._io, name)
|
||||||
|
|
||||||
|
|
||||||
def rmtree(path):
|
def rmtree(path: str) -> None:
|
||||||
# type: (str) -> None
|
|
||||||
if os.path.isdir(path):
|
if os.path.isdir(path):
|
||||||
shutil.rmtree(path)
|
shutil.rmtree(path)
|
||||||
else:
|
else:
|
||||||
|
Loading…
Reference in New Issue
Block a user