##// END OF EJS Templates
test-hardlink: stop explicitly listing `undo.dirstate`...
test-hardlink: stop explicitly listing `undo.dirstate` The files is on its way out.

File last commit:

r50807:bc83ebe0 default
r50978:a28cedb2 default
Show More
pathutil.py
391 lines | 12.5 KiB | text/x-python | PythonLexer
Valentin Gatien-Baron
grep: reduce the cost of pathauditor checks when grepping working copy...
r45392 import contextlib
Gregory Szorc
pathutil: use absolute_import
r25964 import errno
import os
import posixpath
import stat
Arseniy Alekseyev
typing: import unconditionally...
r50801 from typing import (
Any,
Callable,
Iterator,
Optional,
)
Gregory Szorc
pathutil: use absolute_import
r25964 from .i18n import _
from . import (
encoding,
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 error,
utils: move the `dirs` definition in pathutil (API)...
r43923 policy,
Pulkit Goyal
py3: replace os.sep with pycompat.ossep (part 2 of 4)...
r30614 pycompat,
Gregory Szorc
pathutil: use absolute_import
r25964 util,
)
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033
utils: move the `dirs` definition in pathutil (API)...
r43923 rustdirs = policy.importrust('dirstate', 'Dirs')
parsers = policy.importmod('parsers')
Augie Fackler
formatting: blacken the codebase...
r43346
Augie Fackler
pathauditor: check for codepoints ignored on OS X
r23598 def _lowerclean(s):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes) -> bytes
Augie Fackler
pathauditor: check for codepoints ignored on OS X
r23598 return encoding.hfsignoreclean(s.lower())
Augie Fackler
formatting: blacken the codebase...
r43346
Gregory Szorc
py3: use class X: instead of class X(object):...
r49801 class pathauditor:
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """ensure that a filesystem path contains no banned components.
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 the following properties of a path are checked:
- ends with a directory separator
- under top-level .hg
- starts at the root of a windows drive
- contains ".."
Pierre-Yves David
pathauditor: add a way to skip file system check...
r27232
More check are also done about the file system states:
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 - traverses a symlink (e.g. a/symlink_here/b)
- inside a nested repository (a callback can be used to approve
some nested repositories, e.g., subrepositories)
Pierre-Yves David
pathauditor: add a way to skip file system check...
r27232
The file system checks are only done when 'realfs' is set to True (the
default). They should be disable then we are auditing path for operation on
stored history.
Yuya Nishihara
pathauditor: disable cache of audited paths by default (issue5628)...
r33722
If 'cached' is set to True, audited paths and sub-directories are cached.
Be careful to not keep the cache of unmanaged directories for long because
audited paths may be replaced with symlinks.
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033
Yuya Nishihara
pathauditor: disable cache of audited paths by default (issue5628)...
r33722 def __init__(self, root, callback=None, realfs=True, cached=False):
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 self.audited = set()
Arseniy Alekseyev
merge: cache the fs checks made during [_checkunknownfiles]...
r50784 self.auditeddir = dict()
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 self.root = root
Pierre-Yves David
pathauditor: add a way to skip file system check...
r27232 self._realfs = realfs
Yuya Nishihara
pathauditor: disable cache of audited paths by default (issue5628)...
r33722 self._cached = cached
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 self.callback = callback
Martin von Zweigbergk
util: rename checkcase() to fscasesensitive() (API)...
r29889 if os.path.lexists(root) and not util.fscasesensitive(root):
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 self.normcase = util.normcase
else:
self.normcase = lambda x: x
Boris Feld
vfs: allow to pass more argument to audit...
r33435 def __call__(self, path, mode=None):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes, Optional[Any]) -> None
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """Check the relative path.
path may contain a pattern (e.g. foodir/**.txt)"""
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033
path = util.localpath(path)
Arseniy Alekseyev
pathauditor: no need to normcase the paths...
r50780 if path in self.audited:
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 return
# AIX ignores "/" at end of path, others raise EISDIR.
if util.endswithsep(path):
Martin von Zweigbergk
errors: use detailed exit code in pathauditor...
r49192 raise error.InputError(
_(b"path ends in directory separator: %s") % path
)
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 parts = util.splitpath(path)
Augie Fackler
formatting: blacken the codebase...
r43346 if (
os.path.splitdrive(path)[0]
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 or _lowerclean(parts[0]) in (b'.hg', b'.hg.', b'')
Augie Fackler
formatting: blacken the codebase...
r43346 or pycompat.ospardir in parts
):
Martin von Zweigbergk
errors: use detailed exit code in pathauditor...
r49192 raise error.InputError(
_(b"path contains illegal component: %s") % path
)
Matt Mackall
pathauditor: check for Windows shortname aliases
r23599 # Windows shortname aliases
Arseniy Alekseyev
pathutil: slightly faster path audit in the common case
r50779 if b"~" in path:
for p in parts:
if b"~" in p:
first, last = p.split(b"~", 1)
if last.isdigit() and first.upper() in [b"HG", b"HG8B6C"]:
raise error.InputError(
_(b"path contains illegal component: %s") % path
)
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 if b'.hg' in _lowerclean(path):
Martin von Zweigbergk
pathauditor: drop a redundant call to bytes.lower()...
r44641 lparts = [_lowerclean(p) for p in parts]
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 for p in b'.hg', b'.hg.':
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 if p in lparts[1:]:
pos = lparts.index(p)
base = os.path.join(*parts[:pos])
Martin von Zweigbergk
errors: use detailed exit code in pathauditor...
r49192 raise error.InputError(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b"path '%s' is inside nested repo %r")
Augie Fackler
formatting: blacken the codebase...
r43346 % (path, pycompat.bytestr(base))
)
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033
Arseniy Alekseyev
merge: disable the whole filesystem access loop if [_realfs] is false...
r50783 if self._realfs:
# It's important that we check the path parts starting from the root.
# We don't want to add "foo/bar/baz" to auditeddir before checking if
# there's a "foo/.hg" directory. This also means we won't accidentally
# traverse a symlink into some other filesystem (which is potentially
# expensive to access).
Arseniy Alekseyev
pathutil: use `finddirs_rev_noroot` instead of `parts`...
r50803 for prefix in finddirs_rev_noroot(path):
Arseniy Alekseyev
merge: disable the whole filesystem access loop if [_realfs] is false...
r50783 if prefix in self.auditeddir:
Arseniy Alekseyev
merge: cache the fs checks made during [_checkunknownfiles]...
r50784 res = self.auditeddir[prefix]
else:
Arseniy Alekseyev
pathauditor: make _checkfs_exists a static method...
r50807 res = pathauditor._checkfs_exists(
self.root, prefix, path, self.callback
)
Arseniy Alekseyev
merge: cache the fs checks made during [_checkunknownfiles]...
r50784 if self._cached:
self.auditeddir[prefix] = res
Arseniy Alekseyev
merge: disable the whole filesystem access loop if [_realfs] is false...
r50783 if not res:
break
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033
Yuya Nishihara
pathauditor: disable cache of audited paths by default (issue5628)...
r33722 if self._cached:
Arseniy Alekseyev
pathauditor: no need to normcase the paths...
r50780 self.audited.add(path)
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033
Arseniy Alekseyev
pathauditor: make _checkfs_exists a static method...
r50807 @staticmethod
def _checkfs_exists(
root,
prefix: bytes,
path: bytes,
callback: Optional[Callable[[bytes], bool]] = None,
):
Arseniy Alekseyev
merge: short-circuit the _checkfs loop upon getting ENOENT...
r50782 """raise exception if a file system backed check fails.
Return a bool that indicates that the directory (or file) exists."""
Arseniy Alekseyev
pathauditor: make _checkfs_exists a static method...
r50807 curpath = os.path.join(root, prefix)
Pierre-Yves David
pathauditor: move file system specific check in their own function...
r27231 try:
st = os.lstat(curpath)
except OSError as err:
Arseniy Alekseyev
merge: short-circuit the _checkfs loop upon getting ENOENT...
r50782 if err.errno == errno.ENOENT:
return False
Pierre-Yves David
pathauditor: move file system specific check in their own function...
r27231 # EINVAL can be raised as invalid path syntax under win32.
# They must be ignored for patterns can be checked too.
if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
raise
else:
if stat.S_ISLNK(st.st_mode):
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 msg = _(b'path %r traverses symbolic link %r') % (
Augie Fackler
formatting: blacken the codebase...
r43346 pycompat.bytestr(path),
pycompat.bytestr(prefix),
)
Pierre-Yves David
pathutil: use temporary variables instead of complicated wrapping...
r27235 raise error.Abort(msg)
Augie Fackler
formatting: blacken the codebase...
r43346 elif stat.S_ISDIR(st.st_mode) and os.path.isdir(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 os.path.join(curpath, b'.hg')
Augie Fackler
formatting: blacken the codebase...
r43346 ):
Arseniy Alekseyev
pathauditor: make _checkfs_exists a static method...
r50807 if not callback or not callback(curpath):
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 msg = _(b"path '%s' is inside nested repo %r")
Yuya Nishihara
py3: fix formatting of path-auditing errors
r36667 raise error.Abort(msg % (path, pycompat.bytestr(prefix)))
Arseniy Alekseyev
merge: short-circuit the _checkfs loop upon getting ENOENT...
r50782 return True
Pierre-Yves David
pathauditor: move file system specific check in their own function...
r27231
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 def check(self, path):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes) -> bool
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 try:
self(path)
return True
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 except (OSError, error.Abort):
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 return False
Valentin Gatien-Baron
grep: reduce the cost of pathauditor checks when grepping working copy...
r45392 @contextlib.contextmanager
def cached(self):
if self._cached:
yield
else:
try:
self._cached = True
yield
finally:
self.audited.clear()
self.auditeddir.clear()
self._cached = False
Augie Fackler
formatting: blacken the codebase...
r43346
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 def canonpath(root, cwd, myname, auditor=None):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes, bytes, bytes, Optional[pathauditor]) -> bytes
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """return the canonical path of myname, given cwd and root
Matt Harbison
pathutil: add doctests for canonpath()...
r34981
>>> def check(root, cwd, myname):
... a = pathauditor(root, realfs=False)
... try:
... return canonpath(root, cwd, myname, a)
... except error.Abort:
... return 'aborted'
>>> def unixonly(root, cwd, myname, expected='aborted'):
... if pycompat.iswindows:
... return expected
... return check(root, cwd, myname)
>>> def winonly(root, cwd, myname, expected='aborted'):
... if not pycompat.iswindows:
... return expected
... return check(root, cwd, myname)
>>> winonly(b'd:\\\\repo', b'c:\\\\dir', b'filename')
'aborted'
>>> winonly(b'c:\\\\repo', b'c:\\\\dir', b'filename')
'aborted'
>>> winonly(b'c:\\\\repo', b'c:\\\\', b'filename')
'aborted'
>>> winonly(b'c:\\\\repo', b'c:\\\\', b'repo\\\\filename',
... b'filename')
'filename'
>>> winonly(b'c:\\\\repo', b'c:\\\\repo', b'filename', b'filename')
'filename'
>>> winonly(b'c:\\\\repo', b'c:\\\\repo\\\\subdir', b'filename',
... b'subdir/filename')
'subdir/filename'
>>> unixonly(b'/repo', b'/dir', b'filename')
'aborted'
>>> unixonly(b'/repo', b'/', b'filename')
'aborted'
>>> unixonly(b'/repo', b'/', b'repo/filename', b'filename')
'filename'
>>> unixonly(b'/repo', b'/repo', b'filename', b'filename')
'filename'
>>> unixonly(b'/repo', b'/repo/subdir', b'filename', b'subdir/filename')
'subdir/filename'
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 if util.endswithsep(root):
rootsep = root
else:
Pulkit Goyal
py3: replace os.sep with pycompat.ossep (part 2 of 4)...
r30614 rootsep = root + pycompat.ossep
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 name = myname
if not os.path.isabs(name):
name = os.path.join(root, cwd, name)
name = os.path.normpath(name)
if auditor is None:
auditor = pathauditor(root)
if name != rootsep and name.startswith(rootsep):
Augie Fackler
formatting: blacken the codebase...
r43346 name = name[len(rootsep) :]
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 auditor(name)
return util.pconvert(name)
elif name == root:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 return b''
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 else:
# Determine whether `name' is in the hierarchy at or beneath `root',
# by iterating name=dirname(name) until that causes no change (can't
# check name == '/', because that doesn't work on windows). The list
# `rel' holds the reversed list of components making up the relative
# file name we want.
rel = []
while True:
try:
s = util.samefile(name, root)
except OSError:
s = False
if s:
if not rel:
# name was actually the same as root (maybe a symlink)
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 return b''
Augie Fackler
pathutil: tease out a new library to break an import cycle from canonpath use
r20033 rel.reverse()
name = os.path.join(*rel)
auditor(name)
return util.pconvert(name)
dirname, basename = util.split(name)
rel.append(basename)
if dirname == name:
break
name = dirname
Matt Harbison
pathutil: hint if a path is root relative instead of cwd relative (issue4663)...
r25011 # A common mistake is to use -R, but specify a file relative to the repo
# instead of cwd. Detect that case, and provide a hint to the user.
hint = None
try:
Matt Mackall
canonpath: fix infinite recursion
r25022 if cwd != root:
canonpath(root, root, myname, auditor)
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 relpath = util.pathto(root, cwd, b'')
Yuya Nishihara
py3: use bytes.endswith() instead of bytes[n]
r38611 if relpath.endswith(pycompat.ossep):
Matt Harbison
pathutil: use util.pathto() to calculate relative cwd in canonpath()...
r34966 relpath = relpath[:-1]
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 hint = _(b"consider using '--cwd %s'") % relpath
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 except error.Abort:
Matt Harbison
pathutil: hint if a path is root relative instead of cwd relative (issue4663)...
r25011 pass
Augie Fackler
formatting: blacken the codebase...
r43346 raise error.Abort(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b"%s not under root '%s'") % (myname, root), hint=hint
Augie Fackler
formatting: blacken the codebase...
r43346 )
FUJIWARA Katsunori
subrepo: normalize path in the specific way for problematic encodings...
r21568
def normasprefix(path):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes) -> bytes
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """normalize the specified path as path prefix
FUJIWARA Katsunori
subrepo: normalize path in the specific way for problematic encodings...
r21568
Mads Kiilerich
spelling: fixes from proofreading of spell checker issues
r23139 Returned value can be used safely for "p.startswith(prefix)",
FUJIWARA Katsunori
subrepo: normalize path in the specific way for problematic encodings...
r21568 "p[len(prefix):]", and so on.
For efficiency, this expects "path" argument to be already
normalized by "os.path.normpath", "os.path.realpath", and so on.
See also issue3033 for detail about need of this function.
Yuya Nishihara
py3: use bytes os.sep in doctest of pathutil.py
r34255 >>> normasprefix(b'/foo/bar').replace(pycompat.ossep, b'/')
FUJIWARA Katsunori
subrepo: normalize path in the specific way for problematic encodings...
r21568 '/foo/bar/'
Yuya Nishihara
py3: use bytes os.sep in doctest of pathutil.py
r34255 >>> normasprefix(b'/').replace(pycompat.ossep, b'/')
FUJIWARA Katsunori
subrepo: normalize path in the specific way for problematic encodings...
r21568 '/'
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """
FUJIWARA Katsunori
subrepo: normalize path in the specific way for problematic encodings...
r21568 d, p = os.path.splitdrive(path)
Pulkit Goyal
py3: replace os.sep with pycompat.ossep (part 2 of 4)...
r30614 if len(p) != len(pycompat.ossep):
return path + pycompat.ossep
FUJIWARA Katsunori
subrepo: normalize path in the specific way for problematic encodings...
r21568 else:
return path
Durham Goode
pathutil: add dirname and join functions...
r25281
Augie Fackler
formatting: blacken the codebase...
r43346
Martin von Zweigbergk
utils: move finddirs() to pathutil...
r44032 def finddirs(path):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes) -> Iterator[bytes]
Martin von Zweigbergk
utils: move finddirs() to pathutil...
r44032 pos = path.rfind(b'/')
while pos != -1:
yield path[:pos]
pos = path.rfind(b'/', 0, pos)
yield b''
Arseniy Alekseyev
pathutil: add the more efficient finddir iterator...
r50802 def finddirs_rev_noroot(path: bytes) -> Iterator[bytes]:
pos = path.find(pycompat.ossep)
while pos != -1:
yield path[:pos]
pos = path.find(pycompat.ossep, pos + 1)
Gregory Szorc
py3: use class X: instead of class X(object):...
r49801 class dirs:
utils: move the `dirs` definition in pathutil (API)...
r43923 '''a multiset of directory names from a set of file paths'''
pathutil: replace the `skip` argument of `dirs` with a boolean...
r48756 def __init__(self, map, only_tracked=False):
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """
Josef 'Jeff' Sipek
pathutil: document that dirs map type implies manifest/dirstate processing
r45116 a dict map indicates a dirstate while a list indicates a manifest
Augie Fackler
formating: upgrade to black 20.8b1...
r46554 """
utils: move the `dirs` definition in pathutil (API)...
r43923 self._dirs = {}
addpath = self.addpath
pathutil: replace the `skip` argument of `dirs` with a boolean...
r48756 if isinstance(map, dict) and only_tracked:
Gregory Szorc
global: bulk replace simple pycompat.iteritems(x) with x.items()...
r49768 for f, s in map.items():
pathutil: replace the `skip` argument of `dirs` with a boolean...
r48756 if s.state != b'r':
utils: move the `dirs` definition in pathutil (API)...
r43923 addpath(f)
pathutil: replace the `skip` argument of `dirs` with a boolean...
r48756 elif only_tracked:
msg = b"`only_tracked` is only supported with a dict source"
raise error.ProgrammingError(msg)
utils: move the `dirs` definition in pathutil (API)...
r43923 else:
for f in map:
addpath(f)
def addpath(self, path):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes) -> None
utils: move the `dirs` definition in pathutil (API)...
r43923 dirs = self._dirs
Martin von Zweigbergk
utils: move finddirs() to pathutil...
r44032 for base in finddirs(path):
utils: move the `dirs` definition in pathutil (API)...
r43923 if base.endswith(b'/'):
raise ValueError(
"found invalid consecutive slashes in path: %r" % base
)
if base in dirs:
dirs[base] += 1
return
dirs[base] = 1
def delpath(self, path):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes) -> None
utils: move the `dirs` definition in pathutil (API)...
r43923 dirs = self._dirs
Martin von Zweigbergk
utils: move finddirs() to pathutil...
r44032 for base in finddirs(path):
utils: move the `dirs` definition in pathutil (API)...
r43923 if dirs[base] > 1:
dirs[base] -= 1
return
del dirs[base]
def __iter__(self):
return iter(self._dirs)
def __contains__(self, d):
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 # type: (bytes) -> bool
utils: move the `dirs` definition in pathutil (API)...
r43923 return d in self._dirs
if util.safehasattr(parsers, 'dirs'):
dirs = parsers.dirs
if rustdirs is not None:
dirs = rustdirs
Augie Fackler
pathutil: demote two local functions to just be forwards...
r25286 # forward two methods from posixpath that do what we need, but we'd
# rather not let our internals know that we're thinking in posix terms
# - instead we'll let them be oblivious.
join = posixpath.join
Matt Harbison
typing: add some type annotations to mercurial/pathutil.py...
r47392 dirname = posixpath.dirname # type: Callable[[bytes], bytes]