0
  C   ˆl–äY>”JeJe@†à¸Û*bÑ¿�þYï,Ü¡p¬ˆ$‘¦�üÿÂ„šhÁ_ŠI|¥�+Wé3ž¯ÁÀ 0˜    import contextlib
import errno
import os
import posixpath
import stat

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

if pycompat.TYPE_CHECKING:
    from typing import (
        Any,
        Callable,
        Iterator,
        Optional,
    )


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


def _lowerclean(s):
    # type: (bytes) -> bytes
    return encoding.hfsignoreclean(s.lower())


class pathauditor:
    """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):
        # type: (bytes, Optional[Any]) -> 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.InputError(
                _(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.InputError(
                _(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.InputError(
                        _(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.InputError(
                        _(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 