From 924adac16ae256ecfad37009fd403cbc128b3468 Mon Sep 17 00:00:00 2001 From: Robin Munn Date: Mon, 27 May 2024 13:48:53 +0700 Subject: [PATCH] Make `local.env` creation idempotent in `task setup` --- Taskfile.yml | 8 ++++---- ensure.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) create mode 100755 ensure.py diff --git a/Taskfile.yml b/Taskfile.yml index 317aafe50..97a42b8e2 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -30,10 +30,10 @@ tasks: deps: [ setup-win, setup-unix ] cmds: - git config blame.ignoreRevsFile .git-blame-ignore-revs - - echo "HONEYCOMB_API_KEY=__REPLACE__" >> deployment/local-dev/local.env - - echo "#OTEL_SDK_DISABLED=true" >> deployment/local-dev/local.env - - echo "GOOGLE_OAUTH_CLIENT_ID=__REPLACE__.apps.googleusercontent.com" >> deployment/local-dev/local.env - - echo "GOOGLE_OAUTH_CLIENT_SECRET=__REPLACE__" >> deployment/local-dev/local.env + - ./ensure.py deployment/local-dev/local.env HONEYCOMB_API_KEY __REPLACE__ + - ./ensure.py deployment/local-dev/local.env '#OTEL_SDK_DISABLED' true + - ./ensure.py deployment/local-dev/local.env GOOGLE_OAUTH_CLIENT_ID __REPLACE__.apps.googleusercontent.com + - ./ensure.py deployment/local-dev/local.env GOOGLE_OAUTH_CLIENT_SECRET __REPLACE__ - kubectl --context=docker-desktop apply -f deployment/setup/namespace.yaml setup-win: platforms: [ windows ] diff --git a/ensure.py b/ensure.py new file mode 100755 index 000000000..cb9b0c010 --- /dev/null +++ b/ensure.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 + +import os +import sys + +def usage(): + name = os.path.basename(sys.argv[0]) + print(f"Usage: {name} file key value") + print("") + print(f"E.g., {name} local.env HONEYCOMB_API_KEY __REPLACE__") + +def ensure(fname, search_str, replace_str): + # Ensure search_str is present. If not found, add replace_str to end of file + found = False + try: + with open(fname, encoding='utf-8') as f: + lines = f.readlines() + for line in lines: + if search_str in line: + found = True + break + except FileNotFoundError: + lines = [] + need_extra_newline = False + if lines and lines[-1] and not lines[-1].endswith('\n'): + need_extra_newline = True + if not found: + if need_extra_newline: + lines[-1] = lines[-1] + '\n' + lines.append(replace_str + '\n') + with open(fname, 'w', encoding='utf-8') as f: + f.writelines(lines) + +if __name__ == '__main__': + if (len(sys.argv) < 4): + usage() + (fname, key, value) = sys.argv[1:4] + search_str = f"{key}=" + replace_str = f"{key}={value}" + ensure(fname, search_str, replace_str)