Welcome to BMO

find_program(name, hints=[], recursive=False)

where is a given binary

Source code in bmo/common.py
42
43
44
45
46
47
48
49
50
51
52
53
54
def find_program(
    name: str, hints: T.List[T.Union[Path, str]] = [], recursive: bool = False
) -> T.Optional[str]:
    """where is a given binary"""
    for hint in hints:
        hint = Path(hint).resolve()
        if not hint.exists():
            continue
        for p in glob.glob(f"{hint}/**/{name}", recursive=recursive):
            prg  = shutil.which(p)
            if prg is not None:
                return prg
    return shutil.which(name)

is_windows(cygwin_is_windows=True)

Check if we are running on windows.

Parameters

cygwin_is_windows : (default `True`). When set to `True`, consider cygwin as Windows.

Returns

True if on Windows, False otherwise.

Source code in bmo/common.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def is_windows(cygwin_is_windows: bool = True) -> bool:
    """Check if we are running on windows.

    Parameters
    ----------
        cygwin_is_windows : (default `True`). When set to `True`, consider cygwin as Windows.

    Returns
    -------
    `True` if on Windows, `False` otherwise.
    """
    _sys = system()
    if _sys[0].startswith("windows"):
        return True
    return cygwin_is_windows and _sys[1] == "cygwin"

run_command(cmd, cwd=Path.cwd(), silent=False, stream=True)

Run a given command.

Parameters

str

cmd

Path

Current working directory.

bool

If True, output is not printed onto console.

bool

If True the output is printed line by line eagerly (as soon as a line is available) rather than all at once.

Returns

str

Credits

  1. https://stackoverflow.com/questions/18421757/live-output-from-subprocess-command
Source code in bmo/common.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def run_command(
    cmd: str, cwd: Path = Path.cwd(), silent: bool = False, stream: bool = True
) -> str:
    """Run a given command.

    Parameters
    ----------
    cmd : str
        cmd
    cwd : Path
        Current working directory.
    silent : bool
        If `True`, output is not printed onto console.
    stream : bool
        If `True` the output is printed line by line eagerly (as soon as a line is available)
        rather than all at once.

    Returns
    -------
    str

    Credits
    --------
    1. https://stackoverflow.com/questions/18421757/live-output-from-subprocess-command
    """
    logging.debug(f"Running `{cmd}` in {cwd}")
    p = subprocess.Popen(
        cmd.split(),
        cwd=cwd,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    lines = []
    if p.stdout is not None:
        for line in iter(p.stdout.readline, ""):
            if line is None:
                break
            line = line.rstrip()
            lines.append(f"> {line}")
            if stream and not silent:
                typer.echo(f"> {line}")

    output = "\n".join(lines)
    if not silent and not stream:
        typer.echo(f"> {output}")
    return output

search_pat(pat, haystack)

Search for a pattern in haystack.

Source code in bmo/common.py
106
107
108
109
110
def search_pat(pat, haystack):
    """Search for a pattern in haystack."""
    import re

    return re.search(pat, haystack, flags=re.IGNORECASE)

download_and_run_script(script, force=False, download_only=False)

Download a script from https://gitlab.subcom.tech/open/scripts repo and execute it..

Parameters

str

The name or the full URL of the script.

bool

When set to True, redownload the script even if it exists in the cache.

download_only

When set to True, only download the script and do not execute it.

Returns

True on success. False otherwise.

Source code in bmo/subcom.py
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
@app.command("script")
def download_and_run_script(
    script: str, force: bool = False, download_only: bool = False
) -> str:
    """Download a script from https://gitlab.subcom.tech/open/scripts repo and execute it..

    Parameters
    ----------
    script : str
        The name or the full URL of the script.
    force : bool
        When set to `True`, redownload the script even if it exists in the cache.
    download_only:
        When set to `True`, only download the script and do not execute it.

    Returns
    -------
    `True` on success. `False` otherwise.

    """
    SCRIPT_DIR = Path(tempfile.gettempdir()) / "bmo"
    SCRIPT_DIR.mkdir(parents=True, exist_ok=True)
    REPO_URL = "https://gitlab.subcom.tech/open/scripts/"

    if "https://" not in script[-10:] or "http://" not in script[-10:]:
        # Example: https://gitlab.subcom.tech/open/scripts/-/raw/main/bootstrap_debian.sh
        script = f"{REPO_URL}/-/raw/main/{script}"

    scriptname: str = script.rsplit("/", maxsplit=1)[-1]
    scriptpath = SCRIPT_DIR / scriptname
    if not scriptpath.exists() or force:
        res = requests.get(script)
        if res.status_code != 200:
            logging.warning("Failed to download '{script}'. Please check the repository {REPO_URL}")
            return ""
        with open(scriptpath, "w") as f:
            f.write(res.text)

    if download_only:
        with scriptpath.open() as f:
            return f.read()

    output = run_command(f"bash -c {scriptpath}")
    print(output)
    return output