fix: single load in remove, use dataclasses.replace in config_cmd, add remove-running test

This commit is contained in:
2026-05-21 12:45:08 +08:00
parent 9e9ba66f1f
commit 2bb08e92c7
2 changed files with 19 additions and 10 deletions

View File

@@ -1,4 +1,5 @@
import click
from dataclasses import replace
from autossh_mgr.config import (
TunnelConfig, get_config_dir, ensure_dirs,
load_tunnels, save_tunnels, get_tunnel,
@@ -98,14 +99,15 @@ def add(
def remove(ctx, name):
"""Remove a tunnel configuration."""
config_dir = ctx.obj["config_dir"]
get_tunnel(config_dir, name) # raises if not found
tunnels = load_tunnels(config_dir)
if not any(t.name == name for t in tunnels):
raise click.ClickException(f"No tunnel named '{name}'")
status = get_status(config_dir, name)
if status.state == "running":
raise click.ClickException(f"Stop '{name}' before removing it")
if not click.confirm(f"Remove tunnel '{name}'?"):
return
tunnels = [t for t in load_tunnels(config_dir) if t.name != name]
save_tunnels(config_dir, tunnels)
save_tunnels(config_dir, [t for t in tunnels if t.name != name])
click.echo(f"Removed tunnel '{name}'")
@@ -149,13 +151,8 @@ def config_cmd(ctx, name, key, value):
f"Invalid value for '{key}': expected {_FIELD_TYPES[key].__name__}"
)
tunnels = load_tunnels(config_dir)
found = False
for t in tunnels:
if t.name == name:
setattr(t, key, typed_value)
found = True
break
if not found:
if not any(t.name == name for t in tunnels):
raise click.ClickException(f"No tunnel named '{name}'")
tunnels = [replace(t, **{key: typed_value}) if t.name == name else t for t in tunnels]
save_tunnels(config_dir, tunnels)
click.echo(f"Updated {name}.{key} = {typed_value}")