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

# %% auto 0
__all__ = ['path2str', 'aspath', 'fullpath', 'joinpaths', 'selfpath', 'fspath', 'mkdirs', 'relparts', 'ls', 'dirdirs', 'pathsort',
           'rebase', 'dirfile', 'text2clip', 'maketemp']

# %% ../nbs/01_util.ipynb 5
import os
from pathlib import Path

try: import atexit, tempfile
except: ...

# %% ../nbs/01_util.ipynb 7
from quac import pathlike, boolq
from nchr import DOT, NIL
from nlit import (PATH, PBCOPY, CLIP, ECHO, POSIX, NT, __FSPATH__, )
from chck import isfile, isdir, isnone

# %% ../nbs/01_util.ipynb 9
#| export

# %% ../nbs/01_util.ipynb 12
def path2str(path: pathlike, failsafe: boolq = True) -> str:
    if issubclass(type(path), os.PathLike): return str(path.__fspath__())
    elif hasattr(path, __FSPATH__):         return str(path.__fspath__())
    elif hasattr(path, PATH):               return path2str(path.path)
    elif isinstance(path, str):             return path
    elif failsafe:                          return DOT
    else: raise ValueError(f'path2str: path {path} not recognized')

# %% ../nbs/01_util.ipynb 13
def aspath(path) -> Path:
    return Path(path2str(path))

# %% ../nbs/01_util.ipynb 14
def fullpath(path) -> Path:
    return aspath(path).expanduser().absolute()

def joinpaths(*paths) -> Path: 
    return fullpath(os.path.join(*(paths or (DOT,))))

# %% ../nbs/01_util.ipynb 15
def selfpath(self, path) -> os.PathLike: 
    return type(self)(fullpath(path))

# %% ../nbs/01_util.ipynb 16
def fspath(path: pathlike) -> str:
    path = os.fspath(path) if isinstance(path, Path) else path
    return path

# %% ../nbs/01_util.ipynb 18
def mkdirs(dirs: list[Path], mode: int = 511, parents: bool = True, exist_ok: bool = True):
    kwargs = dict(mode=mode, parents=parents, exist_ok=exist_ok)
    for d in dirs:
        if not (d.exist() and d.is_dir()): d.mkdir(**kwargs)

# %% ../nbs/01_util.ipynb 19
def relparts(path: Path, relpath: Path = None, exclude: set = {}) -> set:
    try: parts = (path := Path(path)).relative_to(relpath).parts
    except ValueError: parts = path.parts
    return set(parts) ^ set(exclude)

# %% ../nbs/01_util.ipynb 21
def ls(path: Path) -> list:
    return list(fullpath(path).iterdir())

# %% ../nbs/01_util.ipynb 22
def dirdirs(path: Path) -> list[Path]:
    return list(filter(isdir, map(lambda e: Path(path) / Path(e), ls(path))))

# %% ../nbs/01_util.ipynb 23
def pathsort(path: Path, dir1st: bool = True) -> list:
    return sorted(ls(path), key=lambda p: (dir1st ^ (not isfile(p)), p.name.lower()))

# %% ../nbs/01_util.ipynb 25
def rebase(file: Path, root: Path = None) -> Path:
    '''Keep file name, but change root.'''
    if isnone(root): return file
    return aspath(root) / aspath(file).name

# %% ../nbs/01_util.ipynb 27
def dirfile(path: Path) -> tuple[Path, str]:
    path = fullpath(path)
    return path.parent, path.name

# %% ../nbs/01_util.ipynb 29
def text2clip(text: str) -> None:
    piped = PBCOPY
    
    # macOS and Linux
    if os.name == POSIX: ...        
    # Windows
    elif os.name == NT: piped = CLIP
    else: raise OSError('Unsupported operating system')
    command = f'{ECHO} "{text}" | {piped}'
    os.system(command)

# %% ../nbs/01_util.ipynb 31
def maketemp(**kwargs) -> tempfile.NamedTemporaryFile:
    temp = tempfile.NamedTemporaryFile(**kwargs)
    @atexit.register
    def delete_temp() -> None:
        temp.close()
    return temp
