v0.166.0
 1from importlib.util import find_spec
 2from pathlib import Path
 3
 4from plain.cli.runtime import when_the_running_command_is_found
 5
 6from .dotenv import load_dotenv_files
 7from .utils import has_pyproject_toml
 8
 9
10def setup() -> None:
11    # Make sure our clis are registered
12    # since this isn't an installed app
13    from .cli import cli  # noqa
14    from .precommit import cli  # noqa
15    from .contribute import cli  # noqa
16    from .request import request  # noqa
17    from .services import auto_start_services
18
19    has_postgres = find_spec("plain.postgres") is not None
20
21    # `plain db` manages Postgres databases, so it only exists when
22    # plain.postgres is installed.
23    if has_postgres:
24        from .db import cli  # noqa
25
26    load_dotenv_files()
27
28    # Resolve a database URL before services start, so DB-dependent services
29    # inherit it. No-op when the user configured their own or when managed
30    # Postgres is off; skipped entirely when plain.postgres isn't installed.
31    if has_postgres:
32        _ensure_managed_postgres()
33
34    # Dev services are started for the commands that need them, once there
35    # is known to be such a command. This hook runs for `plain tset` too, and
36    # for `plain test` with no plain.testing installed, and services started
37    # for a command that doesn't exist are left running by it.
38    when_the_running_command_is_found(auto_start_services)
39
40
41def _ensure_managed_postgres() -> None:
42    # Located by walking up from the working directory: this runs before
43    # settings are configured, so `APP_PATH` isn't available yet. `plain db`
44    # walks up from the app instead and must land in the same place — see
45    # `find_project_root`.
46    from .state import find_project_root
47
48    project_root = find_project_root(Path.cwd())
49    if not has_pyproject_toml(project_root):
50        return
51
52    from .postgres.resolve import ensure_postgres
53
54    try:
55        ensure_postgres(project_root)
56    except Exception as e:
57        # A database problem should surface when something actually needs the
58        # database, with that command's own error — not as a failure of every
59        # command that merely passed through setup().
60        import click
61
62        click.secho(f"Managed Postgres unavailable: {e}", fg="yellow", err=True)