Skip to content
Closed
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
21 changes: 19 additions & 2 deletions bridge/fleet_bridge/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def set_fields(path: Path, section: str, name: str, fields: dict[str, Any]) -> N
entry = _entry(yaml.compose(text), section, name)
if not isinstance(entry, yaml.MappingNode):
raise ValueError(f"{section}: no entry {name}")
value = next((v for k, v in entry.value if k.value == key), None)
name_node, value = next(((k, v) for k, v in entry.value if k.value == key), (None, None))
written = json.dumps(setting)
if value is not None:
# A block value runs on to the next key; it ends with its last line of content.
Expand All @@ -78,13 +78,30 @@ def set_fields(path: Path, section: str, name: str, fields: dict[str, Any]) -> N
offset += len(line)
if _is_content(line):
end = offset - (1 if line.endswith("\n") else 0)
text = text[:value.start_mark.index] + written + text[end:]
start = value.start_mark.index
if isinstance(value, yaml.CollectionNode) and not value.flow_style:
# A block list or map starts on the next line, and a list's items may sit at
# the key's own indentation, so the new value goes right after the key's colon.
colon = text.index(":", name_node.end_mark.index) + 1
rest = text[colon:text.index("\n", colon)].strip()
written = " " + written + (f" {rest}" if rest else "")
start = colon
text = text[:start] + written + text[end:]
elif entry.flow_style:
position = entry.end_mark.index - 1
text = text[:position] + f", {key}: {written}" + text[position:]
else:
position = entry.start_mark.index
text = text[:position] + f"{key}: {written}\n" + " " * entry.start_mark.column + text[position:]
# The file is replaced only with text that reads back as the values asked for.
try:
data = (yaml.safe_load(text) or {}).get(section)
except yaml.YAMLError as error:
raise ValueError(f"{section}: writing {', '.join(fields)} into {name} would break {path.name}: {error}")
got = (next((e for e in data if isinstance(e, dict) and e.get("name") == name), None)
if isinstance(data, list) else (data or {}).get(name))
if not isinstance(got, dict) or any(got.get(k) != v for k, v in fields.items()):
raise ValueError(f"{section}: {name} doesn't read back {', '.join(fields)} as written")
_replace(path, text)


Expand Down
24 changes: 24 additions & 0 deletions bridge/tests/test_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,30 @@ def test_resource_update_preserves_comments_and_handles_flow_yaml(tmp_path):
assert data["image"]=="image:latest" and "# machine config" in p.read_text()


@pytest.mark.parametrize("lists",["- "," - "])
def test_settings_update_replaces_block_lists_and_maps_however_indented(tmp_path,lists):
p=tmp_path/"apps.yaml"
p.write_text(f"apps:\n- name: app\n kind: app\n volumes: # mounts\n {lists}/old/a\n {lists}/old/b:ro\n"
f" env:\n HOME: /home/old\n command:\n {lists}python\n {lists}main.py\n image: image:latest\n"
"- name: other\n kind: app\n volumes:\n - /keep\n")
for fields in [{"volumes":["/new/a"]},{"command":["/new/python","main.py"]},{"env":{"HOME":"/home/new"}},
{"volumes":["/new/b"],"command":["/new/b/python"],"workdir":"/new/b"}]:
node.set_fields(p,"apps","app",fields)
apps=yaml.safe_load(p.read_text())["apps"]
assert {k:apps[0][k] for k in fields}==fields and apps[0]["image"]=="image:latest"
assert apps[1]=={"name":"other","kind":"app","volumes":["/keep"]}
assert "# mounts" in p.read_text()


def test_settings_update_never_writes_a_file_that_does_not_read_back(tmp_path,monkeypatch):
p=tmp_path/"apps.yaml";p.write_text("apps:\n- name: app\n kind: app\n volumes:\n - /old\n")
before=p.read_bytes()
monkeypatch.setattr(node.json,"dumps",lambda value:"[unclosed")
with pytest.raises(ValueError,match="would break"):
node.set_fields(p,"apps","app",{"volumes":["/new"]})
assert p.read_bytes()==before and not list(tmp_path.glob("*.node-tmp"))




APPS = """# machine config
Expand Down
Loading