Skip to content
Snippets Groups Projects
os.py 1.49 KiB
Newer Older
#!/usr/bin/env python3

"""EnvSetup system utilities."""

from configparser import ConfigParser
from pathlib import Path
Nicolas KAROLAK's avatar
Nicolas KAROLAK committed
import re

SUPPORTED_PLATFORMS = (("debian", "10"), ("ubuntu", "18.04"))


def get_dir(file_path: str) -> str:
    """Get the absolute directory path for the given file.

    :param file_path: File path
    :type file_path: str
    :return: Absolute directory path
    :rtype: str
    """

    return str(Path(file_path).expanduser().resolve().parent)


def dist() -> tuple:
    """Return distribution name and version).

    :return: Distribution name and version
    :rtype: tuple
    """

    parser = ConfigParser()
    with open("/etc/os-release") as os_release:
        parser.read_string("[os]\n{}".format(os_release.read()))

    return (parser["os"]["ID"], parser["os"]["VERSION_ID"].strip('"'))


def supported_platform() -> bool:
    """Let you know if the current platform is supported.

    :return: Wether the platform is supported or not
    :rtype: bool
    """

    return dist() in SUPPORTED_PLATFORMS
Nicolas KAROLAK's avatar
Nicolas KAROLAK committed


def line_in_file(line: str, file: str) -> bool:
    """Search for a line in the given file.

    :param line: String or pattern to search
    :type line: str
    :param file: File to check
    :type file: str
    :return: Wether the line is present or not
    :rtype: bool
    """

    with open(file) as fh:
        file_lines = fh.readlines()

    regex = re.compile(line)

    for file_line in file_lines:
        if regex.match(file_line):
            return True

    return False