src.extra.utils

 1import logging
 2import os
 3import shutil
 4from pathlib import Path
 5import src.constants as cst
 6
 7def log_error(msg: str | Exception, logger: logging.Logger, exc = False) -> None:
 8    """
 9    Writes an error message to stdout and logfile
10    :param msg: message to log
11    :param logger: logger to write with
12    :param exc: if set to True will enable full traceback
13    """
14    print(msg)
15    if exc:
16        logger.exception(msg)
17        return
18    logger.error(f"ERROR: {msg}")
19
20def remove_arg(arg: str, args: list) -> list:
21    """
22    Remove argument from list of args. Common usage: flags parsing
23
24    :param arg: argument to remove
25    :param args: list of arguments to remove from
26    :return: list of arguments after removal
27    """
28    c_args = args.copy()
29    while arg in c_args:
30        c_args.remove(arg)
31    return c_args
32
33def create_path_obj(path: str, must_exist = True) -> Path:
34    """
35    Create pathlib.Path object from string.
36    :param path: path to create object from
37    :param must_exist: if set to True, will raise exception if path doesn't exist
38    :raise FileNotFoundError: if path doesn't exist ans must_exist set to True
39    :return: pathlib.Path object
40    """
41    path_obj = Path(path)
42    path_obj = path_obj.expanduser()
43
44    if not path_obj.exists() and must_exist:
45        raise FileNotFoundError(
46            2,
47            "File not found",
48            str(path)
49        )
50    return path_obj
51
52def write_history(obj: str):
53    """
54    Write to history file
55    :param obj: line to write to history
56    """
57    if not cst.HISTORY_PATH.exists():
58        cst.HISTORY_PATH.touch()
59    with open(cst.HISTORY_PATH, "a", encoding='utf-8') as f:
60        f.write(f"{obj}\n")
61
62def is_posix() -> bool:
63    """
64    Check if system is on posix
65    :return: True if it is on posix, False otherwise
66    """
67    return os.name == "posix"
68
69def get_terminal_dimensions() -> tuple[int, int]:
70    """
71    Get terminal dimensions
72    :return: terminal columns, terminal lines
73    """
74    try:
75        size = shutil.get_terminal_size()
76        return size.columns, size.lines
77    except OSError:
78        return 80, 24
79
80def raise_on_strict(logger, exc, strict: bool = False):
81    """
82    Raise exception if strict is True
83    :param logger: logger
84    :param exc: exception to raise
85    :param strict: will raise exc if True. Otherwise, will call log_error(exc, logger)
86    :return:
87    """
88    if strict:
89        raise exc
90    log_error(str(exc), logger)
def log_error(msg: str | Exception, logger: logging.Logger, exc=False) -> None:
 8def log_error(msg: str | Exception, logger: logging.Logger, exc = False) -> None:
 9    """
10    Writes an error message to stdout and logfile
11    :param msg: message to log
12    :param logger: logger to write with
13    :param exc: if set to True will enable full traceback
14    """
15    print(msg)
16    if exc:
17        logger.exception(msg)
18        return
19    logger.error(f"ERROR: {msg}")

Writes an error message to stdout and logfile

Parameters
  • msg: message to log
  • logger: logger to write with
  • exc: if set to True will enable full traceback
def remove_arg(arg: str, args: list) -> list:
21def remove_arg(arg: str, args: list) -> list:
22    """
23    Remove argument from list of args. Common usage: flags parsing
24
25    :param arg: argument to remove
26    :param args: list of arguments to remove from
27    :return: list of arguments after removal
28    """
29    c_args = args.copy()
30    while arg in c_args:
31        c_args.remove(arg)
32    return c_args

Remove argument from list of args. Common usage: flags parsing

Parameters
  • arg: argument to remove
  • args: list of arguments to remove from
Returns

list of arguments after removal

def create_path_obj(path: str, must_exist=True) -> pathlib._local.Path:
34def create_path_obj(path: str, must_exist = True) -> Path:
35    """
36    Create pathlib.Path object from string.
37    :param path: path to create object from
38    :param must_exist: if set to True, will raise exception if path doesn't exist
39    :raise FileNotFoundError: if path doesn't exist ans must_exist set to True
40    :return: pathlib.Path object
41    """
42    path_obj = Path(path)
43    path_obj = path_obj.expanduser()
44
45    if not path_obj.exists() and must_exist:
46        raise FileNotFoundError(
47            2,
48            "File not found",
49            str(path)
50        )
51    return path_obj

Create pathlib.Path object from string.

Parameters
  • path: path to create object from
  • must_exist: if set to True, will raise exception if path doesn't exist :raise FileNotFoundError: if path doesn't exist ans must_exist set to True
Returns

pathlib.Path object

def write_history(obj: str):
53def write_history(obj: str):
54    """
55    Write to history file
56    :param obj: line to write to history
57    """
58    if not cst.HISTORY_PATH.exists():
59        cst.HISTORY_PATH.touch()
60    with open(cst.HISTORY_PATH, "a", encoding='utf-8') as f:
61        f.write(f"{obj}\n")

Write to history file

Parameters
  • obj: line to write to history
def is_posix() -> bool:
63def is_posix() -> bool:
64    """
65    Check if system is on posix
66    :return: True if it is on posix, False otherwise
67    """
68    return os.name == "posix"

Check if system is on posix

Returns

True if it is on posix, False otherwise

def get_terminal_dimensions() -> tuple[int, int]:
70def get_terminal_dimensions() -> tuple[int, int]:
71    """
72    Get terminal dimensions
73    :return: terminal columns, terminal lines
74    """
75    try:
76        size = shutil.get_terminal_size()
77        return size.columns, size.lines
78    except OSError:
79        return 80, 24

Get terminal dimensions

Returns

terminal columns, terminal lines

def raise_on_strict(logger, exc, strict: bool = False):
81def raise_on_strict(logger, exc, strict: bool = False):
82    """
83    Raise exception if strict is True
84    :param logger: logger
85    :param exc: exception to raise
86    :param strict: will raise exc if True. Otherwise, will call log_error(exc, logger)
87    :return:
88    """
89    if strict:
90        raise exc
91    log_error(str(exc), logger)

Raise exception if strict is True

Parameters
  • logger: logger
  • exc: exception to raise
  • strict: will raise exc if True. Otherwise, will call log_error(exc, logger)
Returns