diff options
Diffstat (limited to 'sphinx/util/osutil.py')
-rw-r--r-- | sphinx/util/osutil.py | 38 |
1 files changed, 33 insertions, 5 deletions
diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py index 6368384e8..299f2d272 100644 --- a/sphinx/util/osutil.py +++ b/sphinx/util/osutil.py @@ -21,8 +21,11 @@ import filecmp from os import path import contextlib from io import BytesIO, StringIO +from six import PY2, PY3, text_type -from six import PY2, text_type +if False: + # For type annotation + from typing import Any, Iterator, List, Tuple, Union # NOQA # Errnos that we need. EEXIST = getattr(errno, 'EEXIST', 0) @@ -30,6 +33,9 @@ ENOENT = getattr(errno, 'ENOENT', 0) EPIPE = getattr(errno, 'EPIPE', 0) EINVAL = getattr(errno, 'EINVAL', 0) +if PY3: + unicode = str # special alias for static typing... + # SEP separates path elements in the canonical file names # # Define SEP as a manifest constant, not so much because we expect it to change @@ -39,15 +45,18 @@ SEP = "/" def os_path(canonicalpath): + # type: (unicode) -> unicode return canonicalpath.replace(SEP, path.sep) def canon_path(nativepath): + # type: (unicode) -> unicode """Return path in OS-independent form""" return nativepath.replace(path.sep, SEP) def relative_uri(base, to): + # type: (unicode, unicode) -> unicode """Return a relative URL from ``base`` to ``to``.""" if to.startswith(SEP): return to @@ -71,6 +80,7 @@ def relative_uri(base, to): def ensuredir(path): + # type: (unicode) -> None """Ensure that a path exists.""" try: os.makedirs(path) @@ -84,6 +94,7 @@ def ensuredir(path): # that check UnicodeError. # The customization obstacle to replace the function with the os.walk. def walk(top, topdown=True, followlinks=False): + # type: (unicode, bool, bool) -> Iterator[Tuple[unicode, List[unicode], List[unicode]]] """Backport of os.walk from 2.6, where the *followlinks* argument was added. """ @@ -115,6 +126,7 @@ def walk(top, topdown=True, followlinks=False): def mtimes_of_files(dirnames, suffix): + # type: (List[unicode], unicode) -> Iterator[float] for dirname in dirnames: for root, dirs, files in os.walk(dirname): for sfile in files: @@ -126,6 +138,7 @@ def mtimes_of_files(dirnames, suffix): def movefile(source, dest): + # type: (unicode, unicode) -> None """Move a file, removing the destination if it exists.""" if os.path.exists(dest): try: @@ -136,6 +149,7 @@ def movefile(source, dest): def copytimes(source, dest): + # type: (unicode, unicode) -> None """Copy a file's modification times.""" st = os.stat(source) if hasattr(os, 'utime'): @@ -143,6 +157,7 @@ def copytimes(source, dest): def copyfile(source, dest): + # type: (unicode, unicode) -> None """Copy a file and its modification times, if possible. Note: ``copyfile`` skips copying if the file has not been changed""" @@ -159,10 +174,12 @@ no_fn_re = re.compile(r'[^a-zA-Z0-9_-]') def make_filename(string): + # type: (str) -> unicode return no_fn_re.sub('', string) or 'sphinx' def ustrftime(format, *args): + # type: (unicode, Any) -> unicode # [DEPRECATED] strftime for unicode strings # It will be removed at Sphinx-1.5 if not args: @@ -171,7 +188,7 @@ def ustrftime(format, *args): source_date_epoch = os.getenv('SOURCE_DATE_EPOCH') if source_date_epoch is not None: time_struct = time.gmtime(float(source_date_epoch)) - args = [time_struct] + args = [time_struct] # type: ignore if PY2: # if a locale is set, the time strings are encoded in the encoding # given by LC_TIME; if that is available, use it @@ -188,16 +205,18 @@ def ustrftime(format, *args): def safe_relpath(path, start=None): + # type: (unicode, unicode) -> unicode try: return os.path.relpath(path, start) except ValueError: return path -fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() +fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() # type: unicode def abspath(pathdir): + # type: (unicode) -> unicode pathdir = path.abspath(pathdir) if isinstance(pathdir, bytes): pathdir = pathdir.decode(fs_encoding) @@ -205,6 +224,7 @@ def abspath(pathdir): def getcwd(): + # type: () -> unicode if hasattr(os, 'getcwdu'): return os.getcwdu() return os.getcwd() @@ -212,6 +232,7 @@ def getcwd(): @contextlib.contextmanager def cd(target_dir): + # type: (unicode) -> Iterator[None] cwd = getcwd() try: os.chdir(target_dir) @@ -233,19 +254,22 @@ class FileAvoidWrite(object): Objects can be used as context managers. """ def __init__(self, path): + # type: (unicode) -> None self._path = path - self._io = None + self._io = None # type: Union[StringIO, BytesIO] def write(self, data): + # type: (Union[str, unicode]) -> None if not self._io: if isinstance(data, text_type): self._io = StringIO() else: self._io = BytesIO() - self._io.write(data) + self._io.write(data) # type: ignore def close(self): + # type: () -> None """Stop accepting writes and write file, if needed.""" if not self._io: raise Exception('FileAvoidWrite does not support empty files.') @@ -273,12 +297,15 @@ class FileAvoidWrite(object): f.write(buf) def __enter__(self): + # type: () -> FileAvoidWrite return self def __exit__(self, type, value, traceback): + # type: (unicode, unicode, unicode) -> None self.close() def __getattr__(self, name): + # type: (str) -> Any # Proxy to _io instance. if not self._io: raise Exception('Must write to FileAvoidWrite before other ' @@ -288,6 +315,7 @@ class FileAvoidWrite(object): def rmtree(path): + # type: (unicode) -> None if os.path.isdir(path): shutil.rmtree(path) else: |