2010-01-17 10:35:12 -06:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
2010-01-17 10:49:01 -06:00
|
|
|
sphinx.util.osutil
|
|
|
|
~~~~~~~~~~~~~~~~~~
|
2010-01-17 10:35:12 -06:00
|
|
|
|
|
|
|
Operating system-related utility functions for Sphinx.
|
|
|
|
|
2017-12-31 10:06:58 -06:00
|
|
|
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
|
2010-01-17 10:35:12 -06:00
|
|
|
:license: BSD, see LICENSE for details.
|
|
|
|
"""
|
2014-01-19 04:17:10 -06:00
|
|
|
from __future__ import print_function
|
2010-01-17 10:35:12 -06:00
|
|
|
|
2018-01-27 10:52:16 -06:00
|
|
|
import contextlib
|
|
|
|
import errno
|
|
|
|
import filecmp
|
2010-01-17 10:35:12 -06:00
|
|
|
import os
|
|
|
|
import re
|
2018-01-27 10:52:16 -06:00
|
|
|
import shutil
|
2010-07-28 11:43:40 -05:00
|
|
|
import sys
|
2010-01-17 10:35:12 -06:00
|
|
|
import time
|
2018-02-05 15:37:45 -06:00
|
|
|
import warnings
|
2015-06-02 12:00:12 -05:00
|
|
|
from io import BytesIO, StringIO
|
2018-01-27 10:52:16 -06:00
|
|
|
from os import path
|
|
|
|
|
2018-09-07 20:52:24 -05:00
|
|
|
from six import text_type
|
2014-04-28 21:46:47 -05:00
|
|
|
|
2018-09-08 15:02:24 -05:00
|
|
|
from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning
|
2018-02-05 15:37:45 -06:00
|
|
|
|
2018-03-13 09:01:11 -05:00
|
|
|
if False:
|
|
|
|
# For type annotation
|
2017-03-02 21:19:09 -06:00
|
|
|
from typing import Any, Iterator, List, Tuple, Union # NOQA
|
2018-11-24 05:14:43 -06:00
|
|
|
from sphinx.util.typing import unicode # NOQA
|
2016-11-08 20:45:12 -06:00
|
|
|
|
2010-01-17 10:35:12 -06:00
|
|
|
# Errnos that we need.
|
|
|
|
EEXIST = getattr(errno, 'EEXIST', 0)
|
|
|
|
ENOENT = getattr(errno, 'ENOENT', 0)
|
2017-01-11 19:09:44 -06:00
|
|
|
EPIPE = getattr(errno, 'EPIPE', 0)
|
2011-07-14 09:57:01 -05:00
|
|
|
EINVAL = getattr(errno, 'EINVAL', 0)
|
2010-01-17 10:35:12 -06:00
|
|
|
|
|
|
|
# SEP separates path elements in the canonical file names
|
|
|
|
#
|
|
|
|
# Define SEP as a manifest constant, not so much because we expect it to change
|
|
|
|
# in the future as to avoid the suspicion that a stray "/" in the code is a
|
|
|
|
# hangover from more *nix-oriented origins.
|
|
|
|
SEP = "/"
|
|
|
|
|
2015-03-08 10:55:34 -05:00
|
|
|
|
2010-01-17 10:35:12 -06:00
|
|
|
def os_path(canonicalpath):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode) -> unicode
|
2010-01-17 10:35:12 -06:00
|
|
|
return canonicalpath.replace(SEP, path.sep)
|
|
|
|
|
|
|
|
|
2015-10-10 08:40:59 -05:00
|
|
|
def canon_path(nativepath):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode) -> unicode
|
2015-10-10 08:40:59 -05:00
|
|
|
"""Return path in OS-independent form"""
|
|
|
|
return nativepath.replace(path.sep, SEP)
|
2010-01-17 10:35:12 -06:00
|
|
|
|
|
|
|
|
|
|
|
def relative_uri(base, to):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode, unicode) -> unicode
|
2010-01-17 10:35:12 -06:00
|
|
|
"""Return a relative URL from ``base`` to ``to``."""
|
|
|
|
if to.startswith(SEP):
|
|
|
|
return to
|
|
|
|
b2 = base.split(SEP)
|
|
|
|
t2 = to.split(SEP)
|
2012-04-28 14:03:30 -05:00
|
|
|
# remove common segments (except the last segment)
|
|
|
|
for x, y in zip(b2[:-1], t2[:-1]):
|
2010-01-17 10:35:12 -06:00
|
|
|
if x != y:
|
|
|
|
break
|
|
|
|
b2.pop(0)
|
|
|
|
t2.pop(0)
|
2012-04-28 14:03:30 -05:00
|
|
|
if b2 == t2:
|
|
|
|
# Special case: relative_uri('f/index.html','f/index.html')
|
|
|
|
# returns '', not 'index.html'
|
|
|
|
return ''
|
|
|
|
if len(b2) == 1 and t2 == ['']:
|
2012-11-03 11:04:32 -05:00
|
|
|
# Special case: relative_uri('f/index.html','f/') should
|
2012-04-28 14:03:30 -05:00
|
|
|
# return './', not ''
|
2015-03-08 10:55:34 -05:00
|
|
|
return '.' + SEP
|
2017-01-11 19:07:05 -06:00
|
|
|
return ('..' + SEP) * (len(b2) - 1) + SEP.join(t2)
|
2010-01-17 10:35:12 -06:00
|
|
|
|
|
|
|
|
|
|
|
def ensuredir(path):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode) -> None
|
2010-01-17 10:35:12 -06:00
|
|
|
"""Ensure that a path exists."""
|
2018-12-12 10:33:14 -06:00
|
|
|
os.makedirs(path, exist_ok=True)
|
2010-01-17 10:35:12 -06:00
|
|
|
|
|
|
|
|
|
|
|
def walk(top, topdown=True, followlinks=False):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode, bool, bool) -> Iterator[Tuple[unicode, List[unicode], List[unicode]]]
|
2018-09-23 10:04:57 -05:00
|
|
|
warnings.warn('sphinx.util.osutil.walk() is deprecated for removal. '
|
|
|
|
'Please use os.walk() instead.',
|
|
|
|
RemovedInSphinx40Warning)
|
|
|
|
return os.walk(top, topdown=topdown, followlinks=followlinks)
|
2010-01-17 10:35:12 -06:00
|
|
|
|
|
|
|
|
|
|
|
def mtimes_of_files(dirnames, suffix):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (List[unicode], unicode) -> Iterator[float]
|
2010-01-17 10:35:12 -06:00
|
|
|
for dirname in dirnames:
|
|
|
|
for root, dirs, files in os.walk(dirname):
|
|
|
|
for sfile in files:
|
|
|
|
if sfile.endswith(suffix):
|
|
|
|
try:
|
|
|
|
yield path.getmtime(path.join(root, sfile))
|
|
|
|
except EnvironmentError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def movefile(source, dest):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode, unicode) -> None
|
2010-01-17 10:35:12 -06:00
|
|
|
"""Move a file, removing the destination if it exists."""
|
|
|
|
if os.path.exists(dest):
|
|
|
|
try:
|
|
|
|
os.unlink(dest)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
os.rename(source, dest)
|
|
|
|
|
|
|
|
|
|
|
|
def copytimes(source, dest):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode, unicode) -> None
|
2010-01-17 10:35:12 -06:00
|
|
|
"""Copy a file's modification times."""
|
|
|
|
st = os.stat(source)
|
|
|
|
if hasattr(os, 'utime'):
|
|
|
|
os.utime(dest, (st.st_atime, st.st_mtime))
|
|
|
|
|
|
|
|
|
|
|
|
def copyfile(source, dest):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode, unicode) -> None
|
2016-07-06 21:46:42 -05:00
|
|
|
"""Copy a file and its modification times, if possible.
|
|
|
|
|
|
|
|
Note: ``copyfile`` skips copying if the file has not been changed"""
|
|
|
|
if not path.exists(dest) or not filecmp.cmp(source, dest):
|
|
|
|
shutil.copyfile(source, dest)
|
|
|
|
try:
|
|
|
|
# don't do full copystat because the source may be read-only
|
|
|
|
copytimes(source, dest)
|
|
|
|
except OSError:
|
|
|
|
pass
|
2010-01-17 10:35:12 -06:00
|
|
|
|
|
|
|
|
|
|
|
no_fn_re = re.compile(r'[^a-zA-Z0-9_-]')
|
2018-11-11 04:48:50 -06:00
|
|
|
project_suffix_re = re.compile(' Documentation$')
|
2010-01-17 10:35:12 -06:00
|
|
|
|
2015-03-08 10:55:34 -05:00
|
|
|
|
2010-01-17 10:35:12 -06:00
|
|
|
def make_filename(string):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (str) -> unicode
|
2013-06-12 22:22:23 -05:00
|
|
|
return no_fn_re.sub('', string) or 'sphinx'
|
2010-01-17 10:35:12 -06:00
|
|
|
|
2015-07-09 05:03:49 -05:00
|
|
|
|
2018-11-11 04:48:50 -06:00
|
|
|
def make_filename_from_project(project):
|
|
|
|
# type: (str) -> unicode
|
|
|
|
return make_filename(project_suffix_re.sub('', project)).lower()
|
|
|
|
|
|
|
|
|
2015-07-09 05:03:49 -05:00
|
|
|
def ustrftime(format, *args):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode, Any) -> unicode
|
2018-02-05 15:37:45 -06:00
|
|
|
"""[DEPRECATED] strftime for unicode strings."""
|
|
|
|
warnings.warn('sphinx.util.osutil.ustrtime is deprecated for removal',
|
2018-10-14 10:33:19 -05:00
|
|
|
RemovedInSphinx30Warning, stacklevel=2)
|
2018-02-05 15:37:45 -06:00
|
|
|
|
2015-07-09 05:03:49 -05:00
|
|
|
if not args:
|
|
|
|
# If time is not specified, try to use $SOURCE_DATE_EPOCH variable
|
|
|
|
# See https://wiki.debian.org/ReproducibleBuilds/TimestampsProposal
|
|
|
|
source_date_epoch = os.getenv('SOURCE_DATE_EPOCH')
|
|
|
|
if source_date_epoch is not None:
|
|
|
|
time_struct = time.gmtime(float(source_date_epoch))
|
2016-11-08 20:45:12 -06:00
|
|
|
args = [time_struct] # type: ignore
|
2018-09-07 20:52:24 -05:00
|
|
|
# On Windows, time.strftime() and Unicode characters will raise UnicodeEncodeError.
|
|
|
|
# https://bugs.python.org/issue8304
|
|
|
|
try:
|
2018-12-12 10:33:14 -06:00
|
|
|
return time.strftime(format, *args)
|
2018-09-07 20:52:24 -05:00
|
|
|
except UnicodeEncodeError:
|
2018-12-12 10:33:14 -06:00
|
|
|
r = time.strftime(format.encode('unicode-escape').decode(), *args)
|
2018-09-07 20:52:24 -05:00
|
|
|
return r.encode().decode('unicode-escape')
|
2011-09-21 12:06:48 -05:00
|
|
|
|
|
|
|
|
2018-04-01 03:46:44 -05:00
|
|
|
def relpath(path, start=os.curdir):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode, unicode) -> unicode
|
2018-04-01 03:46:44 -05:00
|
|
|
"""Return a relative filepath to *path* either from the current directory or
|
|
|
|
from an optional *start* directory.
|
|
|
|
|
|
|
|
This is an alternative of ``os.path.relpath()``. This returns original path
|
|
|
|
if *path* and *start* are on different drives (for Windows platform).
|
|
|
|
"""
|
2011-09-21 12:06:48 -05:00
|
|
|
try:
|
2013-12-14 23:16:53 -06:00
|
|
|
return os.path.relpath(path, start)
|
2011-09-21 12:06:48 -05:00
|
|
|
except ValueError:
|
|
|
|
return path
|
2011-10-03 06:20:53 -05:00
|
|
|
|
2015-03-08 10:55:34 -05:00
|
|
|
|
2018-04-01 03:46:44 -05:00
|
|
|
safe_relpath = relpath # for compatibility
|
2016-11-08 20:45:12 -06:00
|
|
|
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() # type: unicode
|
2013-09-18 03:51:20 -05:00
|
|
|
|
|
|
|
|
|
|
|
def abspath(pathdir):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode) -> unicode
|
2013-09-18 03:51:20 -05:00
|
|
|
pathdir = path.abspath(pathdir)
|
|
|
|
if isinstance(pathdir, bytes):
|
2018-01-14 15:55:51 -06:00
|
|
|
try:
|
|
|
|
pathdir = pathdir.decode(fs_encoding)
|
|
|
|
except UnicodeDecodeError:
|
2018-12-12 10:33:14 -06:00
|
|
|
raise UnicodeDecodeError('multibyte filename not supported on '
|
2018-01-14 15:55:51 -06:00
|
|
|
'this filesystem encoding '
|
|
|
|
'(%r)' % fs_encoding)
|
2013-09-18 03:51:20 -05:00
|
|
|
return pathdir
|
2014-09-21 09:52:41 -05:00
|
|
|
|
|
|
|
|
|
|
|
def getcwd():
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: () -> unicode
|
2018-09-08 15:02:24 -05:00
|
|
|
warnings.warn('sphinx.util.osutil.getcwd() is deprecated. '
|
|
|
|
'Please use os.getcwd() instead.',
|
|
|
|
RemovedInSphinx40Warning)
|
2014-09-21 09:52:41 -05:00
|
|
|
return os.getcwd()
|
2014-09-25 12:11:51 -05:00
|
|
|
|
|
|
|
|
2014-09-25 11:46:29 -05:00
|
|
|
@contextlib.contextmanager
|
|
|
|
def cd(target_dir):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode) -> Iterator[None]
|
2018-09-08 15:02:24 -05:00
|
|
|
cwd = os.getcwd()
|
2014-09-25 11:46:29 -05:00
|
|
|
try:
|
|
|
|
os.chdir(target_dir)
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
os.chdir(cwd)
|
2015-06-02 12:00:12 -05:00
|
|
|
|
|
|
|
|
2018-09-11 08:48:35 -05:00
|
|
|
class FileAvoidWrite:
|
2015-06-02 12:00:12 -05:00
|
|
|
"""File-like object that buffers output and only writes if content changed.
|
|
|
|
|
|
|
|
Use this class like when writing to a file to avoid touching the original
|
|
|
|
file if the content hasn't changed. This is useful in scenarios where file
|
|
|
|
mtime is used to invalidate caches or trigger new behavior.
|
|
|
|
|
|
|
|
When writing to this file handle, all writes are buffered until the object
|
|
|
|
is closed.
|
|
|
|
|
|
|
|
Objects can be used as context managers.
|
|
|
|
"""
|
|
|
|
def __init__(self, path):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode) -> None
|
2015-06-02 12:00:12 -05:00
|
|
|
self._path = path
|
2016-11-08 20:45:12 -06:00
|
|
|
self._io = None # type: Union[StringIO, BytesIO]
|
2015-06-02 12:00:12 -05:00
|
|
|
|
|
|
|
def write(self, data):
|
2017-02-07 23:31:59 -06:00
|
|
|
# type: (Union[str, unicode]) -> None
|
2015-06-02 12:00:12 -05:00
|
|
|
if not self._io:
|
|
|
|
if isinstance(data, text_type):
|
|
|
|
self._io = StringIO()
|
|
|
|
else:
|
|
|
|
self._io = BytesIO()
|
|
|
|
|
2017-02-07 23:31:59 -06:00
|
|
|
self._io.write(data) # type: ignore
|
2015-06-02 12:00:12 -05:00
|
|
|
|
|
|
|
def close(self):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: () -> None
|
2015-06-02 12:00:12 -05:00
|
|
|
"""Stop accepting writes and write file, if needed."""
|
|
|
|
if not self._io:
|
|
|
|
raise Exception('FileAvoidWrite does not support empty files.')
|
|
|
|
|
|
|
|
buf = self.getvalue()
|
|
|
|
self._io.close()
|
|
|
|
|
|
|
|
r_mode = 'r'
|
|
|
|
w_mode = 'w'
|
|
|
|
if isinstance(self._io, BytesIO):
|
|
|
|
r_mode = 'rb'
|
|
|
|
w_mode = 'wb'
|
|
|
|
|
|
|
|
old_content = None
|
|
|
|
|
|
|
|
try:
|
2016-08-22 05:10:33 -05:00
|
|
|
with open(self._path, r_mode) as old_f:
|
2015-06-02 12:00:12 -05:00
|
|
|
old_content = old_f.read()
|
|
|
|
if old_content == buf:
|
|
|
|
return
|
2016-08-22 05:10:33 -05:00
|
|
|
except IOError:
|
|
|
|
pass
|
2015-06-02 12:00:12 -05:00
|
|
|
|
|
|
|
with open(self._path, w_mode) as f:
|
|
|
|
f.write(buf)
|
|
|
|
|
|
|
|
def __enter__(self):
|
2017-02-07 23:31:59 -06:00
|
|
|
# type: () -> FileAvoidWrite
|
2015-06-02 12:00:12 -05:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, type, value, traceback):
|
2017-02-07 23:31:59 -06:00
|
|
|
# type: (unicode, unicode, unicode) -> None
|
2015-06-02 12:00:12 -05:00
|
|
|
self.close()
|
|
|
|
|
|
|
|
def __getattr__(self, name):
|
2017-02-07 23:31:59 -06:00
|
|
|
# type: (str) -> Any
|
2015-06-02 12:00:12 -05:00
|
|
|
# Proxy to _io instance.
|
|
|
|
if not self._io:
|
|
|
|
raise Exception('Must write to FileAvoidWrite before other '
|
2016-08-22 05:06:50 -05:00
|
|
|
'methods can be used')
|
2015-06-02 12:00:12 -05:00
|
|
|
|
|
|
|
return getattr(self._io, name)
|
2016-08-22 05:03:27 -05:00
|
|
|
|
|
|
|
|
2016-07-15 10:11:25 -05:00
|
|
|
def rmtree(path):
|
2016-11-08 20:45:12 -06:00
|
|
|
# type: (unicode) -> None
|
2016-07-15 10:11:25 -05:00
|
|
|
if os.path.isdir(path):
|
|
|
|
shutil.rmtree(path)
|
|
|
|
else:
|
|
|
|
os.remove(path)
|