Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 41 additions & 15 deletions src/diraccfg/cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -747,26 +747,28 @@ def serialize(self, tabLevelString: str = "") -> str:
:return: String with the contents of the CFG
"""
indentation = " "
cfgString = ""
# Accumulate the pieces in a list and join them once: growing a string
# with += and calling listSections()/listOptions() for every entry is
# quadratic in the number of entries/values
cfgLines: list[str] = []
for entryName in self.__orderedList:
if entryName in self.__commentDict:
for commentLine in List.fromChar(self.__commentDict[entryName], "\n"):
cfgString += f"{tabLevelString}#{commentLine}\n"
if entryName in self.listSections():
cfgString += f"{tabLevelString}{entryName}\n{tabLevelString}{{\n"
cfgString += cast(CFG, self.__dataDict[entryName]).serialize(f"{tabLevelString}{indentation}")
cfgString += "%s}\n" % tabLevelString
elif entryName in self.listOptions():
valueList = List.fromChar(cast(str, self.__dataDict[entryName]))
cfgLines.append(f"{tabLevelString}#{commentLine}\n")
entryValue = self.__dataDict[entryName]
if not isinstance(entryValue, str):
cfgLines.append(f"{tabLevelString}{entryName}\n{tabLevelString}{{\n")
cfgLines.append(entryValue.serialize(f"{tabLevelString}{indentation}"))
cfgLines.append("%s}\n" % tabLevelString)
else:
valueList = List.fromChar(entryValue)
if len(valueList) == 0:
cfgString += f"{tabLevelString}{entryName} = \n"
cfgLines.append(f"{tabLevelString}{entryName} = \n")
else:
cfgString += f"{tabLevelString}{entryName} = {valueList[0]}\n"
cfgLines.append(f"{tabLevelString}{entryName} = {valueList[0]}\n")
for value in valueList[1:]:
cfgString += f"{tabLevelString}{entryName} += {value}\n"
else:
raise ValueError("Oops. There is an entry in the order which is not a section nor an option")
return cfgString
cfgLines.append(f"{tabLevelString}{entryName} += {value}\n")
return "".join(cfgLines)

@gCFGSynchro
def clone(self) -> CFG:
Expand Down Expand Up @@ -1001,6 +1003,18 @@ def loadFromBuffer(self, data: str) -> CFG:
currentLevel = self
currentlyParsedString = ""
currentComment = ""
# Consecutive "+=" lines for the same option (e.g. a long list serialized
# one value per line) are accumulated and appended at once: appending
# them one by one copies the whole growing value each time (quadratic).
# Holds at most one (cfg, optionName, [values still to append])
pendingAppend: list[tuple[CFG, str, list[str]]] = []

def flushPendingAppend() -> None:
if pendingAppend:
pendingCFG, pendingName, pendingValues = pendingAppend.pop()
if pendingValues:
pendingCFG.appendToOption(pendingName, "".join(pendingValues))

for line in data.split("\n"):
line = line.strip()
if len(line) < 1:
Expand All @@ -1010,33 +1024,45 @@ def loadFromBuffer(self, data: str) -> CFG:
continue
for index in range(len(line)):
if line[index] == "{":
flushPendingAppend()
currentlyParsedString = currentlyParsedString.strip()
currentLevel.createNewSection(currentlyParsedString, currentComment)
levelList.append(currentLevel)
currentLevel = cast(CFG, currentLevel[currentlyParsedString])
currentlyParsedString = ""
currentComment = ""
elif line[index] == "}":
flushPendingAppend()
try:
currentLevel = levelList.pop()
except IndexError:
raise ValueError(
"The cfg file seems to close more sections than it opens (i.e. to many '}' vs '{'"
) from None
elif line[index] == "=":
flushPendingAppend()
lFields = line.split("=")
currentLevel.setOption(lFields[0].strip(), "=".join(lFields[1:]).strip(), currentComment)
currentlyParsedString = ""
currentComment = ""
break
elif line[index : index + 2] == "+=":
valueList = line.split("+=")
currentLevel.appendToOption(valueList[0].strip(), f", {'+='.join(valueList[1:]).strip()}")
optionName = valueList[0].strip()
valueToAppend = f", {'+='.join(valueList[1:]).strip()}"
if pendingAppend and pendingAppend[0][0] is currentLevel and pendingAppend[0][1] == optionName:
pendingAppend[0][2].append(valueToAppend)
else:
flushPendingAppend()
# The first append is done straight away so that errors are raised at the same point
currentLevel.appendToOption(optionName, valueToAppend)
pendingAppend.append((currentLevel, optionName, []))
currentlyParsedString = ""
currentComment = ""
break
else:
currentlyParsedString += line[index]
flushPendingAppend()
# At this point, the levelList should be empty
if levelList:
raise ValueError("The cfg file seems to open more sections than it closes (i.e. to many '{' vs '}'")
Expand Down
45 changes: 45 additions & 0 deletions tests/test_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,3 +807,48 @@ def test_clone():
b.setOption("c/d", "2")
assert a.getOption("c/d") == "3"
assert b.getOption("c/d") == "2"


def test_serialize_long_list_roundtrip():
"""A long list is serialized one value per line and loaded back identically (used to be quadratic)"""
values = [f"LFN:/lhcb/data/2024/{i:08d}.dst" for i in range(20000)]
cfg = CFG()
cfg.setOption("InputData", ", ".join(values))
cfg.setOption("Other", "1")
sub = CFG()
sub.setOption("List", "a, b, c")
cfg.createNewSection("Sub", contents=sub)
serialized = cfg.serialize()
assert serialized.startswith(f"InputData = {values[0]}\nInputData += {values[1]}\n")
# InputData lines, Other, then "Sub", "{", 3 List lines and "}"
assert serialized.count("\n") == len(values) + 1 + 6
loaded = CFG().loadFromBuffer(serialized)
assert loaded.getOption("InputData", []) == values
assert loaded.getOption("Sub/List", []) == ["a", "b", "c"]
assert loaded.serialize() == serialized


@pytest.mark.parametrize(
"data, expected",
[
# appends to the same option are concatenated in order
("a = 1\na += 2\na += 3", {"a": "1, 2, 3"}),
# interleaved appends to different options
("a = 1\nb = x\na += 2\nb += y\na += 3", {"a": "1, 2, 3", "b": "x, y"}),
# a new assignment after appends replaces the value
("a = 1\na += 2\na = 9\na += 10", {"a": "9, 10"}),
# appends inside a section, with the same name as an option outside
("a = 1\nS\n{\na = x\na += y\n}\na += 2", {"a": "1, 2", "S/a": "x, y"}),
# appends with a path
("S\n{\na = x\n}\nS/a += y\nS/a += z", {"S/a": "x, y, z"}),
],
)
def test_loadFromBuffer_appends(data, expected):
cfg = CFG().loadFromBuffer(data)
for key, value in expected.items():
assert cfg.getOption(key) == value


def test_loadFromBuffer_append_undeclared():
with pytest.raises(KeyError, match="Option b has not been declared"):
CFG().loadFromBuffer("a = 1\na += 2\nb += 3")