sshcnfgr 0.1.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sshcnfgr/__init__.py +5 -0
- sshcnfgr/cli.py +182 -0
- sshcnfgr/dedup.py +363 -0
- sshcnfgr/dedup_screen.py +466 -0
- sshcnfgr/generator.py +83 -0
- sshcnfgr/gui/__init__.py +29 -0
- sshcnfgr/gui/dedup_dialog.py +462 -0
- sshcnfgr/gui/main_window.py +1225 -0
- sshcnfgr/identities.py +95 -0
- sshcnfgr/importer.py +152 -0
- sshcnfgr/logging_conf.py +45 -0
- sshcnfgr/model.py +231 -0
- sshcnfgr/paths.py +37 -0
- sshcnfgr/settings.py +87 -0
- sshcnfgr/store.py +222 -0
- sshcnfgr/tui.py +471 -0
- sshcnfgr/tui.tcss +105 -0
- sshcnfgr-0.1.0b1.dist-info/METADATA +205 -0
- sshcnfgr-0.1.0b1.dist-info/RECORD +22 -0
- sshcnfgr-0.1.0b1.dist-info/WHEEL +4 -0
- sshcnfgr-0.1.0b1.dist-info/entry_points.txt +2 -0
- sshcnfgr-0.1.0b1.dist-info/licenses/LICENSE +21 -0
sshcnfgr/__init__.py
ADDED
sshcnfgr/cli.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
from loguru import logger
|
|
7
|
+
|
|
8
|
+
from . import __version__
|
|
9
|
+
from .generator import write_generated_config
|
|
10
|
+
from .identities import discover_ssh_identities, merge_discovered_identities
|
|
11
|
+
from .importer import import_ssh_config
|
|
12
|
+
from .logging_conf import configure_logging
|
|
13
|
+
from .paths import DB_PATH, GENERATED_CONFIG_PATH
|
|
14
|
+
from .store import load_database, save_database
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@click.group(
|
|
18
|
+
invoke_without_command=True,
|
|
19
|
+
help="SSHCnfgr: SSH-Hosts per TOML (~/.ssh/sshcnfgr.toml) mit TUI, GUI und CLI verwalten",
|
|
20
|
+
)
|
|
21
|
+
@click.version_option(__version__, prog_name="sshcnfgr")
|
|
22
|
+
@click.option("--verbose", is_flag=True, help="Debug-Logging aktivieren")
|
|
23
|
+
@click.option(
|
|
24
|
+
"--log-file",
|
|
25
|
+
type=click.Path(path_type=Path, dir_okay=False, file_okay=True),
|
|
26
|
+
default=None,
|
|
27
|
+
help="Optionaler Pfad fuer eine Logdatei (Standard: keine Logdatei)",
|
|
28
|
+
)
|
|
29
|
+
@click.pass_context
|
|
30
|
+
def cli(ctx: click.Context, verbose: bool, log_file: Path | None) -> None:
|
|
31
|
+
launching_tui = ctx.invoked_subcommand in (None, "tui")
|
|
32
|
+
# Im TUI-Modus kein stderr-Logging aktivieren, damit das Terminal-Layout sauber bleibt.
|
|
33
|
+
configure_logging(verbose=verbose, console=not launching_tui, log_file=log_file)
|
|
34
|
+
if ctx.invoked_subcommand is None:
|
|
35
|
+
from .tui import run_tui
|
|
36
|
+
|
|
37
|
+
logger.info("TUI wird direkt gestartet")
|
|
38
|
+
run_tui()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@cli.command("tui", help="Starte die Textual TUI")
|
|
42
|
+
def tui_command() -> None:
|
|
43
|
+
# Lazy import, damit reine CLI-Kommandos nicht die Textual-Importzeit zahlen.
|
|
44
|
+
from .tui import run_tui
|
|
45
|
+
|
|
46
|
+
logger.info("TUI wird gestartet")
|
|
47
|
+
run_tui()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@cli.command("gui", help="Starte die optionale Qt6 Desktop-GUI (Wayland/X11)")
|
|
51
|
+
def gui_command() -> None:
|
|
52
|
+
# Lazy import, damit PySide6 nur bei installiertem [qt]-Extra geladen wird.
|
|
53
|
+
try:
|
|
54
|
+
import PySide6 # noqa: F401
|
|
55
|
+
|
|
56
|
+
from .gui import run_gui
|
|
57
|
+
except ImportError as exc:
|
|
58
|
+
raise click.ClickException(
|
|
59
|
+
"Qt6-GUI benoetigt PySide6-Essentials. Installiere mit: uv sync --extra qt"
|
|
60
|
+
) from exc
|
|
61
|
+
|
|
62
|
+
logger.info("Qt6-GUI wird gestartet")
|
|
63
|
+
run_gui()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@cli.command("import", help="Importiere eine bestehende SSH-Config in die TOML-Datenbank")
|
|
67
|
+
@click.option(
|
|
68
|
+
"--source",
|
|
69
|
+
type=click.Path(path_type=Path, exists=True, dir_okay=False, file_okay=True),
|
|
70
|
+
default=Path.home() / ".ssh" / "config",
|
|
71
|
+
show_default=True,
|
|
72
|
+
)
|
|
73
|
+
def import_command(source: Path) -> None:
|
|
74
|
+
db, report = import_ssh_config(source)
|
|
75
|
+
errors = db.validate()
|
|
76
|
+
if errors:
|
|
77
|
+
for err in errors:
|
|
78
|
+
logger.error(err)
|
|
79
|
+
raise click.ClickException("Import erzeugt ungueltige Daten")
|
|
80
|
+
|
|
81
|
+
save_database(db, DB_PATH)
|
|
82
|
+
|
|
83
|
+
logger.info("Import abgeschlossen: {}", report.summary())
|
|
84
|
+
for warning in report.warnings:
|
|
85
|
+
logger.warning(warning)
|
|
86
|
+
|
|
87
|
+
click.echo(f"Import ok: {report.summary()}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@cli.command("generate", help="Generiere eine OpenSSH-Config aus der TOML-Datenbank")
|
|
91
|
+
@click.option(
|
|
92
|
+
"--output",
|
|
93
|
+
type=click.Path(path_type=Path, dir_okay=False, file_okay=True),
|
|
94
|
+
default=GENERATED_CONFIG_PATH,
|
|
95
|
+
show_default=True,
|
|
96
|
+
)
|
|
97
|
+
def generate_command(output: Path) -> None:
|
|
98
|
+
db = load_database()
|
|
99
|
+
errors = db.validate()
|
|
100
|
+
if errors:
|
|
101
|
+
for err in errors:
|
|
102
|
+
logger.error(err)
|
|
103
|
+
raise click.ClickException("Datenbank ist ungueltig, Generierung abgebrochen")
|
|
104
|
+
|
|
105
|
+
target = write_generated_config(db, output=output)
|
|
106
|
+
logger.info("Config generiert: {}", target)
|
|
107
|
+
click.echo(f"Generiert: {target}")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@cli.group("identities", help="Identities verwalten")
|
|
111
|
+
def identities_group() -> None:
|
|
112
|
+
pass
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@identities_group.command("scan", help="Lese Identities direkt aus ~/.ssh ein")
|
|
116
|
+
@click.option(
|
|
117
|
+
"--ssh-dir",
|
|
118
|
+
type=click.Path(path_type=Path, exists=True, file_okay=False, dir_okay=True),
|
|
119
|
+
default=Path.home() / ".ssh",
|
|
120
|
+
show_default=True,
|
|
121
|
+
)
|
|
122
|
+
def identities_scan_command(ssh_dir: Path) -> None:
|
|
123
|
+
db = load_database()
|
|
124
|
+
discovered = discover_ssh_identities(ssh_dir)
|
|
125
|
+
created, updated = merge_discovered_identities(db, discovered)
|
|
126
|
+
save_database(db, DB_PATH)
|
|
127
|
+
logger.info(
|
|
128
|
+
"Identities gescannt: discovered={}, created={}, updated={}",
|
|
129
|
+
len(discovered),
|
|
130
|
+
created,
|
|
131
|
+
updated,
|
|
132
|
+
)
|
|
133
|
+
click.echo(f"Scan ok: discovered={len(discovered)} created={created} updated={updated}")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@identities_group.command("list", help="Liste bekannte Identities")
|
|
137
|
+
def identities_list_command() -> None:
|
|
138
|
+
db = load_database()
|
|
139
|
+
if not db.identities:
|
|
140
|
+
click.echo("Keine Identities vorhanden")
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
for identity in db.sorted_identities():
|
|
144
|
+
click.echo(
|
|
145
|
+
f"{identity.name:20} {identity.identity_file} "
|
|
146
|
+
f"source={identity.source} enabled={identity.enabled}"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@cli.group("groups", help="Gruppen verwalten")
|
|
151
|
+
def groups_group() -> None:
|
|
152
|
+
pass
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@groups_group.command("set-identity", help="Setze eine Identity fuer eine Gruppe")
|
|
156
|
+
@click.argument("group_name")
|
|
157
|
+
@click.argument("identity_name")
|
|
158
|
+
def groups_set_identity_command(group_name: str, identity_name: str) -> None:
|
|
159
|
+
db = load_database()
|
|
160
|
+
|
|
161
|
+
identity = db.get_identity_by_name(identity_name)
|
|
162
|
+
if identity is None:
|
|
163
|
+
raise click.ClickException(f"Identity nicht gefunden: {identity_name}")
|
|
164
|
+
|
|
165
|
+
group = db.get_group_by_name(group_name)
|
|
166
|
+
if group is None:
|
|
167
|
+
db.ensure_groups([group_name])
|
|
168
|
+
group = db.get_group_by_name(group_name)
|
|
169
|
+
assert group is not None
|
|
170
|
+
|
|
171
|
+
group.identity = identity.name
|
|
172
|
+
|
|
173
|
+
errors = db.validate()
|
|
174
|
+
if errors:
|
|
175
|
+
raise click.ClickException("; ".join(errors))
|
|
176
|
+
|
|
177
|
+
save_database(db, DB_PATH)
|
|
178
|
+
click.echo(f"Group '{group.name}' nutzt jetzt Identity '{identity.name}'")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == "__main__":
|
|
182
|
+
cli()
|
sshcnfgr/dedup.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from .model import HostDatabase, HostEntry
|
|
8
|
+
|
|
9
|
+
MergeDisposition = Literal["disable", "delete"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(slots=True)
|
|
13
|
+
class ConflictOption:
|
|
14
|
+
"""Ein moeglicher Feldwert innerhalb eines Dubletten-Konflikts."""
|
|
15
|
+
|
|
16
|
+
value: str | None
|
|
17
|
+
sources: list[str] = field(default_factory=list)
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def display_label(self) -> str:
|
|
21
|
+
value_text = self.value if self.value is not None else "(leer)"
|
|
22
|
+
if self.sources:
|
|
23
|
+
return f"{value_text} [{', '.join(self.sources)}]"
|
|
24
|
+
return value_text
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(slots=True)
|
|
28
|
+
class FieldConflict:
|
|
29
|
+
"""Beschreibt ein Feld mit widerspruechlichen Werten in einer Dubletten-Gruppe."""
|
|
30
|
+
|
|
31
|
+
field: str
|
|
32
|
+
label: str
|
|
33
|
+
options: list[ConflictOption] = field(default_factory=list)
|
|
34
|
+
allow_empty: bool = True
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(slots=True)
|
|
38
|
+
class DuplicateGroup:
|
|
39
|
+
"""Gruppe von Hosts mit identischem Ziel (HostName + effektiver Port + effektiver User)."""
|
|
40
|
+
|
|
41
|
+
host_name: str
|
|
42
|
+
port: int
|
|
43
|
+
user: str
|
|
44
|
+
hosts: list[HostEntry] = field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def key(self) -> tuple[str, int, str]:
|
|
48
|
+
return (self.host_name, self.port, self.user)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def label(self) -> str:
|
|
52
|
+
if self.user:
|
|
53
|
+
return f"{self.user}@{self.host_name}:{self.port}"
|
|
54
|
+
return f"{self.host_name}:{self.port}"
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def aliases(self) -> list[str]:
|
|
58
|
+
return [host.name for host in self.hosts]
|
|
59
|
+
|
|
60
|
+
def get_host_by_id(self, host_id: str) -> HostEntry | None:
|
|
61
|
+
for host in self.hosts:
|
|
62
|
+
if host.id == host_id:
|
|
63
|
+
return host
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(slots=True)
|
|
68
|
+
class MergePlan:
|
|
69
|
+
"""Nutzerentscheidungen zum Zusammenfuehren einer Dubletten-Gruppe."""
|
|
70
|
+
|
|
71
|
+
group: DuplicateGroup
|
|
72
|
+
primary_host_id: str
|
|
73
|
+
target_name: str
|
|
74
|
+
resolved_fields: dict[str, str | None] = field(default_factory=dict)
|
|
75
|
+
disposition: MergeDisposition = "disable"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def find_duplicate_groups(
|
|
79
|
+
db: HostDatabase, *, include_inactive: bool = False
|
|
80
|
+
) -> list[DuplicateGroup]:
|
|
81
|
+
"""Findet potentielle Dubletten mit gleichem Ziel (HostName, Port, User)."""
|
|
82
|
+
buckets: dict[tuple[str, int, str], list[HostEntry]] = {}
|
|
83
|
+
|
|
84
|
+
for host in db.sorted_hosts():
|
|
85
|
+
if not include_inactive and not host.enabled:
|
|
86
|
+
continue
|
|
87
|
+
|
|
88
|
+
normalized_host = host.host_name.strip().lower()
|
|
89
|
+
if not normalized_host:
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
effective_port = db.resolve_port(host)
|
|
93
|
+
effective_user = (db.resolve_user(host) or "").strip()
|
|
94
|
+
key = (normalized_host, effective_port, effective_user)
|
|
95
|
+
buckets.setdefault(key, []).append(host)
|
|
96
|
+
|
|
97
|
+
groups: list[DuplicateGroup] = []
|
|
98
|
+
for (host_name, port, user), members in sorted(buckets.items()):
|
|
99
|
+
if len(members) >= 2:
|
|
100
|
+
groups.append(
|
|
101
|
+
DuplicateGroup(
|
|
102
|
+
host_name=host_name,
|
|
103
|
+
port=port,
|
|
104
|
+
user=user,
|
|
105
|
+
hosts=members,
|
|
106
|
+
)
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
return groups
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _collect_distinct_values(
|
|
113
|
+
hosts: list[HostEntry],
|
|
114
|
+
extractor: list[tuple[str, str | None]],
|
|
115
|
+
) -> list[ConflictOption]:
|
|
116
|
+
"""Sammelt eindeutige nicht-leere Werte inkl. Quell-Aliase in stabiler Reihenfolge."""
|
|
117
|
+
by_value: dict[str, list[str]] = {}
|
|
118
|
+
for alias, value in extractor:
|
|
119
|
+
if value is None:
|
|
120
|
+
continue
|
|
121
|
+
cleaned = value.strip()
|
|
122
|
+
if not cleaned:
|
|
123
|
+
continue
|
|
124
|
+
by_value.setdefault(cleaned, []).append(alias)
|
|
125
|
+
|
|
126
|
+
return [ConflictOption(value=val, sources=sources) for val, sources in by_value.items()]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _collect_extra_key_map(hosts: list[HostEntry]) -> dict[str, str]:
|
|
130
|
+
"""Erstellt ein Mapping lowercase-Key -> kanonischer Key ueber alle Hosts."""
|
|
131
|
+
canonical: dict[str, str] = {}
|
|
132
|
+
for host in hosts:
|
|
133
|
+
for key in sorted(host.extra_options.keys(), key=lambda item: item.lower()):
|
|
134
|
+
key_lower = key.lower()
|
|
135
|
+
if key_lower not in canonical:
|
|
136
|
+
canonical[key_lower] = key
|
|
137
|
+
return canonical
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _get_extra_value_ci(host: HostEntry, key_lower: str) -> str | None:
|
|
141
|
+
for key, value in host.extra_options.items():
|
|
142
|
+
if key.lower() == key_lower:
|
|
143
|
+
return value
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def analyze_group_conflicts(group: DuplicateGroup) -> list[FieldConflict]:
|
|
148
|
+
"""Ermittelt alle Felder innerhalb einer Gruppe mit mehr als einem nicht-leeren Wert."""
|
|
149
|
+
conflicts: list[FieldConflict] = []
|
|
150
|
+
|
|
151
|
+
host_name_options = _collect_distinct_values(
|
|
152
|
+
group.hosts,
|
|
153
|
+
[(h.name, h.host_name) for h in group.hosts],
|
|
154
|
+
)
|
|
155
|
+
if len(host_name_options) >= 2:
|
|
156
|
+
conflicts.append(
|
|
157
|
+
FieldConflict(
|
|
158
|
+
field="host_name",
|
|
159
|
+
label="HostName (Schreibweise)",
|
|
160
|
+
options=host_name_options,
|
|
161
|
+
allow_empty=False,
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
identity_options = _collect_distinct_values(
|
|
166
|
+
group.hosts,
|
|
167
|
+
[(h.name, h.identity) for h in group.hosts],
|
|
168
|
+
)
|
|
169
|
+
if len(identity_options) >= 2:
|
|
170
|
+
conflicts.append(
|
|
171
|
+
FieldConflict(
|
|
172
|
+
field="identity",
|
|
173
|
+
label="Identity Profile",
|
|
174
|
+
options=identity_options,
|
|
175
|
+
allow_empty=True,
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
identity_file_options = _collect_distinct_values(
|
|
180
|
+
group.hosts,
|
|
181
|
+
[(h.name, h.identity_file) for h in group.hosts],
|
|
182
|
+
)
|
|
183
|
+
if len(identity_file_options) >= 2:
|
|
184
|
+
conflicts.append(
|
|
185
|
+
FieldConflict(
|
|
186
|
+
field="identity_file",
|
|
187
|
+
label="IdentityFile",
|
|
188
|
+
options=identity_file_options,
|
|
189
|
+
allow_empty=True,
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
canonical_extras = _collect_extra_key_map(group.hosts)
|
|
194
|
+
for key_lower in sorted(canonical_extras.keys()):
|
|
195
|
+
canonical_key = canonical_extras[key_lower]
|
|
196
|
+
extra_options = _collect_distinct_values(
|
|
197
|
+
group.hosts,
|
|
198
|
+
[(h.name, _get_extra_value_ci(h, key_lower)) for h in group.hosts],
|
|
199
|
+
)
|
|
200
|
+
if len(extra_options) >= 2:
|
|
201
|
+
conflicts.append(
|
|
202
|
+
FieldConflict(
|
|
203
|
+
field=f"extra:{canonical_key}",
|
|
204
|
+
label=f"Extra: {canonical_key}",
|
|
205
|
+
options=extra_options,
|
|
206
|
+
allow_empty=True,
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
return conflicts
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def default_conflict_choices(
|
|
214
|
+
group: DuplicateGroup,
|
|
215
|
+
primary_host_id: str,
|
|
216
|
+
conflicts: list[FieldConflict],
|
|
217
|
+
) -> dict[str, str | None]:
|
|
218
|
+
"""Waehlt pro Konflikt den Wert des Primary-Hosts (oder den ersten verfuegbaren Wert)."""
|
|
219
|
+
primary = group.get_host_by_id(primary_host_id)
|
|
220
|
+
choices: dict[str, str | None] = {}
|
|
221
|
+
|
|
222
|
+
for conflict in conflicts:
|
|
223
|
+
selected: str | None = None
|
|
224
|
+
if primary is not None:
|
|
225
|
+
if conflict.field == "host_name" and primary.host_name.strip():
|
|
226
|
+
selected = primary.host_name.strip()
|
|
227
|
+
elif conflict.field == "identity" and primary.identity:
|
|
228
|
+
selected = primary.identity.strip()
|
|
229
|
+
elif conflict.field == "identity_file" and primary.identity_file:
|
|
230
|
+
selected = primary.identity_file.strip()
|
|
231
|
+
elif conflict.field.startswith("extra:"):
|
|
232
|
+
key_lower = conflict.field.removeprefix("extra:").lower()
|
|
233
|
+
val = _get_extra_value_ci(primary, key_lower)
|
|
234
|
+
if val is not None and val.strip():
|
|
235
|
+
selected = val.strip()
|
|
236
|
+
|
|
237
|
+
if selected is None and conflict.options:
|
|
238
|
+
selected = conflict.options[0].value
|
|
239
|
+
|
|
240
|
+
choices[conflict.field] = selected
|
|
241
|
+
|
|
242
|
+
return choices
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _ordered_hosts(group: DuplicateGroup, primary: HostEntry) -> list[HostEntry]:
|
|
246
|
+
return [primary, *(host for host in group.hosts if host.id != primary.id)]
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _first_non_empty(values: list[str | None]) -> str | None:
|
|
250
|
+
for value in values:
|
|
251
|
+
if value is not None and value.strip():
|
|
252
|
+
return value.strip()
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _merge_unique_list(lists: list[list[str]]) -> list[str]:
|
|
257
|
+
result: list[str] = []
|
|
258
|
+
seen: set[str] = set()
|
|
259
|
+
for items in lists:
|
|
260
|
+
for item in items:
|
|
261
|
+
cleaned = item.strip()
|
|
262
|
+
if cleaned and cleaned not in seen:
|
|
263
|
+
result.append(cleaned)
|
|
264
|
+
seen.add(cleaned)
|
|
265
|
+
return result
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def build_merged_host(
|
|
269
|
+
group: DuplicateGroup,
|
|
270
|
+
primary_host_id: str,
|
|
271
|
+
target_name: str,
|
|
272
|
+
resolved_fields: dict[str, str | None] | None = None,
|
|
273
|
+
) -> HostEntry:
|
|
274
|
+
"""Erstellt den zusammengefuehrten Host auf Basis des Primary-Hosts und der Konfliktwahlen."""
|
|
275
|
+
primary = group.get_host_by_id(primary_host_id)
|
|
276
|
+
if primary is None:
|
|
277
|
+
raise ValueError(f"Primary-Host '{primary_host_id}' ist nicht in der Gruppe enthalten")
|
|
278
|
+
|
|
279
|
+
resolved = resolved_fields or {}
|
|
280
|
+
ordered = _ordered_hosts(group, primary)
|
|
281
|
+
|
|
282
|
+
merged = copy.deepcopy(primary)
|
|
283
|
+
merged.name = target_name.strip()
|
|
284
|
+
merged.enabled = True
|
|
285
|
+
|
|
286
|
+
if "host_name" in resolved and resolved["host_name"]:
|
|
287
|
+
merged.host_name = resolved["host_name"]
|
|
288
|
+
else:
|
|
289
|
+
merged.host_name = primary.host_name.strip()
|
|
290
|
+
|
|
291
|
+
merged.user = _first_non_empty([h.user for h in ordered])
|
|
292
|
+
|
|
293
|
+
merged.port = next((h.port for h in ordered if h.port is not None), None)
|
|
294
|
+
|
|
295
|
+
if "identity" in resolved:
|
|
296
|
+
merged.identity = resolved["identity"]
|
|
297
|
+
else:
|
|
298
|
+
merged.identity = _first_non_empty([h.identity for h in ordered])
|
|
299
|
+
|
|
300
|
+
if "identity_file" in resolved:
|
|
301
|
+
merged.identity_file = resolved["identity_file"]
|
|
302
|
+
else:
|
|
303
|
+
merged.identity_file = _first_non_empty([h.identity_file for h in ordered])
|
|
304
|
+
|
|
305
|
+
merged.groups = _merge_unique_list([h.groups for h in ordered])
|
|
306
|
+
merged.tags = _merge_unique_list([h.tags for h in ordered])
|
|
307
|
+
|
|
308
|
+
canonical_extras = _collect_extra_key_map(ordered)
|
|
309
|
+
resolved_extra_ci: dict[str, str | None] = {}
|
|
310
|
+
for field_name, field_value in resolved.items():
|
|
311
|
+
if field_name.startswith("extra:"):
|
|
312
|
+
resolved_extra_ci[field_name.removeprefix("extra:").lower()] = field_value
|
|
313
|
+
|
|
314
|
+
merged_extras: dict[str, str] = {}
|
|
315
|
+
for key_lower in sorted(canonical_extras.keys()):
|
|
316
|
+
canonical_key = canonical_extras[key_lower]
|
|
317
|
+
if key_lower in resolved_extra_ci:
|
|
318
|
+
chosen = resolved_extra_ci[key_lower]
|
|
319
|
+
if chosen is not None and chosen.strip():
|
|
320
|
+
merged_extras[canonical_key] = chosen.strip()
|
|
321
|
+
else:
|
|
322
|
+
value = _first_non_empty([_get_extra_value_ci(h, key_lower) for h in ordered])
|
|
323
|
+
if value is not None:
|
|
324
|
+
merged_extras[canonical_key] = value
|
|
325
|
+
|
|
326
|
+
merged.extra_options = merged_extras
|
|
327
|
+
return merged
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def apply_merge(
|
|
331
|
+
db: HostDatabase,
|
|
332
|
+
plan: MergePlan,
|
|
333
|
+
) -> tuple[HostDatabase, HostEntry, list[str]]:
|
|
334
|
+
"""Wendet einen MergePlan transaktional auf einer Kopie der Datenbank an."""
|
|
335
|
+
candidate_db = copy.deepcopy(db)
|
|
336
|
+
|
|
337
|
+
primary_in_db = candidate_db.get_by_id(plan.primary_host_id)
|
|
338
|
+
if primary_in_db is None:
|
|
339
|
+
return candidate_db, HostEntry(), ["Primary-Host nicht in der Datenbank gefunden"]
|
|
340
|
+
|
|
341
|
+
merged = build_merged_host(
|
|
342
|
+
group=plan.group,
|
|
343
|
+
primary_host_id=plan.primary_host_id,
|
|
344
|
+
target_name=plan.target_name,
|
|
345
|
+
resolved_fields=plan.resolved_fields,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
primary_index = candidate_db.hosts.index(primary_in_db)
|
|
349
|
+
candidate_db.hosts[primary_index] = merged
|
|
350
|
+
|
|
351
|
+
duplicate_ids = {host.id for host in plan.group.hosts if host.id != plan.primary_host_id}
|
|
352
|
+
if plan.disposition == "delete":
|
|
353
|
+
candidate_db.hosts = [h for h in candidate_db.hosts if h.id not in duplicate_ids]
|
|
354
|
+
elif plan.disposition == "disable":
|
|
355
|
+
for host in candidate_db.hosts:
|
|
356
|
+
if host.id in duplicate_ids:
|
|
357
|
+
host.enabled = False
|
|
358
|
+
else:
|
|
359
|
+
return candidate_db, merged, [f"Unbekannte Merge-Aktion: {plan.disposition}"]
|
|
360
|
+
|
|
361
|
+
candidate_db.ensure_groups(merged.groups)
|
|
362
|
+
errors = candidate_db.validate()
|
|
363
|
+
return candidate_db, merged, errors
|