Passed
Push — main ( d04581...8c2a60 )
by J
07:57
created

dvnv.utils.check_dir()   A

Complexity

Conditions 3

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 13
rs 10
c 0
b 0
f 0
cc 3
nop 1
1
# -*- coding: utf-8 -*-
2
"""utilities that would clutter the main file"""
3
import sys
4
from pathlib import Path
5
from typing import Union
6
7
from rich import print
8
9
10
def check_dir(dir_path: Path) -> bool:
11
    """Checks if the a directory exists and has files
12
13
    Args:
14
        dir_path: The directory to check for runnable scripts
15
16
    Returns:
17
        bool: True for success, False otherwise
18
    """
19
    if not dir_path.exists() or is_empty(dir_path):
20
        dir_path.mkdir(parents=True, exist_ok=True)
21
        return False
22
    return True
23
24
25
def clean_input(prompt: str) -> str:
26
    """Returns user input to a prompt, casefolded and stripped of whitespace
27
28
    Args:
29
        prompt: The prompt to display to the user
30
31
    Returns:
32
        str: The user's input to the prompt
33
    """
34
    return input(prompt).casefold().strip()
35
36
37
def confirm(prompt: str = None) -> bool:
38
    """Confirms a choice made by the user
39
40
    Args:
41
        prompt: The prompt to display to the user (default is None)
42
43
    Returns:
44
        bool: True if the user entered 'y' or 'yes', False otherwise
45
    """
46
    if not prompt:
47
        prompt = "Does this information look correct? [Y/n] "
48
    return clean_input(prompt) in ("y", "yes")
49
50
51
def is_empty(path: Path) -> bool:
52
    """Checks if a directory has files
53
54
    Args:
55
        path: The path to the directory to check
56
57
    Returns:
58
        bool: True if the dir is empty, False if it contains any files
59
    """
60
    return not any(path.iterdir())
61
62
63
def print_error(msg: Union[str, Exception], header: str = "ERR") -> None:
64
    """Prints a message to stderr
65
66
    Args:
67
        msg: The message to print to stderr
68
        header: The string to print before the actual message
69
    """
70
    if header == "ERR":
71
        msg = f"[red][{header}][/red] {msg}"
72
    else:
73
        msg = f"[orange1][{header}][/orange1] {msg}"
74
    print(msg, file=sys.stderr)
75