This commit is contained in:
Jakub Kropáček 2024-07-24 00:09:16 +02:00
parent c3ba2b4a27
commit a8b15a8a75

View file

@ -1,27 +1,19 @@
#!/usr/bin/env python3
import argparse
import enum
import getpass
import shutil
import subprocess as sp
from pathlib import Path
from typing import Literal
import jinja2
bitwarden_session = None
TemplateEnvType = Literal["password", "username"]
def fetch_secret(bw_path: Path, secret_id: str, object_type: str = "password") -> str:
global bitwarden_session
res = sp.run(
[bw_path, "get", object_type, secret_id, "--session", bitwarden_session],
capture_output=True,
text=True,
)
res.check_returncode()
return res.stdout
class TemplateEnvType(enum.StrEnum):
USERNAME = "username"
PASSWORD = "password"
class TemplateEnv:
@ -29,19 +21,29 @@ class TemplateEnv:
env_type: TemplateEnvType
cached_items: dict[str, str]
def _fetch_secret(self, secret_id: str) -> str:
global bitwarden_session
res = sp.run(
[
self.bw_path, "get", self.env_type.value,
secret_id, "--session", bitwarden_session,
],
capture_output=True,
text=True,
)
res.check_returncode()
return res.stdout
def __init__(self, _type: TemplateEnvType, bw_path: Path):
self.env_type = _type
self.bw_path = bw_path
self.cached_items = dict()
def __getitem__(self, item):
print(f"{self.env_type} {self.cached_items}")
if cached_item := self.cached_items.get(item):
return cached_item
self.cached_items[item] = fetch_secret(
self.bw_path,
self.cached_items[item] = self._fetch_secret(
item,
self.env_type,
)
return self.cached_items[item]
@ -101,8 +103,8 @@ def compile_file(file_path: Path, bw_path: Path):
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(file_path.parent),
)
username = TemplateEnv("username", bw_path)
password = TemplateEnv("password", bw_path)
username = TemplateEnv(TemplateEnvType.USERNAME, bw_path)
password = TemplateEnv(TemplateEnvType.PASSWORD, bw_path)
template = jinja_env.get_template(file_path.name)
rendered_template = template.render(