mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-10 21:34:18 +00:00
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
This commit is contained in:
parent
72ad6dc953
commit
f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions
|
|
@ -1,5 +1,4 @@
|
|||
"""create errno-specific classes for IO or os calls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
|
|
@ -13,25 +12,25 @@ from typing import TypeVar
|
|||
if TYPE_CHECKING:
|
||||
from typing_extensions import ParamSpec
|
||||
|
||||
P = ParamSpec("P")
|
||||
P = ParamSpec('P')
|
||||
|
||||
R = TypeVar("R")
|
||||
R = TypeVar('R')
|
||||
|
||||
|
||||
class Error(EnvironmentError):
|
||||
def __repr__(self) -> str:
|
||||
return "{}.{} {!r}: {} ".format(
|
||||
return '{}.{} {!r}: {} '.format(
|
||||
self.__class__.__module__,
|
||||
self.__class__.__name__,
|
||||
self.__class__.__doc__,
|
||||
" ".join(map(str, self.args)),
|
||||
' '.join(map(str, self.args)),
|
||||
# repr(self.args)
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
s = "[{}]: {}".format(
|
||||
s = '[{}]: {}'.format(
|
||||
self.__class__.__doc__,
|
||||
" ".join(map(str, self.args)),
|
||||
' '.join(map(str, self.args)),
|
||||
)
|
||||
return s
|
||||
|
||||
|
|
@ -58,7 +57,7 @@ class ErrorMaker:
|
|||
_errno2class: dict[int, type[Error]] = {}
|
||||
|
||||
def __getattr__(self, name: str) -> type[Error]:
|
||||
if name[0] == "_":
|
||||
if name[0] == '_':
|
||||
raise AttributeError(name)
|
||||
eno = getattr(errno, name)
|
||||
cls = self._geterrnoclass(eno)
|
||||
|
|
@ -69,17 +68,17 @@ class ErrorMaker:
|
|||
try:
|
||||
return self._errno2class[eno]
|
||||
except KeyError:
|
||||
clsname = errno.errorcode.get(eno, "UnknownErrno%d" % (eno,))
|
||||
clsname = errno.errorcode.get(eno, 'UnknownErrno%d' % (eno,))
|
||||
errorcls = type(
|
||||
clsname,
|
||||
(Error,),
|
||||
{"__module__": "py.error", "__doc__": os.strerror(eno)},
|
||||
{'__module__': 'py.error', '__doc__': os.strerror(eno)},
|
||||
)
|
||||
self._errno2class[eno] = errorcls
|
||||
return errorcls
|
||||
|
||||
def checked_call(
|
||||
self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
|
||||
self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs,
|
||||
) -> R:
|
||||
"""Call a function and raise an errno-exception if applicable."""
|
||||
__tracebackhide__ = True
|
||||
|
|
@ -88,10 +87,10 @@ class ErrorMaker:
|
|||
except Error:
|
||||
raise
|
||||
except OSError as value:
|
||||
if not hasattr(value, "errno"):
|
||||
if not hasattr(value, 'errno'):
|
||||
raise
|
||||
errno = value.errno
|
||||
if sys.platform == "win32":
|
||||
if sys.platform == 'win32':
|
||||
try:
|
||||
cls = self._geterrnoclass(_winerrnomap[errno])
|
||||
except KeyError:
|
||||
|
|
@ -100,7 +99,7 @@ class ErrorMaker:
|
|||
# we are not on Windows, or we got a proper OSError
|
||||
cls = self._geterrnoclass(errno)
|
||||
|
||||
raise cls(f"{func.__name__}{args!r}")
|
||||
raise cls(f'{func.__name__}{args!r}')
|
||||
|
||||
|
||||
_error_maker = ErrorMaker()
|
||||
|
|
|
|||
|
|
@ -3,11 +3,15 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
from contextlib import contextmanager
|
||||
import fnmatch
|
||||
import importlib.util
|
||||
import io
|
||||
import os
|
||||
import posixpath
|
||||
import sys
|
||||
import uuid
|
||||
import warnings
|
||||
from contextlib import contextmanager
|
||||
from os.path import abspath
|
||||
from os.path import dirname
|
||||
from os.path import exists
|
||||
|
|
@ -16,39 +20,35 @@ from os.path import isdir
|
|||
from os.path import isfile
|
||||
from os.path import islink
|
||||
from os.path import normpath
|
||||
import posixpath
|
||||
from stat import S_ISDIR
|
||||
from stat import S_ISLNK
|
||||
from stat import S_ISREG
|
||||
import sys
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
from typing import cast
|
||||
from typing import Literal
|
||||
from typing import overload
|
||||
from typing import TYPE_CHECKING
|
||||
import uuid
|
||||
import warnings
|
||||
|
||||
from . import error
|
||||
|
||||
|
||||
# Moved from local.py.
|
||||
iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt")
|
||||
iswin32 = sys.platform == 'win32' or (getattr(os, '_name', False) == 'nt')
|
||||
|
||||
|
||||
class Checkers:
|
||||
_depend_on_existence = "exists", "link", "dir", "file"
|
||||
_depend_on_existence = 'exists', 'link', 'dir', 'file'
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
|
||||
def dotfile(self):
|
||||
return self.path.basename.startswith(".")
|
||||
return self.path.basename.startswith('.')
|
||||
|
||||
def ext(self, arg):
|
||||
if not arg.startswith("."):
|
||||
arg = "." + arg
|
||||
if not arg.startswith('.'):
|
||||
arg = '.' + arg
|
||||
return self.path.ext == arg
|
||||
|
||||
def basename(self, arg):
|
||||
|
|
@ -75,14 +75,14 @@ class Checkers:
|
|||
try:
|
||||
meth = getattr(self, name)
|
||||
except AttributeError:
|
||||
if name[:3] == "not":
|
||||
if name[:3] == 'not':
|
||||
invert = True
|
||||
try:
|
||||
meth = getattr(self, name[3:])
|
||||
except AttributeError:
|
||||
pass
|
||||
if meth is None:
|
||||
raise TypeError(f"no {name!r} checker available for {self.path!r}")
|
||||
raise TypeError(f'no {name!r} checker available for {self.path!r}')
|
||||
try:
|
||||
if getrawcode(meth).co_argcount > 1:
|
||||
if (not meth(value)) ^ invert:
|
||||
|
|
@ -98,7 +98,7 @@ class Checkers:
|
|||
if name in kw:
|
||||
if kw.get(name):
|
||||
return False
|
||||
name = "not" + name
|
||||
name = 'not' + name
|
||||
if name in kw:
|
||||
if not kw.get(name):
|
||||
return False
|
||||
|
|
@ -140,7 +140,7 @@ class Visitor:
|
|||
fil = FNMatcher(fil)
|
||||
if isinstance(rec, str):
|
||||
self.rec: Callable[[LocalPath], bool] = FNMatcher(rec)
|
||||
elif not hasattr(rec, "__call__") and rec:
|
||||
elif not hasattr(rec, '__call__') and rec:
|
||||
self.rec = lambda path: True
|
||||
else:
|
||||
self.rec = rec
|
||||
|
|
@ -156,7 +156,7 @@ class Visitor:
|
|||
return
|
||||
rec = self.rec
|
||||
dirs = self.optsort(
|
||||
[p for p in entries if p.check(dir=1) and (rec is None or rec(p))]
|
||||
[p for p in entries if p.check(dir=1) and (rec is None or rec(p))],
|
||||
)
|
||||
if not self.breadthfirst:
|
||||
for subdir in dirs:
|
||||
|
|
@ -179,9 +179,9 @@ class FNMatcher:
|
|||
pattern = self.pattern
|
||||
|
||||
if (
|
||||
pattern.find(path.sep) == -1
|
||||
and iswin32
|
||||
and pattern.find(posixpath.sep) != -1
|
||||
pattern.find(path.sep) == -1 and
|
||||
iswin32 and
|
||||
pattern.find(posixpath.sep) != -1
|
||||
):
|
||||
# Running on Windows, the pattern has no Windows path separators,
|
||||
# and the pattern has one or more Posix path separators. Replace
|
||||
|
|
@ -193,7 +193,7 @@ class FNMatcher:
|
|||
else:
|
||||
name = str(path) # path.strpath # XXX svn?
|
||||
if not os.path.isabs(pattern):
|
||||
pattern = "*" + path.sep + pattern
|
||||
pattern = '*' + path.sep + pattern
|
||||
return fnmatch.fnmatch(name, pattern)
|
||||
|
||||
|
||||
|
|
@ -213,7 +213,7 @@ class Stat:
|
|||
...
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._osstatresult, "st_" + name)
|
||||
return getattr(self._osstatresult, 'st_' + name)
|
||||
|
||||
def __init__(self, path, osstatresult):
|
||||
self.path = path
|
||||
|
|
@ -222,7 +222,7 @@ class Stat:
|
|||
@property
|
||||
def owner(self):
|
||||
if iswin32:
|
||||
raise NotImplementedError("XXX win32")
|
||||
raise NotImplementedError('XXX win32')
|
||||
import pwd
|
||||
|
||||
entry = error.checked_call(pwd.getpwuid, self.uid) # type:ignore[attr-defined]
|
||||
|
|
@ -232,7 +232,7 @@ class Stat:
|
|||
def group(self):
|
||||
"""Return group name of file."""
|
||||
if iswin32:
|
||||
raise NotImplementedError("XXX win32")
|
||||
raise NotImplementedError('XXX win32')
|
||||
import grp
|
||||
|
||||
entry = error.checked_call(grp.getgrgid, self.gid) # type:ignore[attr-defined]
|
||||
|
|
@ -292,14 +292,14 @@ class LocalPath:
|
|||
path = os.fspath(path)
|
||||
except TypeError:
|
||||
raise ValueError(
|
||||
"can only pass None, Path instances "
|
||||
"or non-empty strings to LocalPath"
|
||||
'can only pass None, Path instances '
|
||||
'or non-empty strings to LocalPath',
|
||||
)
|
||||
if expanduser:
|
||||
path = os.path.expanduser(path)
|
||||
self.strpath = abspath(path)
|
||||
|
||||
if sys.platform != "win32":
|
||||
if sys.platform != 'win32':
|
||||
|
||||
def chown(self, user, group, rec=0):
|
||||
"""Change ownership to the given user and group.
|
||||
|
|
@ -334,7 +334,7 @@ class LocalPath:
|
|||
relsource = self.__class__(value).relto(base)
|
||||
reldest = self.relto(base)
|
||||
n = reldest.count(self.sep)
|
||||
target = self.sep.join(("..",) * n + (relsource,))
|
||||
target = self.sep.join(('..',) * n + (relsource,))
|
||||
error.checked_call(os.symlink, target, self.strpath)
|
||||
|
||||
def __div__(self, other):
|
||||
|
|
@ -345,34 +345,34 @@ class LocalPath:
|
|||
@property
|
||||
def basename(self):
|
||||
"""Basename part of path."""
|
||||
return self._getbyspec("basename")[0]
|
||||
return self._getbyspec('basename')[0]
|
||||
|
||||
@property
|
||||
def dirname(self):
|
||||
"""Dirname part of path."""
|
||||
return self._getbyspec("dirname")[0]
|
||||
return self._getbyspec('dirname')[0]
|
||||
|
||||
@property
|
||||
def purebasename(self):
|
||||
"""Pure base name of the path."""
|
||||
return self._getbyspec("purebasename")[0]
|
||||
return self._getbyspec('purebasename')[0]
|
||||
|
||||
@property
|
||||
def ext(self):
|
||||
"""Extension of the path (including the '.')."""
|
||||
return self._getbyspec("ext")[0]
|
||||
return self._getbyspec('ext')[0]
|
||||
|
||||
def read_binary(self):
|
||||
"""Read and return a bytestring from reading the path."""
|
||||
with self.open("rb") as f:
|
||||
with self.open('rb') as f:
|
||||
return f.read()
|
||||
|
||||
def read_text(self, encoding):
|
||||
"""Read and return a Unicode string from reading the path."""
|
||||
with self.open("r", encoding=encoding) as f:
|
||||
with self.open('r', encoding=encoding) as f:
|
||||
return f.read()
|
||||
|
||||
def read(self, mode="r"):
|
||||
def read(self, mode='r'):
|
||||
"""Read and return a bytestring from reading the path."""
|
||||
with self.open(mode) as f:
|
||||
return f.read()
|
||||
|
|
@ -380,11 +380,11 @@ class LocalPath:
|
|||
def readlines(self, cr=1):
|
||||
"""Read and return a list of lines from the path. if cr is False, the
|
||||
newline will be removed from the end of each line."""
|
||||
mode = "r"
|
||||
mode = 'r'
|
||||
|
||||
if not cr:
|
||||
content = self.read(mode)
|
||||
return content.split("\n")
|
||||
return content.split('\n')
|
||||
else:
|
||||
f = self.open(mode)
|
||||
try:
|
||||
|
|
@ -394,7 +394,7 @@ class LocalPath:
|
|||
|
||||
def load(self):
|
||||
"""(deprecated) return object unpickled from self.read()"""
|
||||
f = self.open("rb")
|
||||
f = self.open('rb')
|
||||
try:
|
||||
import pickle
|
||||
|
||||
|
|
@ -405,7 +405,7 @@ class LocalPath:
|
|||
def move(self, target):
|
||||
"""Move this path to target."""
|
||||
if target.relto(self):
|
||||
raise error.EINVAL(target, "cannot move path into a subdirectory of itself")
|
||||
raise error.EINVAL(target, 'cannot move path into a subdirectory of itself')
|
||||
try:
|
||||
self.rename(target)
|
||||
except error.EXDEV: # invalid cross-device link
|
||||
|
|
@ -436,19 +436,19 @@ class LocalPath:
|
|||
to the given 'relpath'.
|
||||
"""
|
||||
if not isinstance(relpath, (str, LocalPath)):
|
||||
raise TypeError(f"{relpath!r}: not a string or path object")
|
||||
raise TypeError(f'{relpath!r}: not a string or path object')
|
||||
strrelpath = str(relpath)
|
||||
if strrelpath and strrelpath[-1] != self.sep:
|
||||
strrelpath += self.sep
|
||||
# assert strrelpath[-1] == self.sep
|
||||
# assert strrelpath[-2] != self.sep
|
||||
strself = self.strpath
|
||||
if sys.platform == "win32" or getattr(os, "_name", None) == "nt":
|
||||
if sys.platform == 'win32' or getattr(os, '_name', None) == 'nt':
|
||||
if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)):
|
||||
return strself[len(strrelpath) :]
|
||||
return strself[len(strrelpath):]
|
||||
elif strself.startswith(strrelpath):
|
||||
return strself[len(strrelpath) :]
|
||||
return ""
|
||||
return strself[len(strrelpath):]
|
||||
return ''
|
||||
|
||||
def ensure_dir(self, *args):
|
||||
"""Ensure the path joined with args is a directory."""
|
||||
|
|
@ -542,10 +542,10 @@ class LocalPath:
|
|||
|
||||
def _sortlist(self, res, sort):
|
||||
if sort:
|
||||
if hasattr(sort, "__call__"):
|
||||
if hasattr(sort, '__call__'):
|
||||
warnings.warn(
|
||||
DeprecationWarning(
|
||||
"listdir(sort=callable) is deprecated and breaks on python3"
|
||||
'listdir(sort=callable) is deprecated and breaks on python3',
|
||||
),
|
||||
stacklevel=3,
|
||||
)
|
||||
|
|
@ -592,7 +592,7 @@ class LocalPath:
|
|||
other = abspath(other)
|
||||
if self == other:
|
||||
return True
|
||||
if not hasattr(os.path, "samefile"):
|
||||
if not hasattr(os.path, 'samefile'):
|
||||
return False
|
||||
return error.checked_call(os.path.samefile, self.strpath, other)
|
||||
|
||||
|
|
@ -609,7 +609,7 @@ class LocalPath:
|
|||
import shutil
|
||||
|
||||
error.checked_call(
|
||||
shutil.rmtree, self.strpath, ignore_errors=ignore_errors
|
||||
shutil.rmtree, self.strpath, ignore_errors=ignore_errors,
|
||||
)
|
||||
else:
|
||||
error.checked_call(os.rmdir, self.strpath)
|
||||
|
|
@ -618,19 +618,19 @@ class LocalPath:
|
|||
self.chmod(0o700)
|
||||
error.checked_call(os.remove, self.strpath)
|
||||
|
||||
def computehash(self, hashtype="md5", chunksize=524288):
|
||||
def computehash(self, hashtype='md5', chunksize=524288):
|
||||
"""Return hexdigest of hashvalue for this file."""
|
||||
try:
|
||||
try:
|
||||
import hashlib as mod
|
||||
except ImportError:
|
||||
if hashtype == "sha1":
|
||||
hashtype = "sha"
|
||||
if hashtype == 'sha1':
|
||||
hashtype = 'sha'
|
||||
mod = __import__(hashtype)
|
||||
hash = getattr(mod, hashtype)()
|
||||
except (AttributeError, ImportError):
|
||||
raise ValueError(f"Don't know how to compute {hashtype!r} hash")
|
||||
f = self.open("rb")
|
||||
f = self.open('rb')
|
||||
try:
|
||||
while 1:
|
||||
buf = f.read(chunksize)
|
||||
|
|
@ -656,28 +656,28 @@ class LocalPath:
|
|||
obj.strpath = self.strpath
|
||||
return obj
|
||||
drive, dirname, basename, purebasename, ext = self._getbyspec(
|
||||
"drive,dirname,basename,purebasename,ext"
|
||||
'drive,dirname,basename,purebasename,ext',
|
||||
)
|
||||
if "basename" in kw:
|
||||
if "purebasename" in kw or "ext" in kw:
|
||||
raise ValueError("invalid specification %r" % kw)
|
||||
if 'basename' in kw:
|
||||
if 'purebasename' in kw or 'ext' in kw:
|
||||
raise ValueError('invalid specification %r' % kw)
|
||||
else:
|
||||
pb = kw.setdefault("purebasename", purebasename)
|
||||
pb = kw.setdefault('purebasename', purebasename)
|
||||
try:
|
||||
ext = kw["ext"]
|
||||
ext = kw['ext']
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
if ext and not ext.startswith("."):
|
||||
ext = "." + ext
|
||||
kw["basename"] = pb + ext
|
||||
if ext and not ext.startswith('.'):
|
||||
ext = '.' + ext
|
||||
kw['basename'] = pb + ext
|
||||
|
||||
if "dirname" in kw and not kw["dirname"]:
|
||||
kw["dirname"] = drive
|
||||
if 'dirname' in kw and not kw['dirname']:
|
||||
kw['dirname'] = drive
|
||||
else:
|
||||
kw.setdefault("dirname", dirname)
|
||||
kw.setdefault("sep", self.sep)
|
||||
obj.strpath = normpath("{dirname}{sep}{basename}".format(**kw))
|
||||
kw.setdefault('dirname', dirname)
|
||||
kw.setdefault('sep', self.sep)
|
||||
obj.strpath = normpath('{dirname}{sep}{basename}'.format(**kw))
|
||||
return obj
|
||||
|
||||
def _getbyspec(self, spec: str) -> list[str]:
|
||||
|
|
@ -685,28 +685,28 @@ class LocalPath:
|
|||
res = []
|
||||
parts = self.strpath.split(self.sep)
|
||||
|
||||
args = filter(None, spec.split(","))
|
||||
args = filter(None, spec.split(','))
|
||||
for name in args:
|
||||
if name == "drive":
|
||||
if name == 'drive':
|
||||
res.append(parts[0])
|
||||
elif name == "dirname":
|
||||
elif name == 'dirname':
|
||||
res.append(self.sep.join(parts[:-1]))
|
||||
else:
|
||||
basename = parts[-1]
|
||||
if name == "basename":
|
||||
if name == 'basename':
|
||||
res.append(basename)
|
||||
else:
|
||||
i = basename.rfind(".")
|
||||
i = basename.rfind('.')
|
||||
if i == -1:
|
||||
purebasename, ext = basename, ""
|
||||
purebasename, ext = basename, ''
|
||||
else:
|
||||
purebasename, ext = basename[:i], basename[i:]
|
||||
if name == "purebasename":
|
||||
if name == 'purebasename':
|
||||
res.append(purebasename)
|
||||
elif name == "ext":
|
||||
elif name == 'ext':
|
||||
res.append(ext)
|
||||
else:
|
||||
raise ValueError("invalid part specification %r" % name)
|
||||
raise ValueError('invalid part specification %r' % name)
|
||||
return res
|
||||
|
||||
def dirpath(self, *args, **kwargs):
|
||||
|
|
@ -717,7 +717,7 @@ class LocalPath:
|
|||
if args:
|
||||
path = path.join(*args)
|
||||
return path
|
||||
return self.new(basename="").join(*args, **kwargs)
|
||||
return self.new(basename='').join(*args, **kwargs)
|
||||
|
||||
def join(self, *args: os.PathLike[str], abs: bool = False) -> LocalPath:
|
||||
"""Return a new path by appending all 'args' as path
|
||||
|
|
@ -736,20 +736,20 @@ class LocalPath:
|
|||
break
|
||||
newargs.insert(0, arg)
|
||||
# special case for when we have e.g. strpath == "/"
|
||||
actual_sep = "" if strpath.endswith(sep) else sep
|
||||
actual_sep = '' if strpath.endswith(sep) else sep
|
||||
for arg in strargs:
|
||||
arg = arg.strip(sep)
|
||||
if iswin32:
|
||||
# allow unix style paths even on windows.
|
||||
arg = arg.strip("/")
|
||||
arg = arg.replace("/", sep)
|
||||
arg = arg.strip('/')
|
||||
arg = arg.replace('/', sep)
|
||||
strpath = strpath + actual_sep + arg
|
||||
actual_sep = sep
|
||||
obj = object.__new__(self.__class__)
|
||||
obj.strpath = normpath(strpath)
|
||||
return obj
|
||||
|
||||
def open(self, mode="r", ensure=False, encoding=None):
|
||||
def open(self, mode='r', ensure=False, encoding=None):
|
||||
"""Return an opened file with the given mode.
|
||||
|
||||
If ensure is True, create parent directories if needed.
|
||||
|
|
@ -797,15 +797,15 @@ class LocalPath:
|
|||
if not kw:
|
||||
return exists(self.strpath)
|
||||
if len(kw) == 1:
|
||||
if "dir" in kw:
|
||||
return not kw["dir"] ^ isdir(self.strpath)
|
||||
if "file" in kw:
|
||||
return not kw["file"] ^ isfile(self.strpath)
|
||||
if 'dir' in kw:
|
||||
return not kw['dir'] ^ isdir(self.strpath)
|
||||
if 'file' in kw:
|
||||
return not kw['file'] ^ isfile(self.strpath)
|
||||
if not kw:
|
||||
kw = {"exists": 1}
|
||||
kw = {'exists': 1}
|
||||
return Checkers(self)._evaluate(kw)
|
||||
|
||||
_patternchars = set("*?[" + os.sep)
|
||||
_patternchars = set('*?[' + os.sep)
|
||||
|
||||
def listdir(self, fil=None, sort=None):
|
||||
"""List directory contents, possibly filter by the given fil func
|
||||
|
|
@ -882,7 +882,7 @@ class LocalPath:
|
|||
|
||||
def dump(self, obj, bin=1):
|
||||
"""Pickle object into path location"""
|
||||
f = self.open("wb")
|
||||
f = self.open('wb')
|
||||
import pickle
|
||||
|
||||
try:
|
||||
|
|
@ -902,7 +902,7 @@ class LocalPath:
|
|||
"""
|
||||
if ensure:
|
||||
self.dirpath().ensure(dir=1)
|
||||
with self.open("wb") as f:
|
||||
with self.open('wb') as f:
|
||||
f.write(data)
|
||||
|
||||
def write_text(self, data, encoding, ensure=False):
|
||||
|
|
@ -911,18 +911,18 @@ class LocalPath:
|
|||
"""
|
||||
if ensure:
|
||||
self.dirpath().ensure(dir=1)
|
||||
with self.open("w", encoding=encoding) as f:
|
||||
with self.open('w', encoding=encoding) as f:
|
||||
f.write(data)
|
||||
|
||||
def write(self, data, mode="w", ensure=False):
|
||||
def write(self, data, mode='w', ensure=False):
|
||||
"""Write data into path. If ensure is True create
|
||||
missing parent directories.
|
||||
"""
|
||||
if ensure:
|
||||
self.dirpath().ensure(dir=1)
|
||||
if "b" in mode:
|
||||
if 'b' in mode:
|
||||
if not isinstance(data, bytes):
|
||||
raise ValueError("can only process bytes")
|
||||
raise ValueError('can only process bytes')
|
||||
else:
|
||||
if not isinstance(data, str):
|
||||
if not isinstance(data, bytes):
|
||||
|
|
@ -957,12 +957,12 @@ class LocalPath:
|
|||
then the path is forced to be a directory path.
|
||||
"""
|
||||
p = self.join(*args)
|
||||
if kwargs.get("dir", 0):
|
||||
if kwargs.get('dir', 0):
|
||||
return p._ensuredirs()
|
||||
else:
|
||||
p.dirpath()._ensuredirs()
|
||||
if not p.check(file=1):
|
||||
p.open("wb").close()
|
||||
p.open('wb').close()
|
||||
return p
|
||||
|
||||
@overload
|
||||
|
|
@ -1033,7 +1033,7 @@ class LocalPath:
|
|||
return self.stat().atime
|
||||
|
||||
def __repr__(self):
|
||||
return "local(%r)" % self.strpath
|
||||
return 'local(%r)' % self.strpath
|
||||
|
||||
def __str__(self):
|
||||
"""Return string representation of the Path."""
|
||||
|
|
@ -1045,7 +1045,7 @@ class LocalPath:
|
|||
if rec is True perform recursively.
|
||||
"""
|
||||
if not isinstance(mode, int):
|
||||
raise TypeError(f"mode {mode!r} must be an integer")
|
||||
raise TypeError(f'mode {mode!r} must be an integer')
|
||||
if rec:
|
||||
for x in self.visit(rec=rec):
|
||||
error.checked_call(os.chmod, str(x), mode)
|
||||
|
|
@ -1059,7 +1059,7 @@ class LocalPath:
|
|||
pkgpath = None
|
||||
for parent in self.parts(reverse=True):
|
||||
if parent.isdir():
|
||||
if not parent.join("__init__.py").exists():
|
||||
if not parent.join('__init__.py').exists():
|
||||
break
|
||||
if not isimportable(parent.basename):
|
||||
break
|
||||
|
|
@ -1069,7 +1069,7 @@ class LocalPath:
|
|||
def _ensuresyspath(self, ensuremode, path):
|
||||
if ensuremode:
|
||||
s = str(path)
|
||||
if ensuremode == "append":
|
||||
if ensuremode == 'append':
|
||||
if s not in sys.path:
|
||||
sys.path.append(s)
|
||||
else:
|
||||
|
|
@ -1100,7 +1100,7 @@ class LocalPath:
|
|||
if not self.check():
|
||||
raise error.ENOENT(self)
|
||||
|
||||
if ensuresyspath == "importlib":
|
||||
if ensuresyspath == 'importlib':
|
||||
if modname is None:
|
||||
modname = self.purebasename
|
||||
spec = importlib.util.spec_from_file_location(modname, str(self))
|
||||
|
|
@ -1115,10 +1115,10 @@ class LocalPath:
|
|||
pkgpath = self.pypkgpath()
|
||||
if pkgpath is not None:
|
||||
pkgroot = pkgpath.dirpath()
|
||||
names = self.new(ext="").relto(pkgroot).split(self.sep)
|
||||
if names[-1] == "__init__":
|
||||
names = self.new(ext='').relto(pkgroot).split(self.sep)
|
||||
if names[-1] == '__init__':
|
||||
names.pop()
|
||||
modname = ".".join(names)
|
||||
modname = '.'.join(names)
|
||||
else:
|
||||
pkgroot = self.dirpath()
|
||||
modname = self.purebasename
|
||||
|
|
@ -1126,25 +1126,25 @@ class LocalPath:
|
|||
self._ensuresyspath(ensuresyspath, pkgroot)
|
||||
__import__(modname)
|
||||
mod = sys.modules[modname]
|
||||
if self.basename == "__init__.py":
|
||||
if self.basename == '__init__.py':
|
||||
return mod # we don't check anything as we might
|
||||
# be in a namespace package ... too icky to check
|
||||
modfile = mod.__file__
|
||||
assert modfile is not None
|
||||
if modfile[-4:] in (".pyc", ".pyo"):
|
||||
if modfile[-4:] in ('.pyc', '.pyo'):
|
||||
modfile = modfile[:-1]
|
||||
elif modfile.endswith("$py.class"):
|
||||
modfile = modfile[:-9] + ".py"
|
||||
if modfile.endswith(os.sep + "__init__.py"):
|
||||
if self.basename != "__init__.py":
|
||||
elif modfile.endswith('$py.class'):
|
||||
modfile = modfile[:-9] + '.py'
|
||||
if modfile.endswith(os.sep + '__init__.py'):
|
||||
if self.basename != '__init__.py':
|
||||
modfile = modfile[:-12]
|
||||
try:
|
||||
issame = self.samefile(modfile)
|
||||
except error.ENOENT:
|
||||
issame = False
|
||||
if not issame:
|
||||
ignore = os.getenv("PY_IGNORE_IMPORTMISMATCH")
|
||||
if ignore != "1":
|
||||
ignore = os.getenv('PY_IGNORE_IMPORTMISMATCH')
|
||||
if ignore != '1':
|
||||
raise self.ImportMismatchError(modname, modfile, self)
|
||||
return mod
|
||||
else:
|
||||
|
|
@ -1158,7 +1158,7 @@ class LocalPath:
|
|||
mod.__file__ = str(self)
|
||||
sys.modules[modname] = mod
|
||||
try:
|
||||
with open(str(self), "rb") as f:
|
||||
with open(str(self), 'rb') as f:
|
||||
exec(f.read(), mod.__dict__)
|
||||
except BaseException:
|
||||
del sys.modules[modname]
|
||||
|
|
@ -1173,8 +1173,8 @@ class LocalPath:
|
|||
from subprocess import PIPE
|
||||
from subprocess import Popen
|
||||
|
||||
popen_opts.pop("stdout", None)
|
||||
popen_opts.pop("stderr", None)
|
||||
popen_opts.pop('stdout', None)
|
||||
popen_opts.pop('stderr', None)
|
||||
proc = Popen(
|
||||
[str(self)] + [str(arg) for arg in argv],
|
||||
**popen_opts,
|
||||
|
|
@ -1214,23 +1214,23 @@ class LocalPath:
|
|||
else:
|
||||
if paths is None:
|
||||
if iswin32:
|
||||
paths = os.environ["Path"].split(";")
|
||||
if "" not in paths and "." not in paths:
|
||||
paths.append(".")
|
||||
paths = os.environ['Path'].split(';')
|
||||
if '' not in paths and '.' not in paths:
|
||||
paths.append('.')
|
||||
try:
|
||||
systemroot = os.environ["SYSTEMROOT"]
|
||||
systemroot = os.environ['SYSTEMROOT']
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
paths = [
|
||||
path.replace("%SystemRoot%", systemroot) for path in paths
|
||||
path.replace('%SystemRoot%', systemroot) for path in paths
|
||||
]
|
||||
else:
|
||||
paths = os.environ["PATH"].split(":")
|
||||
paths = os.environ['PATH'].split(':')
|
||||
tryadd = []
|
||||
if iswin32:
|
||||
tryadd += os.environ["PATHEXT"].split(os.pathsep)
|
||||
tryadd.append("")
|
||||
tryadd += os.environ['PATHEXT'].split(os.pathsep)
|
||||
tryadd.append('')
|
||||
|
||||
for x in paths:
|
||||
for addext in tryadd:
|
||||
|
|
@ -1248,10 +1248,10 @@ class LocalPath:
|
|||
@classmethod
|
||||
def _gethomedir(cls):
|
||||
try:
|
||||
x = os.environ["HOME"]
|
||||
x = os.environ['HOME']
|
||||
except KeyError:
|
||||
try:
|
||||
x = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]
|
||||
x = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
|
||||
except KeyError:
|
||||
return None
|
||||
return cls(x)
|
||||
|
|
@ -1288,7 +1288,7 @@ class LocalPath:
|
|||
|
||||
@classmethod
|
||||
def make_numbered_dir(
|
||||
cls, prefix="session-", rootdir=None, keep=3, lock_timeout=172800
|
||||
cls, prefix='session-', rootdir=None, keep=3, lock_timeout=172800,
|
||||
): # two days
|
||||
"""Return unique directory with a number greater than the current
|
||||
maximum one. The number is assumed to start directly after prefix.
|
||||
|
|
@ -1306,21 +1306,21 @@ class LocalPath:
|
|||
nbasename = path.basename.lower()
|
||||
if nbasename.startswith(nprefix):
|
||||
try:
|
||||
return int(nbasename[len(nprefix) :])
|
||||
return int(nbasename[len(nprefix):])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def create_lockfile(path):
|
||||
"""Exclusively create lockfile. Throws when failed"""
|
||||
mypid = os.getpid()
|
||||
lockfile = path.join(".lock")
|
||||
if hasattr(lockfile, "mksymlinkto"):
|
||||
lockfile = path.join('.lock')
|
||||
if hasattr(lockfile, 'mksymlinkto'):
|
||||
lockfile.mksymlinkto(str(mypid))
|
||||
else:
|
||||
fd = error.checked_call(
|
||||
os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644
|
||||
os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644,
|
||||
)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
f.write(str(mypid))
|
||||
return lockfile
|
||||
|
||||
|
|
@ -1380,7 +1380,7 @@ class LocalPath:
|
|||
except error.Error:
|
||||
pass
|
||||
|
||||
garbage_prefix = prefix + "garbage-"
|
||||
garbage_prefix = prefix + 'garbage-'
|
||||
|
||||
def is_garbage(path):
|
||||
"""Check if path denotes directory scheduled for removal"""
|
||||
|
|
@ -1428,15 +1428,15 @@ class LocalPath:
|
|||
|
||||
# make link...
|
||||
try:
|
||||
username = os.environ["USER"] # linux, et al
|
||||
username = os.environ['USER'] # linux, et al
|
||||
except KeyError:
|
||||
try:
|
||||
username = os.environ["USERNAME"] # windows
|
||||
username = os.environ['USERNAME'] # windows
|
||||
except KeyError:
|
||||
username = "current"
|
||||
username = 'current'
|
||||
|
||||
src = str(udir)
|
||||
dest = src[: src.rfind("-")] + "-" + username
|
||||
dest = src[: src.rfind('-')] + '-' + username
|
||||
try:
|
||||
os.unlink(dest)
|
||||
except OSError:
|
||||
|
|
@ -1466,9 +1466,9 @@ def copystat(src, dest):
|
|||
|
||||
def copychunked(src, dest):
|
||||
chunksize = 524288 # half a meg of bytes
|
||||
fsrc = src.open("rb")
|
||||
fsrc = src.open('rb')
|
||||
try:
|
||||
fdest = dest.open("wb")
|
||||
fdest = dest.open('wb')
|
||||
try:
|
||||
while 1:
|
||||
buf = fsrc.read(chunksize)
|
||||
|
|
@ -1482,8 +1482,8 @@ def copychunked(src, dest):
|
|||
|
||||
|
||||
def isimportable(name):
|
||||
if name and (name[0].isalpha() or name[0] == "_"):
|
||||
name = name.replace("_", "")
|
||||
if name and (name[0].isalpha() or name[0] == '_'):
|
||||
name = name.replace('_', '')
|
||||
return not name or name.isalnum()
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue