mirror of
https://github.com/NCBM/plyngent.git
synced 2026-07-23 14:14:57 +08:00
core/cli: open config in $EDITOR with optional prompt
shlex-split EDITOR (e.g. codium --wait); prompt when no providers; add config path/edit commands.
This commit is contained in:
+39
-2
@@ -7,7 +7,11 @@ from typing import TYPE_CHECKING
|
||||
import click
|
||||
import msgspec
|
||||
|
||||
from plyngent import config as config_mod
|
||||
from plyngent.cli.editor import (
|
||||
load_config_with_optional_edit,
|
||||
open_in_editor,
|
||||
resolve_config_path,
|
||||
)
|
||||
from plyngent.cli.repl import run_repl
|
||||
from plyngent.cli.selection import select_model, select_provider
|
||||
from plyngent.cli.state import ReplState
|
||||
@@ -21,7 +25,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
def _load_config(config_path: Path | None) -> ConfigStore:
|
||||
return config_mod.load(config_path)
|
||||
return load_config_with_optional_edit(config_path)
|
||||
|
||||
|
||||
def _database_config(store: ConfigStore) -> DatabaseConfig:
|
||||
@@ -137,5 +141,38 @@ def providers_cmd(config_path: Path | None) -> None:
|
||||
click.secho(f"bad: {', '.join(sorted(store.bad_providers.keys()))}", fg="yellow")
|
||||
|
||||
|
||||
@main.group("config")
|
||||
def config_group() -> None:
|
||||
"""Manage plyngent configuration."""
|
||||
|
||||
|
||||
@config_group.command("path")
|
||||
@click.option(
|
||||
"--config",
|
||||
"config_path",
|
||||
type=click.Path(path_type=Path, dir_okay=False),
|
||||
default=None,
|
||||
help="Override config path (prints the path that would be used).",
|
||||
)
|
||||
def config_path_cmd(config_path: Path | None) -> None:
|
||||
"""Print the resolved config file path."""
|
||||
click.echo(str(resolve_config_path(config_path)))
|
||||
|
||||
|
||||
@config_group.command("edit")
|
||||
@click.option(
|
||||
"--config",
|
||||
"config_path",
|
||||
type=click.Path(path_type=Path, dir_okay=False),
|
||||
default=None,
|
||||
help="Path to plyngent.toml (default: platform config dir).",
|
||||
)
|
||||
def config_edit_cmd(config_path: Path | None) -> None:
|
||||
"""Open the config file in $EDITOR (supports e.g. ``codium --wait``)."""
|
||||
path = resolve_config_path(config_path)
|
||||
open_in_editor(path)
|
||||
click.echo(f"edited {path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import click
|
||||
|
||||
from plyngent import config as config_mod
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from plyngent.config.store import ConfigStore
|
||||
|
||||
_MINIMAL_CONFIG = """\
|
||||
# plyngent configuration
|
||||
# edit providers below
|
||||
|
||||
[database]
|
||||
implementation = "sqlite"
|
||||
url = ":memory:"
|
||||
|
||||
# [providers.example]
|
||||
# preset = "openai-compatible"
|
||||
# url = "https://api.openai.com/v1"
|
||||
# access_key_or_token = "sk-..."
|
||||
#
|
||||
# [providers.example.models]
|
||||
# "gpt-4o-mini" = { text = true }
|
||||
"""
|
||||
|
||||
|
||||
def get_editor() -> str | None:
|
||||
"""Return the ``EDITOR`` environment value, or ``None`` if unset/empty."""
|
||||
value = os.environ.get("EDITOR", "").strip()
|
||||
return value or None
|
||||
|
||||
|
||||
def resolve_config_path(config_path: Path | None) -> Path:
|
||||
"""Resolve CLI ``--config`` or the platform default path."""
|
||||
if config_path is not None:
|
||||
return config_path
|
||||
return Path(config_mod.default_config_source)
|
||||
|
||||
|
||||
def ensure_config_file(path: Path) -> None:
|
||||
"""Create parent dirs and a minimal template if the file does not exist."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not path.exists():
|
||||
_ = path.write_text(_MINIMAL_CONFIG, encoding="utf-8")
|
||||
|
||||
|
||||
def open_in_editor(path: Path, *, editor: str | None = None) -> None:
|
||||
"""Open ``path`` with ``EDITOR`` (supports values like ``codium --wait``)."""
|
||||
editor_cmd = editor if editor is not None else get_editor()
|
||||
if editor_cmd is None:
|
||||
msg = "EDITOR is not set"
|
||||
raise click.ClickException(msg)
|
||||
|
||||
ensure_config_file(path)
|
||||
try:
|
||||
argv = [*shlex.split(editor_cmd, posix=os.name != "nt"), str(path)]
|
||||
except ValueError as exc:
|
||||
msg = f"invalid EDITOR value {editor_cmd!r}: {exc}"
|
||||
raise click.ClickException(msg) from exc
|
||||
if not argv:
|
||||
msg = "EDITOR is empty after parsing"
|
||||
raise click.ClickException(msg)
|
||||
|
||||
try:
|
||||
completed = subprocess.run(argv, check=False)
|
||||
except FileNotFoundError as exc:
|
||||
msg = f"editor executable not found: {argv[0]}"
|
||||
raise click.ClickException(msg) from exc
|
||||
except OSError as exc:
|
||||
msg = f"failed to run editor: {exc}"
|
||||
raise click.ClickException(msg) from exc
|
||||
|
||||
if completed.returncode != 0:
|
||||
msg = f"editor exited with status {completed.returncode}"
|
||||
raise click.ClickException(msg)
|
||||
|
||||
|
||||
def prompt_edit_config(path: Path, *, reason: str | None = None) -> bool:
|
||||
"""If ``EDITOR`` is set, ask whether to edit ``path``. Returns True if opened."""
|
||||
if get_editor() is None:
|
||||
return False
|
||||
message = f"{reason} Edit config file {path}?" if reason else f"Edit config file {path}?"
|
||||
if not click.confirm(message, default=False):
|
||||
return False
|
||||
open_in_editor(path)
|
||||
return True
|
||||
|
||||
|
||||
def load_config_with_optional_edit(config_path: Path | None) -> ConfigStore:
|
||||
"""Load config; if there are no providers and EDITOR is set, offer to edit and reload."""
|
||||
path = resolve_config_path(config_path)
|
||||
store = config_mod.load(path)
|
||||
if store.providers:
|
||||
return store
|
||||
reason = "No providers configured."
|
||||
if not path.exists():
|
||||
reason = f"Config file not found ({path})."
|
||||
if prompt_edit_config(path, reason=reason):
|
||||
store = config_mod.load(path)
|
||||
return store
|
||||
Reference in New Issue
Block a user