Skip to content

Commit

Permalink
Merge pull request #448 from DHI/pfs_quotes
Browse files Browse the repository at this point in the history
Pfs quotes
  • Loading branch information
ecomodeller authored Oct 18, 2022
2 parents 7b1890c + aeced34 commit 990aa50
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 11 deletions.
25 changes: 14 additions & 11 deletions mikeio/pfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,19 +498,20 @@ def _parse_line(self, line: str) -> str:

key = s[0:idx]
key = key.strip()
value = s[(idx + 1) :]

if (
s[0] == "'" and s[-1] == "'"
): # This is a quoted string and not a list
s = s
else:
if "," in value:
value = f"[{value}]"
value = s[(idx + 1) :].strip()

if key == "start_time":
v = eval(value)
value = datetime(*v)
value = datetime.strptime(value, "%Y, %m, %d, %H, %M, %S").strftime(
"%Y-%m-%d %H:%M:%S"
)

if len(value) > 2: # ignore foo = ''
value = value.replace("''", '"')

if value[0] == "'" and value[-1] == "'" and value.count("'") == 2:
pass # quoted single string
elif "," in value: # array
value = f"[{value}]"

s = f"{key}: {value}"

Expand Down Expand Up @@ -555,6 +556,8 @@ def _prepare_value_for_write(self, v):
else:
v = f"'{v}'"

v = v.replace('"', "''")

elif isinstance(v, bool):
v = str(v).lower() # stick to MIKE lowercase bool notation

Expand Down
33 changes: 33 additions & 0 deletions tests/test_pfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,3 +546,36 @@ def test_read_string_array():
assert pfs.ENGINE.fill_list[0] == "foo"
assert pfs.ENGINE.fill_list[1] == "bar"
assert pfs.ENGINE.fill_list[2] == "baz"


def test_double_single_quotes_in_string(tmpdir):
text = """
[DERIVED_VARIABLE_106]
name = 'alfa_PC_T'
type = 0
dimension = 3
description = 'alfa_PC_T, ''light'' adjusted alfa_PC, ugC/gC*m2/uE'
EUM_type = 999
EUM_unit = 0
unit = 'ugC/gC*m2/uE'
ID = 597
EndSect // DERIVED_VARIABLE_106
"""

pfs = mikeio.Pfs(StringIO(text))
assert (
pfs.DERIVED_VARIABLE_106.description
== 'alfa_PC_T, "light" adjusted alfa_PC, ugC/gC*m2/uE'
)

filename = os.path.join(tmpdir, "quotes.pfs")

pfs.write(filename)

with open(filename) as f:
for line in f:
if "description" in line:
assert (
line.strip()
== "description = 'alfa_PC_T, ''light'' adjusted alfa_PC, ugC/gC*m2/uE'"
)

0 comments on commit 990aa50

Please sign in to comment.