55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 4:
|
|
print("usage: set_api_token_env.py ENV_PATH PARTNER TOKEN", file=sys.stderr)
|
|
return 2
|
|
|
|
env_path = Path(sys.argv[1])
|
|
partner = sys.argv[2].strip()
|
|
token = sys.argv[3].strip()
|
|
|
|
if not partner or any(ch in partner for ch in ",:= \t\r\n"):
|
|
print("partner must not contain comma, colon, equals, or whitespace", file=sys.stderr)
|
|
return 2
|
|
if not token or any(ch in token for ch in ", \t\r\n"):
|
|
print("token must not contain comma or whitespace", file=sys.stderr)
|
|
return 2
|
|
|
|
text = env_path.read_text(encoding="utf-8") if env_path.exists() else ""
|
|
lines = text.splitlines()
|
|
|
|
api_tokens_index: int | None = None
|
|
current_value = ""
|
|
for index, line in enumerate(lines):
|
|
if line.startswith("API_TOKENS="):
|
|
api_tokens_index = index
|
|
current_value = line.split("=", 1)[1]
|
|
break
|
|
|
|
entries = [entry.strip() for entry in current_value.split(",") if entry.strip()]
|
|
entries = [
|
|
entry
|
|
for entry in entries
|
|
if not (entry.startswith(f"{partner}:") or entry.startswith(f"{partner}="))
|
|
]
|
|
entries.append(f"{partner}:{token}")
|
|
new_line = f"API_TOKENS={','.join(entries)}"
|
|
|
|
if api_tokens_index is None:
|
|
lines.append(new_line)
|
|
else:
|
|
lines[api_tokens_index] = new_line
|
|
|
|
env_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
print(f"updated API_TOKENS for {partner}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|