Welcome to BMO

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

where is a given binary

Source code in bmo/common.py
76
77
78
79
80
81
82
83
84
85
86
87
88
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
140
141
142
143
144
def search_pat(pat, haystack):
    """Search for a pattern in haystack."""
    import re

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

weekly_email(to=typer.Option(...), config=typer.Option(..., callback=bmo.common.conf_callback, is_eager=True), notion_token=typer.Option(...), smtp_server=typer.Option(...), smtp_port=typer.Option(...), smtp_username=typer.Option(...), smtp_password=typer.Option(...), force=typer.Option(False, '--force'))

This week in SubCom delivered to your INBOX.

Source code in bmo/subcom/__init__.py
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
68
69
70
71
72
73
74
75
@app.command()
def weekly_email(
    to: str = typer.Option(...),
    config: str = typer.Option(..., callback=bmo.common.conf_callback, is_eager=True),
    notion_token: str = typer.Option(...),
    smtp_server: str = typer.Option(...),
    smtp_port: int = typer.Option(...),
    smtp_username: str = typer.Option(...),
    smtp_password: str = typer.Option(...),
    force: bool = typer.Option(False, "--force"),
):
    """This week in SubCom delivered to your INBOX."""
    if not notion_token:
        logging.error("Empty token. Add `--help` to usage.")
        return

    if datetime.today().weekday() != 0 and not force:
        logging.warning("Totay is not Monday. Use `--force` to override.")
        return

    notion = bmo.helpers.notion.Notion(notion_token)

    html = """<p>Greetings, puny Humans! I am <a
    href='https://github.com/SubconsciousCompute/bmo'>Subconscious BMO</a>. 
    I automate stuff. I found some stuff that happened at SubCom last week. Missing
    something? Let <a href='webmaster@subcom.tech'>webmaster@subcom.tech</a> know!</p>"""

    html += notion.weekly_update()
    html += "<p>-- <br /> 🎔 Subconscious BMO</p>"

    # create an email and send it. Don't send duplicates.
    emaildir = Path.home() / ".cache" / "bmo"
    h = bmo.common.hash256(html.encode())
    hfile = emaildir / h
    if hfile.exists():
        logging.warn("Email already sent.")
        return

    sender_email = smtp_username
    weekno = datetime.today().isocalendar()[1]
    subject = f"SubCom Weekly #{weekno}"
    envelope = Envelope(
        from_addr=(sender_email, "Subconscious BMO"),
        to_addr=to,
        subject=subject,
        html_body=html,
    )

    logging.info(f"Sending email to {to}")
    extra = ""
    if smtp_port == 587:
        extra = "starttls"
    envelope.send(smtp_server, smtp_port, sender_email, smtp_password, extra)
    # write the hash to disk.
    hfile.parent.mkdir(parents=True, exist_ok=True)
    hfile.write_text(h)