# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/mxns/01_plib.ipynb.

# %% auto 0
__all__ = ['PathLibMixin']

# %% ../../nbs/mxns/01_plib.ipynb 6
import os, pathlib, tempfile, unittest

# %% ../../nbs/mxns/01_plib.ipynb 8
from typing import Callable, Optional

# %% ../../nbs/mxns/01_plib.ipynb 10
from nchr import DOT
from nlit import PATH
from pstr.util import toprivate

# %% ../../nbs/mxns/01_plib.ipynb 12
#| export

# %% ../../nbs/mxns/01_plib.ipynb 14
_PATH = toprivate(PATH)

# %% ../../nbs/mxns/01_plib.ipynb 15
class PathLibMixin(str, os.PathLike):
    # ---------------------------------------------------------------------------------------------------------
    # Is type
    # ---------------------------------------------------------------------------------------------------------
    def is_dir(self) -> bool:
        """Whether this path is a directory."""
        return self.path.is_dir()
    
    def is_file(self) -> bool:
        """Whether this path is a regular file (also True for symlinks pointing to regular files)."""
        return self.path.is_file()
    
    def is_fifo(self) -> bool:
        """Whether this path is a FIFO."""
        return self.path.is_fifo()
    
    def is_mount(self) -> bool:
        """Check if this path is a mount point"""
        return self.path.is_mount()
    
    def is_socket(self) -> bool:
        """Whether this path is a socket."""
        return self.path.is_socket()
    
    def is_symlink(self) -> bool:
        """Whether this path is a symbolic link."""
        return self.path.is_symlink()
    
    def is_junction(self) -> bool:
        """Whether this path is a junction."""
        return self.path.is_junction()
    
    def is_char_device(self) -> bool:
        """Whether this path is a character device."""
        return self.path.is_char_device()
    
    def is_block_device(self) -> bool:
        """Whether this path is a block device."""
        return self.path.is_block_device()
    
    # ---------------------------------------------------------------------------------------------------------
    # Properties
    # ---------------------------------------------------------------------------------------------------------
    @property
    def root(self):
        """The root of the path, if any."""
        return self.path.root
    
    @property
    def name(self):
        """The final path component, if any."""
        return self.path.name
    
    @property
    def stem(self):
        """The final path component, minus its last suffix."""
        return self.path.stem
    
    @property
    def drive(self):
        """The drive prefix (letter or UNC path), if any."""
        return self.path.drive
    
    @property
    def parts(self):
        """An object providing sequence-like access to the
        components in the filesystem path."""
        return self.path.parts
    
    @property
    def anchor(self):
        """The concatenation of the drive and root, or ''."""
        return self.path.anchor
    
    @property
    def suffix(self):
        """
        The final component's last suffix, if any.

        This includes the leading period. For example: '.txt'
        """
        return self.path.suffix
    
    @property
    def parent(self):
        """The logical parent of the path."""
        return self.path.parent
    
    @property
    def parents(self):
        """A sequence of this path's logical parents."""
        return self.path.parents
    
    @property
    def suffixes(self):
        """A list of the final component's suffixes, if any.
        These include the leading periods. For example: ['.tar', '.gz']
        """
        return self.path.suffixes
    
    @property
    def _flavour(self): return self.path._flavour
    
    # ---------------------------------------------------------------------------------------------------------
    # Methods
    # ---------------------------------------------------------------------------------------------------------
    def ls(self, n_max=None, file_type=None, file_exts=None): 
        return self.path.ls(n_max, file_type, file_exts)

    @classmethod
    def cwd(cls):
        """Return a new path pointing to the current working directory."""
        return cls(pathlib.Path.cwd())
    
    def open(
        self, mode: str = 'r', buffering: int = -1, encoding: Optional[str] = None,
        errors: Optional[str] = None, newline: Optional[str] = None
    ):
        """
        Open the file pointed by this path and return a file object, as
        the built-in open() function does.
        """
        return self.path.open(mode, buffering, encoding, errors, newline)
    
    def glob(self, pattern):
        """Iterate over this subtree and yield all existing files (of any
        kind, including directories) matching the given relative pattern.
        """
        return self.path.glob(pattern)
    
    @classmethod
    def home(cls):
        """Return a new path pointing to the user's home directory (as
        returned by os.path.expanduser('~')).
        """
        return cls(cls().path.home())
    
    def walk(self, top_down: bool = True, on_error: Optional[Callable] = None, follow_symlinks: bool  = False):
        """Walk the directory tree from this directory, similar to os.walk()."""
        return self.path.walk(top_down, on_error, follow_symlinks)
    
    def stat(self):
        """
        Return the result of the stat() system call on this path, like
        os.stat() does.
        """
        return self.path.stat()

    def lstat(self):
        """
        Like stat(), except if the path points to a symlink, the symlink's
        status information is returned, rather than its target's.
        """
        return self.path.lstat()
    
    def rmdir(self):
        """
        Remove this directory.  The directory must be empty.
        """
        return self.path.rmdir()
    
    def touch(self, mode: int = 438, exist_ok: bool = True):
        """
        Create this file with the given access mode, if it doesn't exist.
        """
        return self.path.touch(mode, exist_ok)
    
    def mkdir(self, mode: int = 511, parents: bool = False, exist_ok: bool = False):
        """
        Create a new directory at this given path.
        """
        return self.path.mkdir(mode, parents, exist_ok)
    
    def chmod(self, mode):
        """
        Change the permissions of the path, like os.chmod().
        """
        return self.path.chmod(mode)
    
    def owner(self):
        """
        Return the login name of the file owner.
        """
        return self.path.owner()
    
    def group(self):
        """
        Return the group name of the file gid.
        """
        return self.path.group()
    
    def rglob(self, pattern):
        """Recursively yield all existing files (of any kind, including
        directories) matching the given relative pattern, anywhere in
        this subtree.
        """
        return self.path.rglob(pattern)
    
    def match(self, pattern):
        """
        Return True if this path matches the given pattern.
        """
        return self.path.match(pattern)

    def delete(self): return self.path.delete()

    def lchmod(self, mode):
        """
        Like chmod(), except if the path points to a symlink, the symlink's
        permissions are changed, rather than its target's.
        """
        return self.path.lchmod(mode)
    
    def rename(self, target):
        """
        Rename this path to the target path.

        The target path may be absolute or relative. Relative paths are
        interpreted relative to the current working directory, *not* the
        directory of the Path object.

        Returns the new Path instance pointing to the target path.
        """
        return type(self)(self.path.rename(target))
    
    def unlink(self):
        """
        Remove this file or link.
        If the path is a directory, use rmdir() instead.
        """
        return self.path.unlink()
    
    def exists(self):
        """
        Whether this path exists.

        This method normally follows symlinks; to check whether a symlink exists,
        add the argument follow_symlinks=False.
        """
        return self.path.exists()
    
    def as_uri(self):
        """Return the path as a 'file' URI."""
        return self.path.as_uri()
    
    def resolve(self):
        """
        Make the path absolute, resolving all symlinks on the way and also
        normalizing it.
        """
        return type(self)(pathlib.Path(self).resolve())
    
    def link_to(self, target: pathlib.Path): return self.path.link_to(target)

    def relpath(self, start: Optional[pathlib.Path] = None): return self.path.relpath(start)

    def replace(self, target):
        """
        Rename this path to the target path, overwriting if that path exists.

        The target path may be absolute or relative. Relative paths are
        interpreted relative to the current working directory, *not* the
        directory of the Path object.

        Returns the new Path instance pointing to the target path.
        """
        return self.path.replace(target)
    
    def iterdir(self):
        """Yield path objects of the directory contents.

        The children are yielded in arbitrary order, and the
        special entries '.' and '..' are not included.
        """
        return self.path.iterdir()
    
    def as_posix(self) -> str:
        """Return the string representation of the path with forward (/)
        slashes."""
        return self.path.as_posix()
    
    def samefile(self, other):
        """Return whether other_path is the same or not as this file
        (as returned by os.path.samefile()).
        """
        return self.path.samefile(other)
    
    def joinpath(self, *other):
        """Combine this path with one or several arguments, and return a
        new path representing either a subpath (if all arguments are relative
        paths) or a totally different path (if one of the arguments is
        anchored).
        """
        return self.path.joinpath(*other)
    
    def mk_write(self, data, encoding: Optional[str] = None, errors: Optional[list] = None, mode: int = 511): 
        return self.path.mk_write(data, encoding, errors, mode)   
     
    def absolute(self):
        """Return an absolute version of this path by prepending the current
        working directory. No normalization or symlink resolution is performed.

        Use resolve() to get the canonical path to a file.
        """
        return type(self)(self.path.absolute())
    
    def readlink(self):
        """
        Return the path to which the symbolic link points.
        """
        return self.path.readlink()
    
    def _scandir(self): return self.path._scandir()

    def with_name(self, name):
        """Return a new path with the file name changed."""
        return type(self)(self.path.with_name(name))
    
    def with_stem(self, stem):
        """Return a new path with the stem changed."""
        return type(self)(self.path.with_stem(stem))
    
    def read_text(self, *args, **kwargs):
        """
        Open the file in text mode, read it, and close the file.
        """
        return self.path.read_text(*args, **kwargs)
    
    def read_json(self, encoding: Optional[str] = None, errors: Optional[list] = None): 
        return self.path.read_json(encoding, errors)

    def readlines(self, hint: int = -1, encoding: str = 'utf8'): 
        return self.path.readlines(hint, encoding)
    
    def with_segments(self, *segments):
        """Construct a new path object from any number of path-like objects.
        Subclasses may override this method to customize how new path objects
        are created from methods like `iterdir()`.
        """
        return type(self)(self.path.with_segments(*segments))

    def expanduser(self):
        """ Return a new path with expanded ~ and ~user constructs
        (as returned by os.path.expanduser)
        """
        return type(self)(self.path.expanduser())
    
    def read_bytes(self):
        """
        Open the file in bytes mode, read it, and close the file.
        """
        return self.path.read_bytes()
    
    def symlink_to(self, target, target_is_directory):
        """
        Make this path a symlink pointing to the target path.
        Note the order of arguments (link, target) is the reverse of os.symlink.
        """
        return self.path.symlink_to(target, target_is_directory)
    
    def write_text(self, data, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None):
        """
        Open the file in text mode, write to it, and close the file.
        """
        return self.path.write_text(data, encoding, errors, newline)

    def is_absolute(self) -> bool:
        """True if the path is absolute (has both a root and, if applicable,
        a drive)."""
        return self.path.is_absolute()
    
    def is_reserved(self) -> bool:
        """Return True if the path contains one of the special names reserved
        by the system, if any."""
        return self.path.is_reserved()
    
    def write_bytes(self, data):
        """
        Open the file in bytes mode, write to it, and close the file.
        """
        return self.path.write_bytes(data)
    
    def with_suffix(self, suffix):
        """Return a new path with the file suffix changed.  If the path
        has no suffix, add given suffix.  If the given suffix is an empty
        string, remove the suffix from the path.
        """
        return self.path.with_suffix(suffix)
    
    def relative_to(self, *other): 
        """Return the relative path to another path identified by the passed
        arguments.  If the operation is not possible (because this is not
        related to the other path), raise ValueError.

        The *walk_up* parameter controls whether `..` may be used to resolve
        the path.
        """
        return self.path.relative_to(*other)
    
    def hardlink_to(self, target):
        """
        Make this path a hard link pointing to the same file as *target*.

        Note the order of arguments (self, target) is the reverse of os.link's.
        """
        return self.path.hardlink_to(target)
    
    def is_relative_to(self, *other) -> bool:
        """Return True if the path is relative to another path or False."""
        return self.path.is_relative_to(*other)
    
    
    def _make_child_relpath(self, part): 
        return self.path._make_child_relpath(part)

    @classmethod
    def _parse_args(cls, args):
        return cls(pathlib.Path._parse_args(args))
            
    @classmethod
    def _from_parsed_parts(cls, drv, root, parts):        
        return cls(pathlib.Path._from_parsed_parts(drv, root, parts))
        
    @classmethod
    def _format_parsed_parts(cls, drv, root, parts):
        return cls(pathlib.Path._format_parsed_parts(drv, root, parts))

    def __eq__(self, other): 
        return self.path.__eq__(other)
        return self == aspath(other)

    def __lt__(self, other): 
        return self.path.__lt__(other)
        return self <  aspath(other)

    def __le__(self, other): 
        return self.path.__le__(other)
        return self <= aspath(other)

    def __gt__(self, other): 
        return self.path.__gt__(other)
        return self >  aspath(other)

    def __ge__(self, other): 
        return self.path.__ge__(other)
        return self >= aspath(other)


    def __hash__(self): return self.path.__hash__()

    def __bytes__(self):
        """Return the bytes representation of the path.  This is only
        recommended to use under Unix."""
        return self.path.__bytes__()
    
    def __fspath__(self): return self.path.__fspath__()

    def __reduce__(self): return (type(self), ) + self.path.__reduce__()

    def __truediv__(self, other): 
        return type(self)(self.path.__truediv__(other))

    def __rtruediv__(self, other): 
        return type(self)(self.path.__rtruediv__(other))

    def __new__(cls, path: Optional[str] = None, *args, **kwargs):
        obj = super().__new__(cls, (path or DOT))
        obj.path = pathlib.Path(obj)
        return obj
    
    def __init__(self, path = None, *args, **kwargs):
        ...
        self.path = pathlib.Path(path or self)

    @property 
    def path(self) -> pathlib.Path: return pathlib.Path(self or DOT)
    @property 
    def path(self) -> pathlib.Path: return getattr(self, _PATH, pathlib.Path(DOT))
    @path.setter
    def path(self, path: str): setattr(self, _PATH, pathlib.Path(path))
    
    @property
    def clsname(self): return type(self).__name__
    
    def __str__(self): return super().__str__()
    
    def __repr__(self): 
        return f'{self.clsname}({self.path})'
