Skip to content
Snippets Groups Projects
Select Git revision
  • cc5f3e17786e82adb3f6a99b13fa10c11d804d0f
  • main default protected
2 results

utils.py

Blame
  • sedrubal's avatar
    cc5f3e17
    History
    utils.py 1.81 KiB
    """Utils."""
    
    import argparse
    import os
    import sys
    from pathlib import Path
    from typing import Optional
    
    from termcolor import cprint
    from yaspin import yaspin
    
    
    class YaspinWrapper:
        def __init__(self, debug: bool, text: str, color: str):
            self.debug = debug
            self.text = text
            self.color = color
    
            if not debug:
                self.yaspin = yaspin(text=text, color=color)
    
        def __enter__(self):
            if self.debug:
                cprint(self.text, color=self.color)
            else:
                self.yaspin.__enter__()
    
            return self
    
        def __exit__(self, *args, **kwargs):
            if self.debug:
                pass
            else:
                self.yaspin.__exit__(*args, **kwargs)
    
        def ok(self, text: str):
            if self.debug:
                print(text)
            else:
                self.yaspin.ok(text)
    
        def fail(self, text: str):
            if self.debug:
                print(text, file=sys.stderr)
            else:
                self.yaspin.fail(text)
    
    
    def create_relpath(path1: Path, path2: Optional[Path] = None) -> Path:
        """Create a relative path for path1 relative to path2."""
    
        if not path2:
            path2 = Path(".")
    
        path1 = path1.absolute()
        path2 = path2.absolute()
    
        common_prefix = Path(os.path.commonprefix((path1, path2)))
    
        return Path(os.path.relpath(path1, common_prefix))
    
    
    def existing_file_path(value: str, allow_none=False) -> Optional[Path]:
        if not value or value.lower() == "none":
            if allow_none:
                return None
            else:
                raise argparse.ArgumentTypeError("`none` is not allowed here.")
    
        path = Path(value)
    
        if path.is_dir():
            raise argparse.ArgumentTypeError(f"{value} is a directory. A file is required.")
    
        elif not path.is_file():
            raise argparse.ArgumentTypeError(f"{value} does not exist.")
    
        return path