File: util.py

package info (click to toggle)
virtme-ng 1.40-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 616 kB
  • sloc: python: 5,185; sh: 518; makefile: 34
file content (67 lines) | stat: -rw-r--r-- 1,701 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- mode: python -*-
# util.py: Misc helpers
# Copyright © 2014-2019 Andy Lutomirski
# Licensed under the GPLv2, which is available in the virtme distribution
# as a file called LICENSE with SHA-256 hash:
# 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643

import getpass
import itertools
import os
import shutil
from collections.abc import Sequence


class SilentError(Exception):
    pass


def get_username():
    """Reliably get current username."""
    try:
        username = getpass.getuser()
    except OSError:
        # If getpass.getuser() fails, try alternative methods
        username = os.getenv("USER") or os.getenv("LOGNAME")
    return username


def check_kernel_repo():
    if not os.path.isfile("scripts/kconfig/merge_config.sh") and not os.path.isfile(
        "source/scripts/kconfig/merge_config.sh"
    ):
        return False
    return True


def find_binary(
    names: Sequence[str], root: str = "/", use_path: bool = True
) -> str | None:
    dirs = [
        os.path.join(*i)
        for i in itertools.product(["usr/local", "usr", ""], ["bin", "sbin"])
    ]

    for n in names:
        if use_path:
            # Search PATH first
            path = shutil.which(n)
            if path is not None:
                return path

        for d in dirs:
            path = os.path.join(root, d, n)
            if os.path.isfile(path):
                return path

    # We give up.
    return None


def find_binary_or_raise(
    names: Sequence[str], root: str = "/", use_path: bool = True
) -> str:
    ret = find_binary(names, root=root, use_path=use_path)
    if ret is None:
        raise RuntimeError(f"Could not find {names!r}")
    return ret