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/identities.py ADDED
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from .model import HostDatabase, IdentityProfile
6
+
7
+ IGNORED_FILES = {
8
+ "config",
9
+ "known_hosts",
10
+ "known_hosts.old",
11
+ "authorized_keys",
12
+ }
13
+
14
+
15
+ def _parse_public_key_preview(public_key_file: Path) -> str | None:
16
+ try:
17
+ line = public_key_file.read_text(encoding="utf-8").splitlines()[0].strip()
18
+ except (OSError, IndexError):
19
+ return None
20
+
21
+ parts = line.split()
22
+ if not parts:
23
+ return None
24
+
25
+ key_type = parts[0]
26
+ comment = parts[2] if len(parts) >= 3 else ""
27
+ if comment:
28
+ return f"{key_type} {comment}"
29
+ return key_type
30
+
31
+
32
+ def discover_ssh_identities(ssh_dir: Path | None = None) -> list[IdentityProfile]:
33
+ base_dir = ssh_dir or (Path.home() / ".ssh")
34
+ if not base_dir.exists() or not base_dir.is_dir():
35
+ return []
36
+
37
+ identities: list[IdentityProfile] = []
38
+ for candidate in sorted(base_dir.iterdir(), key=lambda path: path.name.lower()):
39
+ if not candidate.is_file():
40
+ continue
41
+ if candidate.name in IGNORED_FILES:
42
+ continue
43
+ if candidate.suffix == ".pub":
44
+ continue
45
+
46
+ public_key_candidate = candidate.with_name(candidate.name + ".pub")
47
+ if not public_key_candidate.exists():
48
+ # Fuer den Start nehmen wir nur Keys mit vorhandenem Public-Key-File auf,
49
+ # um den Datensatz in der UI besser erklaeren zu koennen.
50
+ continue
51
+
52
+ preview = _parse_public_key_preview(public_key_candidate)
53
+ identities.append(
54
+ IdentityProfile(
55
+ name=candidate.name,
56
+ identity_file=str(candidate),
57
+ source="local-ssh",
58
+ public_key_file=str(public_key_candidate),
59
+ public_key_preview=preview,
60
+ enabled=True,
61
+ )
62
+ )
63
+
64
+ return identities
65
+
66
+
67
+ def merge_discovered_identities(
68
+ db: HostDatabase, discovered: list[IdentityProfile]
69
+ ) -> tuple[int, int]:
70
+ existing_by_name = {identity.name: identity for identity in db.identities}
71
+ existing_paths = {identity.identity_file for identity in db.identities}
72
+
73
+ created = 0
74
+ updated = 0
75
+
76
+ for profile in discovered:
77
+ existing = existing_by_name.get(profile.name)
78
+ if existing:
79
+ existing.identity_file = profile.identity_file
80
+ existing.source = profile.source
81
+ existing.public_key_file = profile.public_key_file
82
+ existing.public_key_preview = profile.public_key_preview
83
+ updated += 1
84
+ continue
85
+
86
+ if profile.identity_file in existing_paths:
87
+ # Bereits durch ein anderes Profil abgedeckt.
88
+ continue
89
+
90
+ db.identities.append(profile)
91
+ existing_by_name[profile.name] = profile
92
+ existing_paths.add(profile.identity_file)
93
+ created += 1
94
+
95
+ return created, updated
sshcnfgr/importer.py ADDED
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from pathlib import Path
5
+
6
+ from loguru import logger
7
+
8
+ from .model import HostDatabase, HostEntry
9
+
10
+ DIRECTIVE_SPLIT_RE = re.compile(r"(?:[ \t]*=[ \t]*|[ \t]+)")
11
+
12
+ KNOWN_DIRECTIVES = {
13
+ "hostname": "host_name",
14
+ "user": "user",
15
+ "port": "port",
16
+ "identityfile": "identity_file",
17
+ }
18
+
19
+
20
+ class ImportReport:
21
+ def __init__(self) -> None:
22
+ self.imported_hosts = 0
23
+ self.renamed_hosts = 0
24
+ self.warnings: list[str] = []
25
+
26
+ def summary(self) -> str:
27
+ return (
28
+ f"imported={self.imported_hosts}, renamed={self.renamed_hosts}, "
29
+ f"warnings={len(self.warnings)}"
30
+ )
31
+
32
+
33
+ def _unique_name(candidate: str, seen: set[str]) -> tuple[str, bool]:
34
+ if candidate not in seen:
35
+ return candidate, False
36
+
37
+ index = 1
38
+ while f"{candidate}-{index}" in seen:
39
+ index += 1
40
+ return f"{candidate}-{index}", True
41
+
42
+
43
+ def import_ssh_config(path: Path) -> tuple[HostDatabase, ImportReport]:
44
+ report = ImportReport()
45
+ if not path.exists():
46
+ raise FileNotFoundError(f"Config nicht gefunden: {path}")
47
+
48
+ hosts: list[HostEntry] = []
49
+ global_options: dict[str, str] = {}
50
+ seen_names: set[str] = set()
51
+ current_hosts: list[HostEntry] = []
52
+ in_host_wildcard = False
53
+ in_skipped_host = False
54
+ seen_host_block = False
55
+
56
+ for line_number, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
57
+ line = raw_line.strip()
58
+ if not line or line.startswith("#"):
59
+ continue
60
+
61
+ parts = DIRECTIVE_SPLIT_RE.split(line, maxsplit=1)
62
+ if len(parts) != 2 or not parts[0] or not parts[1]:
63
+ report.warnings.append(f"Zeile {line_number}: kann nicht geparst werden: {raw_line}")
64
+ continue
65
+
66
+ key, value = parts[0], parts[1].strip()
67
+ key_lower = key.lower()
68
+
69
+ if key_lower == "match":
70
+ # Match-Bloecke werden noch nicht modelliert; sie muessen aber den vorherigen
71
+ # Host-Block beenden, damit ihre Direktiven nicht in andere Hosts leaken.
72
+ current_hosts = []
73
+ in_host_wildcard = False
74
+ in_skipped_host = True
75
+ seen_host_block = True
76
+ report.warnings.append(
77
+ f"Zeile {line_number}: Match-Block '{value}' wird aktuell uebersprungen"
78
+ )
79
+ continue
80
+
81
+ if key_lower == "host":
82
+ names = [token for token in value.split() if token]
83
+ current_hosts = []
84
+ in_host_wildcard = names == ["*"]
85
+ in_skipped_host = False
86
+ seen_host_block = True
87
+
88
+ if in_host_wildcard:
89
+ continue
90
+
91
+ for name in names:
92
+ if any(ch in name for ch in "*?!"):
93
+ report.warnings.append(
94
+ f"Zeile {line_number}: Wildcard-Host '{name}' wurde uebersprungen"
95
+ )
96
+ continue
97
+
98
+ unique_name, renamed = _unique_name(name, seen_names)
99
+ seen_names.add(unique_name)
100
+
101
+ host = HostEntry(name=unique_name, host_name=unique_name, enabled=True)
102
+ current_hosts.append(host)
103
+ hosts.append(host)
104
+ report.imported_hosts += 1
105
+ if renamed:
106
+ report.renamed_hosts += 1
107
+ report.warnings.append(
108
+ f"Zeile {line_number}: Host '{name}' umbenannt zu '{unique_name}'"
109
+ )
110
+
111
+ # Komplett uebersprungene Bloecke (z. B. nur Wildcards) duerfen ihre
112
+ # Direktiven nicht an nachfolgende Hosts oder global_options verlieren.
113
+ in_skipped_host = not current_hosts
114
+ continue
115
+
116
+ if in_host_wildcard:
117
+ global_options[key] = value
118
+ continue
119
+
120
+ if in_skipped_host:
121
+ report.warnings.append(
122
+ f"Zeile {line_number}: Direktive fuer uebersprungenen Host-Block ignoriert ({key})"
123
+ )
124
+ continue
125
+
126
+ if not seen_host_block:
127
+ # Direktiven vor dem ersten Host-Block (inkl. Include) gelten in
128
+ # OpenSSH als globale Defaults und gehoeren nicht an einen Host.
129
+ global_options[key] = value
130
+ continue
131
+
132
+ for host in current_hosts:
133
+ field_name = KNOWN_DIRECTIVES.get(key_lower)
134
+ if field_name == "host_name":
135
+ host.host_name = value
136
+ elif field_name == "user":
137
+ host.user = value
138
+ elif field_name == "port":
139
+ try:
140
+ host.port = int(value)
141
+ except ValueError:
142
+ report.warnings.append(
143
+ f"Zeile {line_number}: Port '{value}' ist ungueltig fuer Host '{host.name}'"
144
+ )
145
+ elif field_name == "identity_file":
146
+ host.identity_file = value
147
+ else:
148
+ host.extra_options[key] = value
149
+
150
+ logger.info("Import abgeschlossen: {}", report.summary())
151
+ db = HostDatabase(hosts=hosts, global_options=global_options)
152
+ return db, report
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ from loguru import logger
7
+
8
+
9
+ def configure_logging(
10
+ verbose: bool = False,
11
+ *,
12
+ console: bool = True,
13
+ log_file: Path | None = None,
14
+ ) -> None:
15
+ """Konfiguriert Loguru ohne ungefragt lokale Dateien anzulegen."""
16
+ logger.remove()
17
+
18
+ if console:
19
+ console_level = "DEBUG" if verbose else "INFO"
20
+ console_format = (
21
+ "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | "
22
+ "<cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>"
23
+ )
24
+ logger.add(
25
+ sys.stderr,
26
+ level=console_level,
27
+ format=console_format,
28
+ backtrace=False,
29
+ diagnose=False,
30
+ )
31
+
32
+ if log_file is not None:
33
+ log_file.parent.mkdir(parents=True, exist_ok=True)
34
+ logger.add(
35
+ str(log_file),
36
+ level="DEBUG",
37
+ rotation="5 MB",
38
+ retention="10 days",
39
+ format=(
40
+ "{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | "
41
+ "{name}:{function}:{line} - {message}"
42
+ ),
43
+ backtrace=True,
44
+ diagnose=False,
45
+ )
sshcnfgr/model.py ADDED
@@ -0,0 +1,231 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from uuid import uuid4
5
+
6
+
7
+ def get_option_ci(options: dict[str, str], key: str) -> str | None:
8
+ """Liest eine OpenSSH-Direktive case-insensitive aus einem Options-Dict."""
9
+ if key in options:
10
+ return options[key]
11
+ key_lower = key.lower()
12
+ for existing_key, value in options.items():
13
+ if existing_key.lower() == key_lower:
14
+ return value
15
+ return None
16
+
17
+
18
+ @dataclass(slots=True)
19
+ class HostGroup:
20
+ name: str
21
+ description: str = ""
22
+ identity: str | None = None
23
+
24
+ def validate(self) -> list[str]:
25
+ errors: list[str] = []
26
+ if not self.name:
27
+ errors.append("group.name darf nicht leer sein")
28
+ if " " in self.name:
29
+ errors.append("group.name darf keine Leerzeichen enthalten")
30
+ if self.identity is not None and " " in self.identity:
31
+ errors.append("group.identity darf keine Leerzeichen enthalten")
32
+ return errors
33
+
34
+
35
+ @dataclass(slots=True)
36
+ class IdentityProfile:
37
+ name: str
38
+ identity_file: str
39
+ source: str = "manual"
40
+ public_key_file: str | None = None
41
+ public_key_preview: str | None = None
42
+ enabled: bool = True
43
+
44
+ def validate(self) -> list[str]:
45
+ errors: list[str] = []
46
+ if not self.name:
47
+ errors.append("identity.name darf nicht leer sein")
48
+ if " " in self.name:
49
+ errors.append("identity.name darf keine Leerzeichen enthalten")
50
+ if not self.identity_file:
51
+ errors.append("identity.identity_file darf nicht leer sein")
52
+ return errors
53
+
54
+
55
+ @dataclass(slots=True)
56
+ class HostEntry:
57
+ id: str = field(default_factory=lambda: str(uuid4()))
58
+ name: str = ""
59
+ enabled: bool = True
60
+ host_name: str = ""
61
+ user: str | None = None
62
+ port: int | None = None
63
+ identity: str | None = None
64
+ identity_file: str | None = None
65
+ groups: list[str] = field(default_factory=list)
66
+ tags: list[str] = field(default_factory=list)
67
+ extra_options: dict[str, str] = field(default_factory=dict)
68
+
69
+ def validate(self) -> list[str]:
70
+ errors: list[str] = []
71
+
72
+ if not self.name:
73
+ errors.append("name darf nicht leer sein")
74
+ if " " in self.name:
75
+ errors.append("name darf keine Leerzeichen enthalten")
76
+ if not self.host_name:
77
+ errors.append("host_name darf nicht leer sein")
78
+ if self.port is not None and not (1 <= self.port <= 65535):
79
+ errors.append("port muss zwischen 1 und 65535 liegen")
80
+ if self.identity is not None and " " in self.identity:
81
+ errors.append("identity darf keine Leerzeichen enthalten")
82
+ if self.identity_file is not None and not isinstance(self.identity_file, str):
83
+ errors.append("identity_file muss ein String sein")
84
+ if any((not group) or (" " in group) for group in self.groups):
85
+ errors.append("groups duerfen keine leeren Werte oder Leerzeichen enthalten")
86
+
87
+ return errors
88
+
89
+
90
+ @dataclass(slots=True)
91
+ class HostDatabase:
92
+ groups: list[HostGroup] = field(default_factory=list)
93
+ identities: list[IdentityProfile] = field(default_factory=list)
94
+ global_options: dict[str, str] = field(default_factory=dict)
95
+ hosts: list[HostEntry] = field(default_factory=list)
96
+ ui: dict[str, str | bool] = field(default_factory=dict)
97
+
98
+ def validate(self) -> list[str]:
99
+ errors: list[str] = []
100
+ seen_names: set[str] = set()
101
+ seen_groups: set[str] = set()
102
+ seen_identities: set[str] = set()
103
+
104
+ for identity in self.identities:
105
+ identity_errors = identity.validate()
106
+ for err in identity_errors:
107
+ errors.append(f"identity {identity.name or '<leer>'}: {err}")
108
+ if identity.name in seen_identities:
109
+ errors.append(f"identity doppelt vorhanden: {identity.name}")
110
+ seen_identities.add(identity.name)
111
+
112
+ for group in self.groups:
113
+ group_errors = group.validate()
114
+ for err in group_errors:
115
+ errors.append(f"group {group.name or '<leer>'}: {err}")
116
+ if group.name in seen_groups:
117
+ errors.append(f"group doppelt vorhanden: {group.name}")
118
+ seen_groups.add(group.name)
119
+ if group.identity and group.identity not in seen_identities:
120
+ errors.append(
121
+ f"group {group.name}: referenziert unbekannte identity '{group.identity}'"
122
+ )
123
+
124
+ for host in self.hosts:
125
+ host_errors = host.validate()
126
+ for err in host_errors:
127
+ errors.append(f"{host.name or '<leer>'}: {err}")
128
+
129
+ if host.name in seen_names:
130
+ errors.append(f"name doppelt vorhanden: {host.name}")
131
+ seen_names.add(host.name)
132
+
133
+ if host.identity and host.identity not in seen_identities:
134
+ errors.append(
135
+ f"{host.name or '<leer>'}: referenziert unbekannte identity '{host.identity}'"
136
+ )
137
+
138
+ for group_name in host.groups:
139
+ if group_name not in seen_groups:
140
+ errors.append(
141
+ f"{host.name or '<leer>'}: referenziert unbekannte group '{group_name}'"
142
+ )
143
+
144
+ return errors
145
+
146
+ def get_by_id(self, host_id: str) -> HostEntry | None:
147
+ for host in self.hosts:
148
+ if host.id == host_id:
149
+ return host
150
+ return None
151
+
152
+ def sorted_hosts(self) -> list[HostEntry]:
153
+ return sorted(self.hosts, key=lambda h: h.name.lower())
154
+
155
+ def sorted_groups(self) -> list[HostGroup]:
156
+ return sorted(self.groups, key=lambda g: g.name.lower())
157
+
158
+ def sorted_identities(self) -> list[IdentityProfile]:
159
+ return sorted(self.identities, key=lambda i: i.name.lower())
160
+
161
+ def get_group_by_name(self, group_name: str) -> HostGroup | None:
162
+ for group in self.groups:
163
+ if group.name == group_name:
164
+ return group
165
+ return None
166
+
167
+ def get_identity_by_name(self, identity_name: str) -> IdentityProfile | None:
168
+ for identity in self.identities:
169
+ if identity.name == identity_name:
170
+ return identity
171
+ return None
172
+
173
+ def resolve_identity_file(self, host: HostEntry) -> str | None:
174
+ # Prioritaet: expliziter Host-Pfad > Host-Identity-Profil > Gruppen-Identity.
175
+ if host.identity_file:
176
+ return host.identity_file
177
+
178
+ if host.identity:
179
+ identity = self.get_identity_by_name(host.identity)
180
+ if identity and identity.enabled:
181
+ return identity.identity_file
182
+
183
+ for group_name in host.groups:
184
+ group = self.get_group_by_name(group_name)
185
+ if not group or not group.identity:
186
+ continue
187
+ identity = self.get_identity_by_name(group.identity)
188
+ if identity and identity.enabled:
189
+ return identity.identity_file
190
+
191
+ global_identity_file = get_option_ci(self.global_options, "IdentityFile")
192
+ if global_identity_file:
193
+ return global_identity_file
194
+
195
+ return None
196
+
197
+ def resolve_identity_agent(self, host: HostEntry) -> str | None:
198
+ host_agent = get_option_ci(host.extra_options, "IdentityAgent")
199
+ if host_agent is not None:
200
+ return host_agent
201
+ return get_option_ci(self.global_options, "IdentityAgent")
202
+
203
+ def resolve_user(self, host: HostEntry) -> str | None:
204
+ if host.user:
205
+ return host.user
206
+ global_user = get_option_ci(self.global_options, "User")
207
+ if global_user:
208
+ return global_user
209
+ return None
210
+
211
+ def resolve_port(self, host: HostEntry) -> int:
212
+ if host.port is not None:
213
+ return host.port
214
+ global_port = get_option_ci(self.global_options, "Port")
215
+ if global_port:
216
+ try:
217
+ return int(global_port)
218
+ except ValueError:
219
+ pass
220
+ return 22
221
+
222
+ def ensure_groups(self, group_names: list[str]) -> None:
223
+ existing = {group.name for group in self.groups}
224
+ for group_name in group_names:
225
+ if group_name and group_name not in existing:
226
+ self.groups.append(HostGroup(name=group_name))
227
+ existing.add(group_name)
228
+
229
+ def ensure_identity(self, profile: IdentityProfile) -> None:
230
+ if self.get_identity_by_name(profile.name) is None:
231
+ self.identities.append(profile)
sshcnfgr/paths.py ADDED
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ SSH_DIR = Path.home() / ".ssh"
7
+ DB_PATH = SSH_DIR / "sshcnfgr.toml"
8
+ GENERATED_CONFIG_PATH = SSH_DIR / "config.generated"
9
+
10
+ # Rueckwaertskompatible Aliase (Single-File-Design: UI-Settings liegen mit in sshcnfgr.toml)
11
+ APP_DIR = SSH_DIR
12
+ APP_SETTINGS_PATH = DB_PATH
13
+
14
+ # Legacy-Pfade aus 0.1.0a1 fuer nahtlose Uebernahme bestehender Daten
15
+ LEGACY_APP_DIR = Path.home() / ".config" / "sshcnfgr"
16
+ LEGACY_DB_PATH = LEGACY_APP_DIR / "hosts.toml"
17
+ LEGACY_APP_SETTINGS_PATH = LEGACY_APP_DIR / "app.toml"
18
+
19
+
20
+ def set_private_permissions(path: Path) -> None:
21
+ """Setzt 0o600-Dateirechte auf POSIX-Systemen (Linux/macOS); No-Op unter Windows."""
22
+ if os.name == "posix":
23
+ os.chmod(path, 0o600)
24
+
25
+
26
+ def ensure_private_dir(path: Path) -> Path:
27
+ """Stellt sicher, dass ein Zielverzeichnis existiert (0o700 auf POSIX bei Neuanlage)."""
28
+ existed = path.exists()
29
+ path.mkdir(parents=True, exist_ok=True)
30
+ if not existed and os.name == "posix":
31
+ os.chmod(path, 0o700)
32
+ return path
33
+
34
+
35
+ def ensure_app_dir() -> Path:
36
+ """Stellt sicher, dass ~/.ssh existiert."""
37
+ return ensure_private_dir(SSH_DIR)
sshcnfgr/settings.py ADDED
@@ -0,0 +1,87 @@
1
+ from __future__ import annotations
2
+
3
+ import tomllib
4
+ from pathlib import Path
5
+
6
+ import tomli_w
7
+
8
+ from .paths import (
9
+ DB_PATH,
10
+ LEGACY_APP_SETTINGS_PATH,
11
+ SSH_DIR,
12
+ ensure_private_dir,
13
+ set_private_permissions,
14
+ )
15
+
16
+ DEFAULT_DARK_THEME = "textual-dark"
17
+ DEFAULT_LIGHT_THEME = "textual-light"
18
+
19
+
20
+ def _read_ui_table(path: Path) -> dict[str, object] | None:
21
+ if not path.exists():
22
+ return None
23
+ try:
24
+ raw = tomllib.loads(path.read_text(encoding="utf-8"))
25
+ except (OSError, tomllib.TOMLDecodeError):
26
+ return None
27
+ ui_data = raw.get("ui")
28
+ return ui_data if isinstance(ui_data, dict) else None
29
+
30
+
31
+ def load_ui_theme(path: Path | None = None) -> bool:
32
+ """Liest den Dark-Mode-Status aus der zentralen sshcnfgr.toml.
33
+
34
+ Rueckgabe: True = dark, False = light.
35
+ """
36
+ return load_ui_theme_name(path) != DEFAULT_LIGHT_THEME
37
+
38
+
39
+ def load_ui_theme_name(path: Path | None = None) -> str:
40
+ """Liest den gespeicherten Textual-Theme-Namen aus sshcnfgr.toml (mit Legacy-Fallback)."""
41
+ target = path if path is not None else DB_PATH
42
+ ui_data = _read_ui_table(target)
43
+ if ui_data is None and path is None:
44
+ ui_data = _read_ui_table(LEGACY_APP_SETTINGS_PATH)
45
+ if ui_data is None:
46
+ return DEFAULT_DARK_THEME
47
+
48
+ theme_name = ui_data.get("theme")
49
+ if isinstance(theme_name, str) and theme_name.strip():
50
+ return theme_name.strip()
51
+
52
+ is_dark = bool(ui_data.get("dark", True))
53
+ return DEFAULT_DARK_THEME if is_dark else DEFAULT_LIGHT_THEME
54
+
55
+
56
+ def save_ui_theme(dark: bool, path: Path | None = None) -> None:
57
+ """Speichert den Dark-Mode-Status in sshcnfgr.toml."""
58
+ theme_name = DEFAULT_DARK_THEME if dark else DEFAULT_LIGHT_THEME
59
+ save_ui_theme_name(theme_name, path)
60
+
61
+
62
+ def save_ui_theme_name(theme_name: str, path: Path | None = None) -> None:
63
+ """Speichert den Textual-Theme-Namen im [ui]-Abschnitt der zentralen sshcnfgr.toml."""
64
+ target = path if path is not None else DB_PATH
65
+ if target.parent == SSH_DIR:
66
+ ensure_private_dir(target.parent)
67
+ else:
68
+ target.parent.mkdir(parents=True, exist_ok=True)
69
+
70
+ payload: dict[str, object] = {}
71
+ if target.exists():
72
+ try:
73
+ loaded = tomllib.loads(target.read_text(encoding="utf-8"))
74
+ if isinstance(loaded, dict):
75
+ payload = loaded
76
+ except (OSError, tomllib.TOMLDecodeError):
77
+ payload = {}
78
+
79
+ payload["ui"] = {
80
+ "theme": theme_name,
81
+ "dark": theme_name != DEFAULT_LIGHT_THEME,
82
+ }
83
+
84
+ tmp_path = target.with_name(target.name + ".tmp")
85
+ tmp_path.write_text(tomli_w.dumps(payload), encoding="utf-8")
86
+ set_private_permissions(tmp_path)
87
+ tmp_path.replace(target)