view mercurial/pathutil.py @ 46018:8b0a3ff5ed12

statprof: separate functions and "line", assume 4 digit line numbers Previously, the profile output looked like this (I've removed many lines that are mostly inconsequential): ``` | 100.0% 0.02s hg: <module> line 43: dispatch.run() | 100.0% 0.02s dispatch.py: run line 115: status = dispatch(req) | 100.0% 0.02s dispatch.py: _runcatchfunc line 432: return _dispatch(req) \ 50.0% 0.01s dispatch.py: _dispatch line 1228: return runcommand( | 50.0% 0.01s dispatch.py: runcommand line 883: ret = _runcommand(ui, optio... | 50.0% 0.01s dispatch.py: _runcommand line 1240: return cmdfunc() | 50.0% 0.01s localrepo.py: __getitem__ line 1670: quick_access = self._quick_... | 50.0% 0.01s localrepo.py: _quick_access_changeidline 1650: return self._quick_access_c... | 50.0% 0.01s localrepo.py: __get__ line 179: return getattr(unfi, self.n... | 50.0% 0.01s util.py: __get__ line 1747: result = self.func(obj) | 50.0% 0.01s localrepo.py: _quick_access_changeid_wcline 1611: cl = self.unfiltered().chan... | 50.0% 0.01s localrepo.py: __get__ line 110: return super(_basefilecache... | 50.0% 0.01s util.py: __getattribute__line 245: self.__spec__.loader.exec_m... | 50.0% 0.01s <frozen importlib._bootstrap_external>: exec_moduleline 783: | 50.0% 0.01s <frozen importlib._bootstrap>: _call_with_frames_removedline 219: | 50.0% 0.01s changelog.py: <module> line 376: class changelog(revlog.revl... | 50.0% 0.01s util.py: __getattribute__line 245: self.__spec__.loader.exec_m... | 50.0% 0.01s <frozen importlib._bootstrap_external>: exec_moduleline 779: | 50.0% 0.01s <frozen importlib._bootstrap_external>: get_codeline 868: | 50.0% 0.01s <frozen importlib._bootstrap_external>: path_statsline 1012: | 50.0% 0.01s <frozen importlib._bootstrap_external>: _path_statline 87: ``` This has a few problems, though I'm only addressing some of them. 1. If the stuff before "line ###" is long, there's no separation between the function name and the "line" string. 2. If the stuff before "line ###" is really long, there's excessive separation between the "line" string and the line number. 3. We frequently have 4-digit line numbers, the code on the right wasn't dynamically indented and ended up quite messy looking. To solve these problems, I've added a ", " prefix before "line" iff it would otherwise not have any separation such as spaces. I've added a 'max' so that we never use a negative width (which is the cause of problem #2 above), and I've added a default assumption of 4 digit line numbers (but again using a 'max' so this shouldn't cause problems if we go beyond that. With these changes, it now looks like this: ``` | 100.0% 0.02s hg: <module> line 43: dispatch.run() | 100.0% 0.02s dispatch.py: run line 115: status = dispatch(req) | 100.0% 0.02s dispatch.py: _runcatchfunc line 432: return _dispatch(req) \ 50.0% 0.01s dispatch.py: _dispatch line 1228: return runcommand( | 50.0% 0.01s dispatch.py: runcommand line 883: ret = _runcommand(ui, optio... | 50.0% 0.01s dispatch.py: _runcommand line 1240: return cmdfunc() | 50.0% 0.01s localrepo.py: __getitem__ line 1670: quick_access = self._quick_... | 50.0% 0.01s localrepo.py: _quick_access_changeid, line 1650: return self._quick_access_c... | 50.0% 0.01s localrepo.py: __get__ line 179: return getattr(unfi, self.n... | 50.0% 0.01s util.py: __get__ line 1747: result = self.func(obj) | 50.0% 0.01s localrepo.py: _quick_access_changeid_wc, line 1611: cl = self.unfiltered().chan... | 50.0% 0.01s localrepo.py: __get__ line 110: return super(_basefilecache... | 50.0% 0.01s util.py: __getattribute__, line 245: self.__spec__.loader.exec_m... | 50.0% 0.01s <frozen importlib._bootstrap_external>: exec_module, line 783: | 50.0% 0.01s <frozen importlib._bootstrap>: _call_with_frames_removed, line 219: | 50.0% 0.01s changelog.py: <module> line 376: class changelog(revlog.revl... | 50.0% 0.01s util.py: __getattribute__, line 245: self.__spec__.loader.exec_m... | 50.0% 0.01s <frozen importlib._bootstrap_external>: exec_module, line 779: | 50.0% 0.01s <frozen importlib._bootstrap_external>: get_code, line 868: | 50.0% 0.01s <frozen importlib._bootstrap_external>: path_stats, line 1012: | 50.0% 0.01s <frozen importlib._bootstrap_external>: _path_stat, line 87: ``` Differential Revision: https://phab.mercurial-scm.org/D9511
author Kyle Lippincott <spectral@google.com>
date Wed, 02 Dec 2020 12:33:51 -0800
parents 89a2afe31e82
children 5d483e3bb60e
line wrap: on
line source

from __future__ import absolute_import

import contextlib
import errno
import os
import posixpath
import stat

from .i18n import _
from . import (
    encoding,
    error,
    policy,
    pycompat,
    util,
)

rustdirs = policy.importrust('dirstate', 'Dirs')
parsers = policy.importmod('parsers')


def _lowerclean(s):
    return encoding.hfsignoreclean(s.lower())


class pathauditor(object):
    """ensure that a filesystem path contains no banned components.
    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 ".."

    More check are also done about the file system states:
    - 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)

    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.

    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.
    """

    def __init__(self, root, callback=None, realfs=True, cached=False):
        self.audited = set()
        self.auditeddir = set()
        self.root = root
        self._realfs = realfs
        self._cached = cached
        self.callback = callback
        if os.path.lexists(root) and not util.fscasesensitive(root):
            self.normcase = util.normcase
        else:
            self.normcase = lambda x: x

    def __call__(self, path, mode=None):
        """Check the relative path.
        path may contain a pattern (e.g. foodir/**.txt)"""

        path = util.localpath(path)
        normpath = self.normcase(path)
        if normpath in self.audited:
            return
        # AIX ignores "/" at end of path, others raise EISDIR.
        if util.endswithsep(path):
            raise error.Abort(_(b"path ends in directory separator: %s") % path)
        parts = util.splitpath(path)
        if (
            os.path.splitdrive(path)[0]
            or _lowerclean(parts[0]) in (b'.hg', b'.hg.', b'')
            or pycompat.ospardir in parts
        ):
            raise error.Abort(_(b"path contains illegal component: %s") % path)
        # Windows shortname aliases
        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.Abort(
                        _(b"path contains illegal component: %s") % path
                    )
        if b'.hg' in _lowerclean(path):
            lparts = [_lowerclean(p) for p in parts]
            for p in b'.hg', b'.hg.':
                if p in lparts[1:]:
                    pos = lparts.index(p)
                    base = os.path.join(*parts[:pos])
                    raise error.Abort(
                        _(b"path '%s' is inside nested repo %r")
                        % (path, pycompat.bytestr(base))
                    )

        normparts = util.splitpath(normpath)
        assert len(parts) == len(normparts)

        parts.pop()
        normparts.pop()
        # 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).
        for i in range(len(parts)):
            prefix = pycompat.ossep.join(parts[: i + 1])
            normprefix = pycompat.ossep.join(normparts[: i + 1])
            if normprefix in self.auditeddir:
                continue
            if self._realfs:
                self._checkfs(prefix, path)
            if self._cached:
                self.auditeddir.add(normprefix)

        if self._cached:
            self.audited.add(normpath)

    def _checkfs(self, prefix, path):
        """raise exception if a file system backed check fails"""
        curpath = os.path.join(self.root, prefix)
        try:
            st = os.lstat(curpath)
        except OSError as err:
            # 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):
                msg = _(b'path %r traverses symbolic link %r') % (
                    pycompat.bytestr(path),
                    pycompat.bytestr(prefix),
                )
                raise error.Abort(msg)
            elif stat.S_ISDIR(st.st_mode) and os.path.isdir(
                os.path.join(curpath, b'.hg')
            ):
                if not self.callback or not self.callback(curpath):
                    msg = _(b"path '%s' is inside nested repo %r")
                    raise error.Abort(msg % (path, pycompat.bytestr(prefix)))

    def check(self, path):
        try:
            self(path)
            return True
        except (OSError, error.Abort):
            return False

    @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


def canonpath(root, cwd, myname, auditor=None):
    """return the canonical path of myname, given cwd and root

    >>> 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'
    """
    if util.endswithsep(root):
        rootsep = root
    else:
        rootsep = root + pycompat.ossep
    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):
        name = name[len(rootsep) :]
        auditor(name)
        return util.pconvert(name)
    elif name == root:
        return b''
    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)
                    return b''
                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

        # 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:
            if cwd != root:
                canonpath(root, root, myname, auditor)
                relpath = util.pathto(root, cwd, b'')
                if relpath.endswith(pycompat.ossep):
                    relpath = relpath[:-1]
                hint = _(b"consider using '--cwd %s'") % relpath
        except error.Abort:
            pass

        raise error.Abort(
            _(b"%s not under root '%s'") % (myname, root), hint=hint
        )


def normasprefix(path):
    """normalize the specified path as path prefix

    Returned value can be used safely for "p.startswith(prefix)",
    "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.

    >>> normasprefix(b'/foo/bar').replace(pycompat.ossep, b'/')
    '/foo/bar/'
    >>> normasprefix(b'/').replace(pycompat.ossep, b'/')
    '/'
    """
    d, p = os.path.splitdrive(path)
    if len(p) != len(pycompat.ossep):
        return path + pycompat.ossep
    else:
        return path


def finddirs(path):
    pos = path.rfind(b'/')
    while pos != -1:
        yield path[:pos]
        pos = path.rfind(b'/', 0, pos)
    yield b''


class dirs(object):
    '''a multiset of directory names from a set of file paths'''

    def __init__(self, map, skip=None):
        """
        a dict map indicates a dirstate while a list indicates a manifest
        """
        self._dirs = {}
        addpath = self.addpath
        if isinstance(map, dict) and skip is not None:
            for f, s in pycompat.iteritems(map):
                if s[0] != skip:
                    addpath(f)
        elif skip is not None:
            raise error.ProgrammingError(
                b"skip character is only supported with a dict source"
            )
        else:
            for f in map:
                addpath(f)

    def addpath(self, path):
        dirs = self._dirs
        for base in finddirs(path):
            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):
        dirs = self._dirs
        for base in finddirs(path):
            if dirs[base] > 1:
                dirs[base] -= 1
                return
            del dirs[base]

    def __iter__(self):
        return iter(self._dirs)

    def __contains__(self, d):
        return d in self._dirs


if util.safehasattr(parsers, 'dirs'):
    dirs = parsers.dirs

if rustdirs is not None:
    dirs = rustdirs


# 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
dirname = posixpath.dirname