fix(agents): preserve existing rules during symlink installation

This commit is contained in:
Ryan Yin
2026-09-05 13:34:13 +08:00
parent 33b17baeff
commit a3bbb70508
3 changed files with 66 additions and 4 deletions
+18 -3
View File
@@ -2,6 +2,7 @@
import os
import sys
import tempfile
from pathlib import Path
@@ -12,10 +13,24 @@ def install_one(target_dir: Path, source_file: Path, target_name: str) -> None:
target_file = target_dir / target_name
if target_file.exists() or target_file.is_symlink():
target_file.unlink()
if target_file.is_file() and not target_file.is_symlink():
# Preserve the old inode without reading its contents or replacing an earlier backup.
index = 0
while True:
suffix = ".bak" if index == 0 else f".bak.{index}"
backup = target_file.with_name(target_file.name + suffix)
try:
os.link(target_file, backup)
break
except FileExistsError:
index += 1
print(f"backed up {target_file} -> {backup}")
target_file.symlink_to(source_file)
# Create the link on the same filesystem before atomically replacing the destination.
with tempfile.TemporaryDirectory(prefix=".install-rules-", dir=target_dir) as staging:
link = Path(staging) / target_name
link.symlink_to(source_file)
link.replace(target_file)
print(f"linked {target_file} -> {source_file}")