fix(cfg): show only the duplicate-key warning, once

This commit is contained in:
imSp4rky
2026-10-22 20:43:40 -06:00
parent 3e9c26bd46
commit 71f293161e
4 changed files with 34 additions and 25 deletions
+8 -5
View File
@@ -6,7 +6,7 @@ import click
from ruamel.yaml import YAML
from ruamel.yaml.constructor import DuplicateKeyError
from unshackle.core.config import config, duplicate_key_lines, duplicate_key_message, get_config_path
from unshackle.core.config import config, duplicate_key_lines, get_config_path, load_yaml
from unshackle.core.constants import context_settings
@@ -45,10 +45,13 @@ def cfg(ctx: click.Context, key: str, value: str, unset: bool, list_: bool) -> N
try:
data = yaml.load(config_path)
except DuplicateKeyError as e:
pairs = duplicate_key_lines(yaml.compose(config_path))
raise click.ClickException(
duplicate_key_message(config_path.name, pairs, e.problem_mark.line + 1)
) from None
if duplicate_key_lines(yaml.compose(config_path)):
load_yaml(config_path)
else:
log.warning(
f"{config_path}: duplicate key on line {e.problem_mark.line + 1}. Unshackle uses the later one."
)
sys.exit(1)
if not data:
log.warning("No config file was found or it has no data, yet")
+6 -9
View File
@@ -406,12 +406,6 @@ def duplicate_key_lines(root: Any) -> list[tuple[int, int]]:
return sorted(pairs)
def duplicate_key_message(name: str, pairs: list[tuple[int, int]], line: int = 0) -> str:
"""Say where a file repeats a key: each (first, repeat) pair, or `line` when no pair is known."""
where = ", ".join(f"lines {first} and {repeat}" for first, repeat in pairs) or f"line {line}"
return f"{name}: duplicate key on {where}. Unshackle uses the later one."
_warned: set[str] = set()
@@ -422,9 +416,12 @@ def load_yaml(path: Path) -> Any:
node = loader.get_single_node()
if node is None:
return None
if (pairs := duplicate_key_lines(node)) and (message := duplicate_key_message(str(path), pairs)) not in _warned:
_warned.add(message)
logging.getLogger("config").warning(message)
if pairs := duplicate_key_lines(node):
where = ", ".join(f"lines {first} and {repeat}" for first, repeat in pairs)
message = f"{path}: duplicate key on {where}. Unshackle uses the later one."
if message not in _warned:
_warned.add(message)
logging.getLogger("config").warning(message)
return loader.construct_document(node)
finally:
loader.dispose()