Skip to content

Commit

Permalink
EnvFile now prefixes empty variables with a comment (#) to avoid over…
Browse files Browse the repository at this point in the history
…riding existing variables. More robust stripping on parse, too.
  • Loading branch information
tcdent committed Dec 18, 2024
1 parent b85f089 commit dffff68
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions agentstack/generation/files.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Optional, Union
import string
import os, sys
from pathlib import Path

Expand All @@ -20,6 +21,10 @@ class EnvFile:
and instead just append new lines to the end of the file. This preseres
comments and other formatting that the user may have added and prevents
opportunities for data loss.
If the value of a variable is None, it will be commented out when it is written
to the file. This gives the user a suggestion, but doesn't override values that
may have been set by the user via other means.
`path` is the directory where the .env file is located. Defaults to the
current working directory.
Expand Down Expand Up @@ -57,7 +62,7 @@ def append_if_new(self, key, value):
def read(self):
def parse_line(line):
key, value = line.split('=')
return key.strip(), value.strip()
return key.strip(string.whitespace + '#'), value.strip(string.whitespace + '"')

if os.path.exists(conf.PATH / self._filename):
with open(conf.PATH / self._filename, 'r') as f:
Expand All @@ -69,7 +74,10 @@ def parse_line(line):
def write(self):
with open(conf.PATH / self._filename, 'a') as f:
for key, value in self._new_variables.items():
f.write(f"\n{key}={value}")
if value is None:
f.write(f'\n#{key}=""') # comment-out empty values
else:
f.write(f'\n{key}={value}')

def __enter__(self) -> 'EnvFile':
return self
Expand Down

0 comments on commit dffff68

Please sign in to comment.