fix: clean up config.py unused imports, null-YAML safety, and add non-default roundtrip test

This commit is contained in:
2026-05-21 12:08:56 +08:00
parent 53133ccb67
commit 62414399b1
2 changed files with 29 additions and 9 deletions

View File

@@ -1,7 +1,6 @@
import os
from dataclasses import dataclass, asdict, field
from dataclasses import dataclass, asdict, fields as dc_fields
from pathlib import Path
from typing import Optional
import click
import yaml
@@ -28,9 +27,11 @@ class TunnelConfig:
ssh_options: str = ""
_DEFAULTS = TunnelConfig(
name="", host="", user="", local_port=0, remote_port=0
)
_OPTIONAL_DEFAULTS = {
f.name: f.default
for f in dc_fields(TunnelConfig)
if f.name in ("port", "identity_file", "local_host", "remote_host", "ssh_options")
}
def ensure_dirs(config_dir: Path) -> None:
@@ -47,7 +48,7 @@ def load_tunnels(config_dir: Path) -> list[TunnelConfig]:
if not tunnels_file.exists():
return []
data = yaml.safe_load(tunnels_file.read_text()) or {}
return [TunnelConfig(**entry) for entry in data.get("tunnels", [])]
return [TunnelConfig(**entry) for entry in (data.get("tunnels") or [])]
def save_tunnels(config_dir: Path, tunnels: list[TunnelConfig]) -> None:
@@ -55,8 +56,8 @@ def save_tunnels(config_dir: Path, tunnels: list[TunnelConfig]) -> None:
for t in tunnels:
d = asdict(t)
# Omit optional fields that are at their default values
for key in ("port", "identity_file", "local_host", "remote_host", "ssh_options"):
if d[key] == getattr(_DEFAULTS, key):
for key, default in _OPTIONAL_DEFAULTS.items():
if d[key] == default:
del d[key]
rows.append(d)
tmp = config_dir / "tunnels.yaml.tmp"