hiramedbc 0.1.1__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.
- hiramedbc/__init__.py +11 -0
- hiramedbc/__main__.py +3 -0
- hiramedbc/cli.py +149 -0
- hiramedbc/commands/__init__.py +0 -0
- hiramedbc/commands/add.py +334 -0
- hiramedbc/commands/common.py +211 -0
- hiramedbc/commands/config.py +36 -0
- hiramedbc/commands/connect.py +41 -0
- hiramedbc/commands/doctor.py +278 -0
- hiramedbc/commands/dump.py +110 -0
- hiramedbc/commands/edit.py +22 -0
- hiramedbc/commands/init.py +86 -0
- hiramedbc/commands/list.py +54 -0
- hiramedbc/commands/remove.py +36 -0
- hiramedbc/commands/version.py +6 -0
- hiramedbc/config/__init__.py +0 -0
- hiramedbc/config/manager.py +139 -0
- hiramedbc/config/schema.py +209 -0
- hiramedbc/config/validator.py +62 -0
- hiramedbc/context.py +43 -0
- hiramedbc/docker/__init__.py +0 -0
- hiramedbc/docker/image.py +86 -0
- hiramedbc/docker/option_file.py +79 -0
- hiramedbc/docker/runner.py +358 -0
- hiramedbc/prompts/__init__.py +0 -0
- hiramedbc/prompts/auth.py +133 -0
- hiramedbc/secrets/__init__.py +0 -0
- hiramedbc/secrets/keychain.py +81 -0
- hiramedbc/utils/__init__.py +0 -0
- hiramedbc/utils/aliases.py +77 -0
- hiramedbc/utils/console.py +30 -0
- hiramedbc/utils/errors.py +41 -0
- hiramedbc/utils/platform.py +84 -0
- hiramedbc-0.1.1.dist-info/METADATA +182 -0
- hiramedbc-0.1.1.dist-info/RECORD +38 -0
- hiramedbc-0.1.1.dist-info/WHEEL +4 -0
- hiramedbc-0.1.1.dist-info/entry_points.txt +2 -0
- hiramedbc-0.1.1.dist-info/licenses/LICENSE +21 -0
hiramedbc/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""HirameDBC: a CLI for switching between MySQL client versions running on Docker."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("hiramedbc")
|
|
7
|
+
except PackageNotFoundError: # pragma: no cover - when run directly from the source tree
|
|
8
|
+
__version__ = "0.0.0+unknown"
|
|
9
|
+
|
|
10
|
+
APP_NAME = "hiramedbc"
|
|
11
|
+
"""Name used for the config directory, the keychain service name, and the container name prefix."""
|
hiramedbc/__main__.py
ADDED
hiramedbc/cli.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""CLI entry point.
|
|
2
|
+
|
|
3
|
+
- Command aliases (`c` -> `connect`, etc.) are resolved in one place: HirameGroup.get_command.
|
|
4
|
+
- If the first argument matches no command name or alias, `connect` is inserted (`hirame production`).
|
|
5
|
+
- The global `--config` option is accepted before or after the subcommand.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Annotated, Any
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
from typer.core import TyperGroup
|
|
12
|
+
|
|
13
|
+
from hiramedbc.context import RAW_ARGS_KEY, AppContext
|
|
14
|
+
from hiramedbc.utils import console as out
|
|
15
|
+
from hiramedbc.utils.aliases import alias_of, resolve_command_name
|
|
16
|
+
from hiramedbc.utils.errors import HirameError
|
|
17
|
+
|
|
18
|
+
CONFIG_OPTION = "--config"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def normalize_args(args: list[str]) -> list[str]:
|
|
22
|
+
"""Move `--config` to the front, and insert `connect` if the command name is omitted.
|
|
23
|
+
|
|
24
|
+
Arguments after `--` are passed to the external command untouched.
|
|
25
|
+
"""
|
|
26
|
+
if "--" in args:
|
|
27
|
+
split = args.index("--")
|
|
28
|
+
head, tail = args[:split], args[split:]
|
|
29
|
+
else:
|
|
30
|
+
head, tail = list(args), []
|
|
31
|
+
|
|
32
|
+
hoisted: list[str] = []
|
|
33
|
+
rest: list[str] = []
|
|
34
|
+
i = 0
|
|
35
|
+
while i < len(head):
|
|
36
|
+
token = head[i]
|
|
37
|
+
if token == CONFIG_OPTION and i + 1 < len(head):
|
|
38
|
+
hoisted += [token, head[i + 1]]
|
|
39
|
+
i += 2
|
|
40
|
+
continue
|
|
41
|
+
if token.startswith(CONFIG_OPTION + "="):
|
|
42
|
+
hoisted.append(token)
|
|
43
|
+
else:
|
|
44
|
+
rest.append(token)
|
|
45
|
+
i += 1
|
|
46
|
+
|
|
47
|
+
for token in rest:
|
|
48
|
+
if token.startswith("-"):
|
|
49
|
+
if token in ("--help", "-h"):
|
|
50
|
+
break
|
|
51
|
+
continue
|
|
52
|
+
if resolve_command_name(token) is None:
|
|
53
|
+
# Insert at the front so connect options placed first, as in `hirame --ask-user prod`, still parse
|
|
54
|
+
rest.insert(0, "connect")
|
|
55
|
+
break
|
|
56
|
+
|
|
57
|
+
return hoisted + rest + tail
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class HirameGroup(TyperGroup):
|
|
61
|
+
def get_command(self, ctx: Any, cmd_name: str) -> Any:
|
|
62
|
+
return super().get_command(ctx, resolve_command_name(cmd_name) or cmd_name)
|
|
63
|
+
|
|
64
|
+
def parse_args(self, ctx: Any, args: list[str]) -> list[str]:
|
|
65
|
+
normalized = normalize_args(args)
|
|
66
|
+
# click strips `--`, so keep the original order for commands (dump) that need to tell arguments after `--` apart
|
|
67
|
+
ctx.meta[RAW_ARGS_KEY] = list(normalized)
|
|
68
|
+
return super().parse_args(ctx, normalized)
|
|
69
|
+
|
|
70
|
+
def invoke(self, ctx: Any) -> Any:
|
|
71
|
+
try:
|
|
72
|
+
return super().invoke(ctx)
|
|
73
|
+
except HirameError as e:
|
|
74
|
+
out.error(e.message, e.hint)
|
|
75
|
+
raise typer.Exit(e.exit_code) from None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
app = typer.Typer(
|
|
79
|
+
cls=HirameGroup,
|
|
80
|
+
name="hirame",
|
|
81
|
+
help="HirameDBC: switch between MySQL client versions using the official MySQL Docker image",
|
|
82
|
+
invoke_without_command=True,
|
|
83
|
+
add_completion=False,
|
|
84
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
85
|
+
rich_markup_mode="rich",
|
|
86
|
+
# Do not show local variables (which may contain passwords) in tracebacks. Typer defaults to False, but be explicit
|
|
87
|
+
pretty_exceptions_show_locals=False,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@app.callback()
|
|
92
|
+
def main(
|
|
93
|
+
ctx: typer.Context,
|
|
94
|
+
config: Annotated[
|
|
95
|
+
str | None,
|
|
96
|
+
typer.Option(
|
|
97
|
+
CONFIG_OPTION,
|
|
98
|
+
metavar="PATH",
|
|
99
|
+
help="Path to the config file (takes precedence over the HIRAMEDBC_CONFIG environment variable)",
|
|
100
|
+
),
|
|
101
|
+
] = None,
|
|
102
|
+
) -> None:
|
|
103
|
+
if isinstance(ctx.obj, AppContext): # An AppContext with replaced dependencies was passed in (e.g. by tests)
|
|
104
|
+
ctx.obj.config_option = config
|
|
105
|
+
else:
|
|
106
|
+
ctx.obj = AppContext(config_option=config)
|
|
107
|
+
if ctx.invoked_subcommand is not None:
|
|
108
|
+
return
|
|
109
|
+
help_text = ctx.get_help()
|
|
110
|
+
if help_text:
|
|
111
|
+
typer.echo(help_text)
|
|
112
|
+
if not ctx.obj.manager.exists():
|
|
113
|
+
out.info("\nNo config file yet. Run `hirame init` to start the initial setup.")
|
|
114
|
+
raise typer.Exit(0)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def command_help(name: str, text: str) -> str:
|
|
118
|
+
short = alias_of(name)
|
|
119
|
+
return f"{text} (alias: {short})" if short else text
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _register() -> None:
|
|
123
|
+
from hiramedbc.commands import add, connect, doctor, dump, edit, init, remove, version
|
|
124
|
+
from hiramedbc.commands import config as config_command
|
|
125
|
+
from hiramedbc.commands import list as list_command
|
|
126
|
+
|
|
127
|
+
commands = [
|
|
128
|
+
("init", init.init, "Initial setup (environment check → create config file → add connections → pull images)"),
|
|
129
|
+
("connect", connect.connect, "Connect to a database"),
|
|
130
|
+
("add", add.add, "Add a connection"),
|
|
131
|
+
("list", list_command.list_connections, "List saved connections"),
|
|
132
|
+
("remove", remove.remove, "Remove a connection (also deletes its password from the keychain)"),
|
|
133
|
+
("edit", edit.edit, "Edit a connection"),
|
|
134
|
+
("dump", dump.dump, "Create a dump with mysqldump"),
|
|
135
|
+
("version", version.version, "Show the app version"),
|
|
136
|
+
(
|
|
137
|
+
"doctor",
|
|
138
|
+
doctor.doctor,
|
|
139
|
+
"Check the environment (--pull to pre-pull images, --clean to remove leftover containers)",
|
|
140
|
+
),
|
|
141
|
+
]
|
|
142
|
+
for name, func, text in commands:
|
|
143
|
+
# Show the docstring below the help as a detailed description
|
|
144
|
+
epilog = (func.__doc__ or "").strip() or None
|
|
145
|
+
app.command(name, help=command_help(name, text), epilog=epilog)(func)
|
|
146
|
+
app.add_typer(config_command.config_app, name="config")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
_register()
|
|
File without changes
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""The `add` command, plus the interactive connection form and save logic shared with edit / init."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
from pydantic import ValidationError
|
|
9
|
+
|
|
10
|
+
from hiramedbc.commands.common import find_case_conflict
|
|
11
|
+
from hiramedbc.config.schema import (
|
|
12
|
+
DEFAULT_PORT,
|
|
13
|
+
KEYRING,
|
|
14
|
+
PASSWORD_STORE_ASK,
|
|
15
|
+
PASSWORD_STORE_CONFIG,
|
|
16
|
+
PASSWORD_STORE_KEYCHAIN,
|
|
17
|
+
SSL_MODES,
|
|
18
|
+
AppConfig,
|
|
19
|
+
ConnectionConfig,
|
|
20
|
+
SslConfig,
|
|
21
|
+
validate_version_tag,
|
|
22
|
+
)
|
|
23
|
+
from hiramedbc.context import AppContext, get_app_context
|
|
24
|
+
from hiramedbc.prompts.auth import Prompter
|
|
25
|
+
from hiramedbc.utils import console as out
|
|
26
|
+
from hiramedbc.utils.aliases import validate_alias_name
|
|
27
|
+
from hiramedbc.utils.errors import ConfigError, KeychainError
|
|
28
|
+
|
|
29
|
+
CLEAR = "-"
|
|
30
|
+
"""Value to enter in edit to unset an optional field."""
|
|
31
|
+
|
|
32
|
+
SUGGESTED_VERSION = "8.4"
|
|
33
|
+
|
|
34
|
+
PASSWORD_STORE_LABELS = {
|
|
35
|
+
PASSWORD_STORE_ASK: "Don't save (ask every time)",
|
|
36
|
+
PASSWORD_STORE_CONFIG: "Save in the config file (plaintext)",
|
|
37
|
+
PASSWORD_STORE_KEYCHAIN: "Save in the OS keychain",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
NO_SSL_MODE = "DEFAULT"
|
|
41
|
+
"""Choice for not setting an SSL mode (leave it to the MySQL client default)."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class ConnectionDraft:
|
|
46
|
+
name: str
|
|
47
|
+
conn: ConnectionConfig
|
|
48
|
+
new_password: str | None = field(default=None, repr=False)
|
|
49
|
+
"""New password to store in the keychain. None keeps the saved one unchanged.
|
|
50
|
+
|
|
51
|
+
A password saved in the config file is not held here; it is already in `conn.password`."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _validate_name(config: AppConfig, name: str, current_name: str | None) -> None:
|
|
55
|
+
validate_alias_name(name)
|
|
56
|
+
if current_name and name != current_name and name.lower() == current_name.lower():
|
|
57
|
+
# Keychains that ignore case (such as Windows Credential Manager)
|
|
58
|
+
# cannot safely move the entry
|
|
59
|
+
raise ConfigError(
|
|
60
|
+
f"Cannot change only the case of a connection name ({current_name} → {name}).",
|
|
61
|
+
hint="Use a different name, or remove the connection and add it again.",
|
|
62
|
+
)
|
|
63
|
+
if name != current_name and name in config.connections:
|
|
64
|
+
raise ConfigError(f"Connection {name!r} already exists.", hint="Use `hirame edit` to change it.")
|
|
65
|
+
conflict = find_case_conflict(config, name, exclude=current_name)
|
|
66
|
+
if conflict:
|
|
67
|
+
raise ConfigError(
|
|
68
|
+
f"Cannot add connection {name!r}: it differs from existing {conflict!r} only in case.",
|
|
69
|
+
hint="The keychain (especially Windows Credential Manager) may treat them as the same name.",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _ask_name(prompter: Prompter, config: AppConfig, current_name: str | None) -> str:
|
|
74
|
+
while True:
|
|
75
|
+
name = prompter.ask_text("Connection name", default=current_name)
|
|
76
|
+
try:
|
|
77
|
+
_validate_name(config, name, current_name)
|
|
78
|
+
return name
|
|
79
|
+
except ConfigError as e:
|
|
80
|
+
out.warn(e.message + (f"\n{e.hint}" if e.hint else ""))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _ask_host(prompter: Prompter, current: ConnectionConfig | None) -> str:
|
|
84
|
+
while True:
|
|
85
|
+
host = prompter.ask_text("Host", default=current.host if current else None)
|
|
86
|
+
try:
|
|
87
|
+
return ConnectionConfig(host=host).host
|
|
88
|
+
except ValidationError:
|
|
89
|
+
out.warn("Host names cannot contain whitespace or control characters.")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _ask_port(prompter: Prompter, current: ConnectionConfig | None) -> int:
|
|
93
|
+
while True:
|
|
94
|
+
value = prompter.ask_text("Port", default=str(current.port if current else DEFAULT_PORT))
|
|
95
|
+
# isascii: "²" and full-width digits pass isdigit() but fail int() or give unintended values
|
|
96
|
+
if value.isascii() and value.isdigit() and 1 <= int(value) <= 65535:
|
|
97
|
+
return int(value)
|
|
98
|
+
out.warn("Enter an integer from 1 to 65535.")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _ask_new_password(prompter: Prompter, name: str, *, destination: str, plaintext: bool = False) -> str | None:
|
|
102
|
+
"""Ask for a password twice. With `plaintext`, values that cannot be stored in the config file are rejected."""
|
|
103
|
+
for _ in range(3):
|
|
104
|
+
first = prompter.ask_secret(f"Password for {name} (saved in {destination})")
|
|
105
|
+
second = prompter.ask_secret("Confirm password")
|
|
106
|
+
if first != second:
|
|
107
|
+
out.warn("Passwords do not match.")
|
|
108
|
+
elif plaintext and first.strip() == "":
|
|
109
|
+
out.warn("An empty password cannot be saved in the config file.")
|
|
110
|
+
return None
|
|
111
|
+
elif plaintext and first == KEYRING:
|
|
112
|
+
out.warn(f'The password "{KEYRING}" cannot be saved in the config file (reserved word).')
|
|
113
|
+
return None
|
|
114
|
+
else:
|
|
115
|
+
return first
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _ask_version(prompter: Prompter, config: AppConfig, current: ConnectionConfig | None) -> str | None:
|
|
120
|
+
editing = current is not None
|
|
121
|
+
while True:
|
|
122
|
+
if config.defaults.version:
|
|
123
|
+
if editing and current.version:
|
|
124
|
+
suffix = f" (Enter: keep current, {CLEAR}: use default {config.defaults.version})"
|
|
125
|
+
else:
|
|
126
|
+
suffix = f" (empty: use default {config.defaults.version})"
|
|
127
|
+
value = prompter.ask_text(
|
|
128
|
+
f"MySQL version{suffix}", default=current.version if current else None, allow_empty=True
|
|
129
|
+
)
|
|
130
|
+
if value in ("", CLEAR):
|
|
131
|
+
return None
|
|
132
|
+
else:
|
|
133
|
+
value = prompter.ask_text(
|
|
134
|
+
"MySQL version (e.g. 8.4, 8.0, 5.7)",
|
|
135
|
+
default=(current.version if current and current.version else SUGGESTED_VERSION),
|
|
136
|
+
)
|
|
137
|
+
try:
|
|
138
|
+
return validate_version_tag(value)
|
|
139
|
+
except ValueError as e:
|
|
140
|
+
out.warn(str(e))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _ask_ssl_file(prompter: Prompter, label: str, current: str | None) -> str | None:
|
|
144
|
+
while True:
|
|
145
|
+
value = prompter.ask_text(
|
|
146
|
+
f"{label} path" + (f" (Enter: keep current, {CLEAR}: remove)" if current else " (empty: none)"),
|
|
147
|
+
default=current,
|
|
148
|
+
allow_empty=True,
|
|
149
|
+
)
|
|
150
|
+
if value in ("", CLEAR):
|
|
151
|
+
return None
|
|
152
|
+
path = Path(value).expanduser()
|
|
153
|
+
if path.is_file():
|
|
154
|
+
return str(path.resolve())
|
|
155
|
+
out.warn(f"File {value} not found.")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _ask_ssl(prompter: Prompter, current: ConnectionConfig | None) -> SslConfig | None:
|
|
159
|
+
current_ssl = current.ssl if current else None
|
|
160
|
+
if not prompter.confirm("Configure SSL?", default=current_ssl is not None):
|
|
161
|
+
return None
|
|
162
|
+
if current_ssl is None:
|
|
163
|
+
default_mode = "REQUIRED"
|
|
164
|
+
else:
|
|
165
|
+
default_mode = current_ssl.mode or NO_SSL_MODE
|
|
166
|
+
mode = prompter.choose("SSL mode", [*SSL_MODES, NO_SSL_MODE], default=default_mode)
|
|
167
|
+
ssl = SslConfig(
|
|
168
|
+
mode=None if mode == NO_SSL_MODE else mode,
|
|
169
|
+
ca=_ask_ssl_file(prompter, "CA certificate", current_ssl.ca if current_ssl else None),
|
|
170
|
+
cert=_ask_ssl_file(prompter, "Client certificate", current_ssl.cert if current_ssl else None),
|
|
171
|
+
key=_ask_ssl_file(prompter, "Client private key", current_ssl.key if current_ssl else None),
|
|
172
|
+
)
|
|
173
|
+
return None if ssl.is_empty() else ssl
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def prompt_connection(
|
|
177
|
+
app_ctx: AppContext,
|
|
178
|
+
config: AppConfig,
|
|
179
|
+
*,
|
|
180
|
+
name: str | None = None,
|
|
181
|
+
current_name: str | None = None,
|
|
182
|
+
current: ConnectionConfig | None = None,
|
|
183
|
+
) -> ConnectionDraft:
|
|
184
|
+
"""Ask for the connection settings interactively. In edit, current values are the defaults."""
|
|
185
|
+
prompter = app_ctx.prompter
|
|
186
|
+
if name is not None:
|
|
187
|
+
_validate_name(config, name, current_name)
|
|
188
|
+
else:
|
|
189
|
+
name = _ask_name(prompter, config, current_name)
|
|
190
|
+
|
|
191
|
+
host = _ask_host(prompter, current)
|
|
192
|
+
port = _ask_port(prompter, current)
|
|
193
|
+
|
|
194
|
+
user_fixed = prompter.confirm(
|
|
195
|
+
"Save the user name in the config file? (no: ask every time)",
|
|
196
|
+
default=current.user_fixed if current else True,
|
|
197
|
+
)
|
|
198
|
+
user = prompter.ask_text("User name", default=current.user if current else None) if user_fixed else None
|
|
199
|
+
|
|
200
|
+
password: str | None = None
|
|
201
|
+
new_password: str | None = None
|
|
202
|
+
# If the user name is asked every time, the password cannot be saved (config validation also rejects it)
|
|
203
|
+
if user_fixed:
|
|
204
|
+
store = prompter.choose(
|
|
205
|
+
"Where to save the password?",
|
|
206
|
+
[PASSWORD_STORE_ASK, PASSWORD_STORE_CONFIG, PASSWORD_STORE_KEYCHAIN],
|
|
207
|
+
default=current.password_store if current else PASSWORD_STORE_ASK,
|
|
208
|
+
labels=PASSWORD_STORE_LABELS,
|
|
209
|
+
)
|
|
210
|
+
# If the user name changed, the saved password belongs to the old user, so default to changing it
|
|
211
|
+
user_changed = current is not None and current.user != user
|
|
212
|
+
if store == PASSWORD_STORE_KEYCHAIN:
|
|
213
|
+
has_stored = current is not None and current.password_in_keychain
|
|
214
|
+
if has_stored and not prompter.confirm("Change the saved password?", default=user_changed):
|
|
215
|
+
password = KEYRING
|
|
216
|
+
else:
|
|
217
|
+
new_password = _ask_new_password(prompter, name, destination="keychain")
|
|
218
|
+
if new_password is not None:
|
|
219
|
+
password = KEYRING
|
|
220
|
+
elif has_stored:
|
|
221
|
+
out.warn("Keeping the saved password.")
|
|
222
|
+
password = KEYRING
|
|
223
|
+
elif current is not None and current.plaintext_password is not None:
|
|
224
|
+
out.warn("Keeping the saved password in the config file.")
|
|
225
|
+
password = current.plaintext_password
|
|
226
|
+
else:
|
|
227
|
+
out.warn("Password not saved. It will be asked every time.")
|
|
228
|
+
elif store == PASSWORD_STORE_CONFIG:
|
|
229
|
+
saved_plaintext = current.plaintext_password if current else None
|
|
230
|
+
if saved_plaintext is not None and not prompter.confirm("Change the saved password?", default=user_changed):
|
|
231
|
+
password = saved_plaintext
|
|
232
|
+
else:
|
|
233
|
+
password = _ask_new_password(prompter, name, destination="config file", plaintext=True)
|
|
234
|
+
if password is None and saved_plaintext is not None:
|
|
235
|
+
out.warn("Keeping the saved password.")
|
|
236
|
+
password = saved_plaintext
|
|
237
|
+
elif password is None and current is not None and current.password_in_keychain:
|
|
238
|
+
out.warn("Keeping the saved password in the keychain.")
|
|
239
|
+
password = KEYRING
|
|
240
|
+
elif password is None:
|
|
241
|
+
out.warn("Password not saved. It will be asked every time.")
|
|
242
|
+
|
|
243
|
+
version = _ask_version(prompter, config, current)
|
|
244
|
+
ssl = _ask_ssl(prompter, current)
|
|
245
|
+
conn = ConnectionConfig(host=host, port=port, user=user, password=password, version=version, ssl=ssl)
|
|
246
|
+
return ConnectionDraft(name=name, conn=conn, new_password=new_password)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def save_connection(
|
|
250
|
+
app_ctx: AppContext,
|
|
251
|
+
config: AppConfig,
|
|
252
|
+
draft: ConnectionDraft,
|
|
253
|
+
*,
|
|
254
|
+
old_name: str | None = None,
|
|
255
|
+
) -> AppConfig:
|
|
256
|
+
"""Save the connection to the config file and the keychain.
|
|
257
|
+
|
|
258
|
+
A new password goes into the keychain before the config is saved (on failure, keep using the
|
|
259
|
+
saved password if there is one, otherwise switch to asking every time).
|
|
260
|
+
Renaming and deleting entries no longer needed happen after the config is saved.
|
|
261
|
+
"""
|
|
262
|
+
keychain = app_ctx.keychain
|
|
263
|
+
conn = draft.conn
|
|
264
|
+
old_conn = config.connections.get(old_name) if old_name else None
|
|
265
|
+
|
|
266
|
+
stored_new = False
|
|
267
|
+
previous_password: str | None = None
|
|
268
|
+
had_stored = old_conn is not None and old_conn.password_in_keychain
|
|
269
|
+
if draft.new_password is not None:
|
|
270
|
+
try:
|
|
271
|
+
if had_stored and old_name == draft.name:
|
|
272
|
+
# With the same name the new password overwrites the old entry, so keep it to restore if saving fails
|
|
273
|
+
previous_password = keychain.get(old_name)
|
|
274
|
+
keychain.set(draft.name, draft.new_password)
|
|
275
|
+
stored_new = True
|
|
276
|
+
except KeychainError as e:
|
|
277
|
+
if had_stored:
|
|
278
|
+
# Keep using the saved password (on rename, the old entry is moved after saving)
|
|
279
|
+
out.warn(f"{e.message} Keeping the saved password.")
|
|
280
|
+
elif old_conn is not None and old_conn.plaintext_password is not None:
|
|
281
|
+
out.warn(f"{e.message} Keeping the saved password in the config file.")
|
|
282
|
+
conn = conn.model_copy(update={"password": old_conn.plaintext_password})
|
|
283
|
+
else:
|
|
284
|
+
out.warn(f"{e.message} The password will be asked every time.")
|
|
285
|
+
conn = conn.model_copy(update={"password": None})
|
|
286
|
+
|
|
287
|
+
connections: dict[str, ConnectionConfig] = {}
|
|
288
|
+
for existing_name, existing in config.connections.items():
|
|
289
|
+
if existing_name == old_name:
|
|
290
|
+
connections[draft.name] = conn # Keep the original position when editing
|
|
291
|
+
else:
|
|
292
|
+
connections[existing_name] = existing
|
|
293
|
+
connections.setdefault(draft.name, conn)
|
|
294
|
+
new_config = config.model_copy(update={"connections": connections})
|
|
295
|
+
|
|
296
|
+
try:
|
|
297
|
+
app_ctx.manager.save(new_config)
|
|
298
|
+
except ConfigError:
|
|
299
|
+
if stored_new:
|
|
300
|
+
if previous_password is not None:
|
|
301
|
+
_try_keychain(lambda: keychain.set(draft.name, previous_password))
|
|
302
|
+
else:
|
|
303
|
+
_try_keychain(lambda: keychain.delete(draft.name))
|
|
304
|
+
raise
|
|
305
|
+
|
|
306
|
+
if old_name and old_conn and old_conn.password_in_keychain:
|
|
307
|
+
if not conn.password_in_keychain:
|
|
308
|
+
_try_keychain(lambda: keychain.delete(old_name))
|
|
309
|
+
elif old_name != draft.name:
|
|
310
|
+
if stored_new:
|
|
311
|
+
_try_keychain(lambda: keychain.delete(old_name))
|
|
312
|
+
else:
|
|
313
|
+
_try_keychain(lambda: keychain.rename(old_name, draft.name))
|
|
314
|
+
return new_config
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _try_keychain(operation) -> None: # noqa: ANN001
|
|
318
|
+
try:
|
|
319
|
+
operation()
|
|
320
|
+
except KeychainError as e:
|
|
321
|
+
out.warn(e.message)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def add(
|
|
325
|
+
ctx: typer.Context,
|
|
326
|
+
alias: Annotated[
|
|
327
|
+
str | None, typer.Argument(metavar="[ALIAS]", help="Connection name to add (prompted if omitted)")
|
|
328
|
+
] = None,
|
|
329
|
+
) -> None:
|
|
330
|
+
app_ctx = get_app_context(ctx)
|
|
331
|
+
config = app_ctx.manager.load()
|
|
332
|
+
draft = prompt_connection(app_ctx, config, name=alias)
|
|
333
|
+
save_connection(app_ctx, config, draft)
|
|
334
|
+
out.info(f"Connection [bold]{draft.name}[/bold] added. Connect with `hirame c {draft.name}`.")
|