Skip to content

Commit

Permalink
Allow reading Heroku API key from file
Browse files Browse the repository at this point in the history
Makes using it in an installed environment much simpler
  • Loading branch information
RealOrangeOne committed Sep 7, 2023
1 parent 538d3a7 commit 1b6dc48
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
11 changes: 7 additions & 4 deletions heroku_audit/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import sys
from typing import Any, cast

Expand All @@ -7,6 +6,8 @@
from rich import print
from rich.text import Text

from heroku_audit.config import config_env_default

__all__ = ["heroku"]


Expand All @@ -19,16 +20,18 @@ class LazyHerokuWrapper:

def _get_heroku(self) -> Heroku:
if self._heroku is None:
try:
self._heroku = heroku3.from_key(os.environ["HEROKU_API_KEY"])
except KeyError:
api_key = config_env_default("heroku-api-key.txt", "HEROKU_API_KEY")
if api_key is None:
print(
Text(
"Please set $HEROKU_API_KEY to a valid Heroku API key.",
style="red",
)
)
sys.exit(1)

self._heroku = heroku3.from_key(api_key.strip())

return self._heroku

def __getattr__(self, attr_name: str) -> Any:
Expand Down
29 changes: 29 additions & 0 deletions heroku_audit/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import os
from pathlib import Path
from typing import Optional

from typer import get_app_dir

APP_DIR = Path(get_app_dir("heroku-audit"))


def config_env_default(
file_name: str, env_var: str, default: Optional[str] = None
) -> Optional[str]:
"""
Attempt to load a configuration value.
Sources, in order:
1. Environment variable named `env_var`
2. Config file in app dir with name `file_name`
3. `default`
"""
if env_value := os.environ.get(env_var):
return env_value

config_file = APP_DIR / file_name
if config_file.is_file():
return config_file.read_text()

return default

0 comments on commit 1b6dc48

Please sign in to comment.