rb-keys 0.2.3__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.
rb_keys/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """rb-keys: the shared keys (query, domain, URL) every tool links its records by.
2
+
3
+ `from rb_keys import norm_query, norm_domain, norm_url, KEYS_VERSION`; the contract is
4
+ `vectors/keys-v<KEYS_VERSION>.yaml` in the repository.
5
+ """
6
+
7
+ from .core.normalize import KEYS_VERSION, norm_domain, norm_phrase, norm_query, norm_url
8
+
9
+ __all__ = ["KEYS_VERSION", "norm_domain", "norm_phrase", "norm_query", "norm_url"]
@@ -0,0 +1,24 @@
1
+ """The distribution name and the tool namespace copier writes from its answers, because an editable install cannot map
2
+ this import package to its distribution at runtime.
3
+ """
4
+
5
+ # Rendered by copier from the `dist_name` answer: the [project] name in
6
+ # pyproject.toml (`rb-<slug>`, the Standard, Technology), which may differ from this
7
+ # import package's name. importlib.metadata finds this package's version,
8
+ # summary and console script by it; an editable install (`uv sync`) can't be
9
+ # mapped from package to distribution at runtime, so it is written down here.
10
+ # tests/test_cli.py fails if it drifts from pyproject.toml.
11
+ DIST_NAME = "rb-keys"
12
+ # The previous distribution name during a rename: an install made
13
+ # under it (not yet reinstalled) still finds its own version. Drop it once
14
+ # every machine has the new name.
15
+ DIST_NAME_LEGACY: str | None = None
16
+ # The command name (`cli_name`) as an identifier: the namespace of this tool's
17
+ # shared-database names (core/db.py) — table prefix `<TOOL>_`, env var
18
+ # `<TOOL>_DATABASE_URL`, Alembic table `alembic_version_<TOOL>`. Written down,
19
+ # not derived at runtime: a bare source run falls back to the package name,
20
+ # and a table name must never depend on how the tool was started.
21
+ TOOL = "keys"
22
+ # The cli-generator release this project was generated or last updated from
23
+ # (copier's `_commit`), for `describe --json`; None for a project not made by copier.
24
+ TEMPLATE_VERSION: str | None = "v1.27.3"
@@ -0,0 +1,146 @@
1
+ [project]
2
+ name = "rb-keys"
3
+ # Version comes from the git tag vX.Y.Z (uv-dynamic-versioning) — never add `version =`.
4
+ dynamic = ["version"]
5
+ description = "Shared normalization keys (query, domain, URL) for linking records across tools"
6
+ readme = "README.md"
7
+ authors = [{ name = "Roman Bolandau" }]
8
+ requires-python = ">=3.14"
9
+ dependencies = [
10
+ "typer>=0.27,<0.29",
11
+ "rich>=13.7",
12
+ "pydantic>=2.6",
13
+ "tomli-w>=1.0",
14
+ "platformdirs>=4.2",
15
+ "packaging>=24.0",
16
+ "w3lib>=2.5.0",
17
+ ]
18
+
19
+ [project.scripts]
20
+ keys = "rb_keys.cli:main"
21
+
22
+ [project.urls]
23
+ Repository = "https://github.com/bolandeu/keys"
24
+
25
+ [build-system]
26
+ requires = ["hatchling", "uv-dynamic-versioning"]
27
+ build-backend = "hatchling.build"
28
+
29
+ [tool.hatch.version]
30
+ source = "uv-dynamic-versioning"
31
+
32
+ [tool.uv-dynamic-versioning]
33
+ vcs = "git"
34
+ style = "pep440"
35
+ fallback-version = "0.0.0"
36
+
37
+ [tool.uv]
38
+ # Rebuild the editable install when a commit or tag moves, so `--version` follows the tag.
39
+ cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
40
+
41
+ # Our packages come only from the Gitea registry: a version range in
42
+ # `dependencies` ("rb-serp>=0.3") and a source line per package, never a git
43
+ # tag. explicit = true: only the packages named in [tool.uv.sources] are looked
44
+ # up there, and they are never taken from PyPI (an unrelated package of the
45
+ # same name may live there).
46
+ # # rb-serp = { index = "gitea" }
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["src/rb_keys"]
49
+
50
+ [tool.hatch.build.targets.wheel.force-include]
51
+ # The installed CLI reads [[tool.rb.external]] from here (core/deps.py).
52
+ "pyproject.toml" = "rb_keys/_pyproject.toml"
53
+
54
+ [dependency-groups]
55
+ # Mutation testing, run now and then and before big releases — not in the gate:
56
+ # `uv run --group mutation mutmut run`, then `mutmut results` / `mutmut browse`.
57
+ # Needs fork(): macOS/Linux (WSL on Windows). Settings: [tool.mutmut] below.
58
+ mutation = ["mutmut>=3.3"]
59
+ dev = [
60
+ "jsonschema>=4.23",
61
+ "pytest>=8.0",
62
+ "pyyaml>=6.0", # .copier-answers.yml, the CI workflow, tests/contracts/*.yaml
63
+ "pytest-cov>=5.0",
64
+ "ruff>=0.6",
65
+ "syrupy>=4.8",
66
+ "ty>=0.0.80",
67
+ ]
68
+
69
+ # External (non-Python) dependencies — every CLI this tool runs (require_cli,
70
+ # shutil.which, subprocess with a literal program, npx). The gate checks this
71
+ # list against the code both ways; doctor and require_cli read it at runtime;
72
+ # the tools catalog reads it (the Standard, Technology).
73
+ # [[tool.rb.external]]
74
+ # name = "ffmpeg"
75
+ # required = true # false: the tool works without it (doctor stays healthy)
76
+ # min_version = "6.0" # optional
77
+ # check = "ffmpeg -version" # prints the version; default "<name> --version"
78
+ # why = "transcodes the downloaded videos"
79
+ # detect = false # run via an injected runner / absolute path the gate can't see
80
+ # dist = "rb-serp" # for one of our CLIs: its distribution (default rb-<name>)
81
+ # url = "https://github.com/bolandeu/serp" # its repo: DEPENDENCY_TOO_OLD then prints a pinned install
82
+
83
+ # Where sysadmin's tool-updater installs this tool after its first tag. The
84
+ # installation is sysadmin's; this section only says where. homeserver: users
85
+ # to install for (empty = build and publish only); mac: install on the Mac.
86
+ # extras (optional): the extras to install with, e.g. extras = ["browser"].
87
+ [tool.rb.install]
88
+ homeserver = ["rbtools"]
89
+ mac = true
90
+
91
+ [tool.cli-generator]
92
+ # Where scripts/check_command_docstrings.py (called by the project's checks)
93
+ # looks for commands: a glob or a list of globs, relative to the repo root.
94
+ commands = ["src/rb_keys/commands/*.py"]
95
+ # gate check (the gate): extras to install before ruff/ty/pytest.
96
+ # gate_extras = ["browser"]
97
+
98
+ [tool.pytest.ini_options]
99
+ # Only tests/: mutmut leaves a copy of the tree in mutants/.
100
+ testpaths = ["tests"]
101
+ addopts = "--cov --cov-report=term-missing:skip-covered"
102
+ # tests/test_help.py keeps help snapshots at tests/snapshots/help/<command>.txt
103
+ # (the Standard, Commands), not in syrupy's own `__snapshots__/<test file>/` layout, so
104
+ # syrupy warns it "can not relate" each file to its test. It can — by name.
105
+ filterwarnings = ["ignore:(?s).*Can not relate snapshot:UserWarning"]
106
+
107
+ [tool.mutmut]
108
+ source_paths = ["src/rb_keys"]
109
+ also_copy = ["scripts/", "pyproject.toml"] # tests read them (test_scripts.py, the distribution checks)
110
+ pytest_add_cli_args = ["--no-cov"] # fail_under would kill every mutant
111
+ # only_mutate = ["*/core/normalize.py"] # one module at a time on a big tool
112
+
113
+ [tool.coverage.run]
114
+ source = ["src"]
115
+ # sysmon (default on 3.14) keeps a record per recompiled code object; Typer recompiles annotations on every invoke, so memory grows.
116
+ core = "ctrace"
117
+
118
+ [tool.coverage.report]
119
+ # The template ships at ~94%; keep the bar where it is instead of letting
120
+ # new commands land untested. Raise it, never lower it.
121
+ fail_under = 90
122
+ show_missing = true
123
+
124
+ [tool.ty.terminal]
125
+ # Only errors fail the gate; recent ty (>= 0.0.84) otherwise exits 1 on warnings too.
126
+ # Legacy code that can't be fixed yet: downgrade specific rules instead of
127
+ # ignoring them, e.g. [tool.ty.rules] possibly-unbound-attribute = "warn".
128
+ error-on-warning = false
129
+
130
+ [tool.ruff]
131
+ line-length = 120
132
+
133
+ [tool.ruff.lint]
134
+ select = ["E4", "E7", "E9", "F", "I", "UP", "B", "SIM", "RUF", "S", "T20", "TID251"]
135
+
136
+ [tool.ruff.lint.per-file-ignores]
137
+ "tests/*" = ["S101", "T201", "TID251"] # assert is the point of a test; print in code strings; httpx for mocks
138
+ "scripts/*" = ["S603", "S607", "T201"] # subprocess with fixed argv lists (git, uv), no shell; scripts print to the console
139
+ "src/*/providers/*" = ["TID251"] # external APIs live here
140
+
141
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
142
+ "httpx".msg = "Call external APIs through providers/ (subclass providers.HttpProvider)."
143
+
144
+ [tool.ruff.lint.flake8-bugbear]
145
+ # Typer's `param: T = typer.Option(...)` style is a call in a default on purpose.
146
+ extend-immutable-calls = ["typer.Option", "typer.Argument"]
rb_keys/cli.py ADDED
@@ -0,0 +1,71 @@
1
+ """The root Typer app: global options, the command groups and the optional commands a generated package has, wired
2
+ together, and the console-script entry point.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import typer
8
+
9
+ from . import output
10
+ from .commands import auth, doctor, keys
11
+ from .core.version import DEV_VERSION, cli_name, installed_version, optional_module, package_summary
12
+
13
+ _PACKAGE_NAME = __name__.split(".")[0]
14
+ # Optional parts (copier questions, dropped by _exclude): each one ships a module that registers its
15
+ # commands and global options. Probed at runtime, so this file needs no template logic.
16
+ PARTS = ("project", "skill", "describe", "db")
17
+
18
+ # A bare `<cli>` is the discovery entry point for humans and agents alike:
19
+ # name + version + description, then every command with the first line of
20
+ # its docstring. No `no_args_is_help` (that exits 2) — main_options() below
21
+ # prints this and exits 0. Shell completion stays enabled.
22
+ app = typer.Typer(
23
+ cls=output.RootGroup, # a usage error under --json is the error envelope
24
+ help=f"{cli_name()} {installed_version() or DEV_VERSION} — {package_summary() or 'project-aware automation CLI'}",
25
+ )
26
+
27
+ app.add_typer(auth.app, name="auth") # `auth status` in every CLI; login/logout only with credentials
28
+ app.command(name="doctor")(doctor.doctor)
29
+ app.command(name="query")(keys.query)
30
+ app.command(name="domain")(keys.domain)
31
+ app.command(name="url")(keys.url)
32
+ for part in PARTS:
33
+ if module := optional_module(f"{_PACKAGE_NAME}.commands.{part}"):
34
+ module.register(app)
35
+
36
+
37
+ def _version_callback(value: bool) -> None:
38
+ if not value:
39
+ return
40
+ typer.echo(installed_version() or DEV_VERSION)
41
+ raise typer.Exit()
42
+
43
+
44
+ @app.callback(invoke_without_command=True)
45
+ def main_options(
46
+ ctx: typer.Context,
47
+ json_output: bool = typer.Option(False, "--json", help="Emit machine-readable JSON output."),
48
+ quiet: bool = typer.Option(False, "--quiet", help="Suppress non-essential output."),
49
+ verbose: bool = typer.Option(False, "--verbose", help="Emit extra diagnostic output."),
50
+ non_interactive: bool = typer.Option(False, "--non-interactive", help="Never prompt; fail instead."),
51
+ dry_run: bool = typer.Option(False, "--dry-run", help="Show what would happen without making changes."),
52
+ version: bool = typer.Option(
53
+ False, "--version", callback=_version_callback, is_eager=True, help="Show the version and exit."
54
+ ),
55
+ ) -> None:
56
+ ctx.ensure_object(dict) # a part's global option (--project) may have put its value here already
57
+ ctx.obj["json"] = json_output
58
+ ctx.obj["quiet"] = quiet
59
+ ctx.obj["verbose"] = verbose
60
+ ctx.obj["non_interactive"] = non_interactive
61
+ ctx.obj["dry_run"] = dry_run
62
+ output.configure_logging(verbose)
63
+ output.help_if_no_command(ctx)
64
+
65
+
66
+ def main() -> None:
67
+ app()
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
@@ -0,0 +1 @@
1
+ """The commands of the CLI, one module per command or command group."""
@@ -0,0 +1,66 @@
1
+ """The `auth` command group: `status` reports the health of the credentials of every provider, or an empty report when
2
+ the package has none.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import importlib
8
+ from datetime import UTC, datetime
9
+
10
+ import typer
11
+
12
+ from .. import output
13
+ from ..core.errors import InvalidArguments
14
+ from ..core.version import DEV_VERSION, cli_name, installed_version, module_exists, optional_module
15
+
16
+ # `auth status` exists in every CLI (the Standard, Health); a CLI
17
+ # generated without credentials (no credentials/ package, no commands/login.py)
18
+ # reports an empty `credentials` list and exits 0. Detected at runtime so this
19
+ # file needs no template logic — same approach as doctor.py.
20
+ _PACKAGE_NAME = __name__.split(".")[0]
21
+ _HAS_CREDENTIALS = module_exists(f"{_PACKAGE_NAME}.credentials.manager")
22
+
23
+ app = output.group("Credentials: report their health (and store them, if this CLI has any).")
24
+
25
+
26
+ @app.command("status")
27
+ @output.guard
28
+ def auth_status(
29
+ ctx: typer.Context,
30
+ check: bool = typer.Option(
31
+ False, "--check", help="Also make one cheap read-only call per provider (10 s timeout) to prove each works."
32
+ ),
33
+ provider: str | None = typer.Option(
34
+ None, "--provider", help="Report only this provider, or one target as <kind>:<target> (default: all)."
35
+ ),
36
+ json_output: bool = output.JsonOption,
37
+ quiet: bool = output.QuietOption,
38
+ ) -> None:
39
+ """Report every provider's credential: where it comes from and whether it works. Never prints values.
40
+
41
+ Without --check only presence is reported (status `unchecked` or `missing`).
42
+ Exits 0 when every required provider is ok/unchecked (an optional one may be
43
+ missing), 3 when any required provider has a problem or any credential is
44
+ invalid/expired, 2 on a usage error. A per-target provider (one credential per
45
+ site/host/account) gets one entry per stored target, named `<kind>:<target>`. The --json shape is a cross-tool contract:
46
+ `tool`, `version`, `checked_at`, `credentials[]` with `provider`, `required`,
47
+ `fields`, `source`, `source_ref`, `status`, `expires_at`, `quota`, `message`.
48
+
49
+ Example: {cli} auth status --check --json
50
+ """
51
+ tool, version = cli_name(), installed_version() or DEV_VERSION
52
+ if not _HAS_CREDENTIALS:
53
+ if provider is not None:
54
+ raise InvalidArguments(f"Unknown provider '{provider}' ({tool} stores no credentials).")
55
+ checked_at = datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
56
+ payload = {"tool": tool, "version": version, "checked_at": checked_at, "credentials": []}
57
+ output.emit_report(ctx, payload, lambda _: output.human.echo(f"{tool} stores no credentials."), None)
58
+ return
59
+ health = importlib.import_module(f"{_PACKAGE_NAME}.credentials.health")
60
+ payload, problem = health.status(tool, version, check=check, only=provider)
61
+ output.emit_report(ctx, payload, health.render, problem)
62
+
63
+
64
+ if _login := optional_module(f"{_PACKAGE_NAME}.commands.login"):
65
+ app.command("login")(_login.login)
66
+ app.command("logout")(_login.logout)
@@ -0,0 +1,87 @@
1
+ """The `config` command group: show and change the project's config file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import typer
8
+
9
+ from .. import output
10
+ from ..core import services
11
+ from ..core.errors import InvalidArguments
12
+ from ..core.models import ProjectConfig
13
+
14
+ app = output.group("Manage project configuration.")
15
+
16
+
17
+ @app.command("list")
18
+ @output.guard
19
+ def list_config(
20
+ ctx: typer.Context,
21
+ json_output: bool = output.JsonOption,
22
+ quiet: bool = output.QuietOption,
23
+ ) -> None:
24
+ """List all configuration values.
25
+
26
+ Example: {cli} config list --json
27
+ """
28
+ start = Path(ctx.obj.get("project") or Path.cwd())
29
+ root = services.require_project_root(start)
30
+ config = services.load_config(root)
31
+ data = config.model_dump()
32
+ output.emit_success(ctx, data, render_human=lambda d: output.human.key_values("Config", d))
33
+
34
+
35
+ @app.command("get")
36
+ @output.guard
37
+ def get_config(
38
+ ctx: typer.Context,
39
+ key: str = typer.Argument(..., help="Dotted config key, e.g. cli.min_version (see `config list`)."),
40
+ json_output: bool = output.JsonOption,
41
+ quiet: bool = output.QuietOption,
42
+ ) -> None:
43
+ """Get a single configuration value.
44
+
45
+ Example: {cli} config get cli.min_version
46
+ """
47
+ start = Path(ctx.obj.get("project") or Path.cwd())
48
+ root = services.require_project_root(start)
49
+ value: object = services.load_config(root).model_dump()
50
+ for part in key.split("."):
51
+ if not isinstance(value, dict) or part not in value:
52
+ raise InvalidArguments(f"Unknown config key '{key}'.")
53
+ value = value[part]
54
+ output.emit_success(
55
+ ctx, {"key": key, "value": value}, render_human=lambda d: output.human.echo(f"{d['key']} = {d['value']}")
56
+ )
57
+
58
+
59
+ @app.command("set")
60
+ @output.guard
61
+ def set_config(
62
+ ctx: typer.Context,
63
+ key: str = typer.Argument(..., help="Dotted config key, e.g. cli.min_version (see `config list`)."),
64
+ value: str = typer.Argument(..., help="New value (stored as a string)."),
65
+ json_output: bool = output.JsonOption,
66
+ quiet: bool = output.QuietOption,
67
+ ) -> None:
68
+ """Set a single, non-secret configuration value.
69
+
70
+ Example: {cli} config set cli.min_version 0.2.0
71
+ """
72
+ start = Path(ctx.obj.get("project") or Path.cwd())
73
+ root = services.require_project_root(start)
74
+ data = services.load_config(root).model_dump()
75
+ parts = key.split(".")
76
+ target = data
77
+ for part in parts[:-1]:
78
+ if not isinstance(target, dict) or part not in target:
79
+ raise InvalidArguments(f"Unknown config key '{key}'.")
80
+ target = target[part]
81
+ if not isinstance(target, dict) or parts[-1] not in target:
82
+ raise InvalidArguments(f"Unknown config key '{key}'.")
83
+ target[parts[-1]] = value
84
+ services.save_config(root, ProjectConfig.model_validate(data))
85
+ output.emit_success(
86
+ ctx, {"key": key, "value": value}, render_human=lambda d: output.human.echo(f"Set {d['key']} = {d['value']}")
87
+ )
@@ -0,0 +1,34 @@
1
+ """The `describe` command: the machine-readable description (OpenCLI document) of this CLI for agents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ import typer
8
+
9
+ from .. import output
10
+ from ..core import opencli
11
+
12
+
13
+ @output.guard
14
+ def describe(
15
+ ctx: typer.Context,
16
+ json_output: bool = output.JsonOption,
17
+ quiet: bool = output.QuietOption,
18
+ verbose: bool = output.VerboseOption,
19
+ ) -> None:
20
+ """Print this CLI's machine-readable contract: an OpenCLI document (opencli.org).
21
+
22
+ Commands, options, arguments, exit codes, plus `x-rb-*` metadata: env vars,
23
+ tables, v1 views, data files, external programs. With --json it is the bare
24
+ document on one line (no {"ok": ...} envelope); without, the same indented.
25
+
26
+ Example: {cli} describe --json
27
+ """
28
+ document = opencli.document(ctx.find_root().command)
29
+ typer.echo(json.dumps(document, ensure_ascii=False, indent=None if ctx.obj.get("json") else 2))
30
+
31
+
32
+ def register(root: typer.Typer) -> None:
33
+ """Add `describe` to the CLI's root (the describe part, copier's include_describe)."""
34
+ root.command(name="describe")(describe)
@@ -0,0 +1,43 @@
1
+ """The `doctor` command: checks of this CLI's own setup, one line per check."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from .. import output
8
+ from ..core import deps
9
+ from ..core.version import DEV_VERSION, installed_version, optional_module
10
+
11
+ _PACKAGE_NAME = __name__.split(".")[0]
12
+
13
+
14
+ @output.guard
15
+ def doctor(
16
+ ctx: typer.Context,
17
+ json_output: bool = output.JsonOption,
18
+ quiet: bool = output.QuietOption,
19
+ verbose: bool = output.VerboseOption,
20
+ ) -> None:
21
+ """Run diagnostic checks and report readiness.
22
+
23
+ Always exits 0 — the report itself is the result; `healthy` says
24
+ whether every check passed.
25
+
26
+ Example: {cli} doctor --json
27
+ """
28
+ checks: list[dict] = [{"name": "python", "ok": True}]
29
+ checks.append({"name": "cli_version", "ok": True, "detail": installed_version() or DEV_VERSION})
30
+
31
+ if project := optional_module(f"{_PACKAGE_NAME}.commands.project"): # include_project=false drops it
32
+ checks.extend(project.doctor_checks(ctx))
33
+
34
+ if credentials := optional_module(f"{_PACKAGE_NAME}.credentials.health"): # include_auth=false drops it
35
+ checks.extend(credentials.doctor_checks())
36
+ checks.extend(deps.doctor_checks()) # [[tool.rb.external]] in pyproject.toml
37
+ if db := optional_module(f"{_PACKAGE_NAME}.core.db"): # include_db=false drops it at generation time
38
+ checks.extend(db.doctor_checks())
39
+
40
+ all_ok = all(check["ok"] for check in checks)
41
+ output.emit_success(
42
+ ctx, {"healthy": all_ok, "checks": checks}, render_human=lambda data: output.human.render_doctor(data["checks"])
43
+ )
@@ -0,0 +1,48 @@
1
+ """The `init` command: create the project folder with its config file in the target directory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import typer
8
+
9
+ from .. import output
10
+ from ..core import services
11
+
12
+
13
+ @output.guard
14
+ def init(
15
+ ctx: typer.Context,
16
+ name: str | None = typer.Option(None, "--name", help="Project name (defaults to directory name)."),
17
+ force: bool = typer.Option(False, "--force", help="Overwrite an already-initialized project's config."),
18
+ json_output: bool = output.JsonOption,
19
+ quiet: bool = output.QuietOption,
20
+ verbose: bool = output.VerboseOption,
21
+ ) -> None:
22
+ """Initialize a project: creates .{package}/config.toml in the target directory.
23
+
24
+ Example: {cli} init --name demo
25
+ """
26
+ target = Path(ctx.obj.get("project") or Path.cwd()).resolve()
27
+
28
+ if not force and services.find_project_root(target) == target:
29
+ output.vecho(ctx, f"Found existing config at {services.config_path(target)}")
30
+ config = services.load_config(target)
31
+ output.emit_success(
32
+ ctx,
33
+ {"project": config.name, "path": str(target), "already_initialized": True},
34
+ render_human=lambda data: output.human.echo(
35
+ f"Already initialized in {data['path']} (use --force to reset)."
36
+ ),
37
+ )
38
+ return
39
+
40
+ project_name = name or target.name
41
+ config = services.init_project(target, project_name)
42
+ output.emit_success(
43
+ ctx,
44
+ {"project": config.name, "path": str(target), "already_initialized": False},
45
+ render_human=lambda data: output.human.key_values(
46
+ f"Initialized project in {data['path']}", {"name": data["project"]}
47
+ ),
48
+ )
@@ -0,0 +1,124 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from collections.abc import Callable
5
+ from pathlib import Path
6
+
7
+ import typer
8
+
9
+ from .. import output
10
+ from ..core.errors import InvalidArguments
11
+ from ..core.normalize import KEYS_VERSION, norm_domain, norm_query, norm_url
12
+
13
+
14
+ def _read_lines(source: str) -> list[str]:
15
+ try:
16
+ text = sys.stdin.read() if source == "-" else Path(source).read_text(encoding="utf-8")
17
+ except (OSError, UnicodeDecodeError) as exc:
18
+ raise InvalidArguments(f"--input: cannot read {source!r}: {getattr(exc, 'strerror', None) or exc}.") from None
19
+ return [line for line in text.splitlines() if line]
20
+
21
+
22
+ def _key(value: str, norm: Callable[[str], str]) -> str:
23
+ try:
24
+ return norm(value)
25
+ except ValueError as exc:
26
+ raise InvalidArguments(str(exc)) from None
27
+
28
+
29
+ def _emit(
30
+ ctx: typer.Context, fn: str, values: list[str] | None, input_path: str | None, norm: Callable[[str], str]
31
+ ) -> None:
32
+ given = [*(values or []), *(_read_lines(input_path) if input_path else [])]
33
+ if not given:
34
+ raise InvalidArguments("No values given: pass them as arguments or via --input <file|->.")
35
+ if input_path is None and len(given) == 1:
36
+ key = _key(given[0], norm)
37
+ output.emit_success(
38
+ ctx,
39
+ {"fn": fn, "input": given[0], "key": key, "keys_version": KEYS_VERSION},
40
+ render_human=lambda d: typer.echo(d["key"]),
41
+ )
42
+ return
43
+ results = [{"input": v, "key": _key(v, norm)} for v in given]
44
+ output.emit_success(
45
+ ctx,
46
+ {"fn": fn, "count": len(results), "keys_version": KEYS_VERSION, "results": results},
47
+ render_human=lambda d: typer.echo("\n".join(r["key"] for r in d["results"])),
48
+ )
49
+
50
+
51
+ @output.guard
52
+ def query(
53
+ ctx: typer.Context,
54
+ values: list[str] | None = typer.Argument(
55
+ None, help="The search query, as typed or with Wordstat operators. One or more."
56
+ ),
57
+ input_path: str | None = typer.Option(
58
+ None, "--input", help="File with values, one per line; '-' reads stdin. Added after the arguments."
59
+ ),
60
+ json_output: bool = output.JsonOption,
61
+ ) -> None:
62
+ """Print the query key: NFKC, lower case, yo as ye, no Wordstat operators, minus-words or punctuation.
63
+
64
+ The key alone on stdout (an empty line when nothing is left); --json adds
65
+ the input and keys_version. Rules: vectors/keys-v1.yaml in the repository.
66
+
67
+ Batch: several values and/or --input FILE (one per line, '-' = stdin,
68
+ empty lines skipped) in one call. Human output: one key per line; --json:
69
+ {ok, fn, count, keys_version, results: [{input, key}]} in input order,
70
+ duplicates kept. One value without --input: the single envelope above.
71
+
72
+ Example: {cli} query '!купить диван -бесплатно' --json
73
+ """
74
+ _emit(ctx, "query", values, input_path, norm_query)
75
+
76
+
77
+ @output.guard
78
+ def domain(
79
+ ctx: typer.Context,
80
+ values: list[str] | None = typer.Argument(None, help="A domain or any URL on it. One or more."),
81
+ input_path: str | None = typer.Option(
82
+ None, "--input", help="File with values, one per line; '-' reads stdin. Added after the arguments."
83
+ ),
84
+ json_output: bool = output.JsonOption,
85
+ ) -> None:
86
+ """Print the domain key: lower case, Unicode not punycode, no www., no :80/:443, no trailing dot.
87
+
88
+ The key alone on stdout; --json adds the input and keys_version. No host
89
+ in VALUE: INVALID_ARGUMENTS (exit 2).
90
+
91
+ Batch: several values and/or --input FILE (one per line, '-' = stdin,
92
+ empty lines skipped) in one call. Human output: one key per line; --json:
93
+ {ok, fn, count, keys_version, results: [{input, key}]} in input order,
94
+ duplicates kept. One value without --input: the single envelope above.
95
+
96
+ Example: {cli} domain https://www.example.com/a --json
97
+ """
98
+ _emit(ctx, "domain", values, input_path, norm_domain)
99
+
100
+
101
+ @output.guard
102
+ def url(
103
+ ctx: typer.Context,
104
+ values: list[str] | None = typer.Argument(None, help="A page URL, with or without the scheme. One or more."),
105
+ input_path: str | None = typer.Option(
106
+ None, "--input", help="File with values, one per line; '-' reads stdin. Added after the arguments."
107
+ ),
108
+ json_output: bool = output.JsonOption,
109
+ ) -> None:
110
+ """Print the URL key: the domain key + path + sorted query, without scheme, fragment or tracking parameters.
111
+
112
+ Path decoded to Unicode (spaces and reserved characters stay escaped),
113
+ dot-segments resolved, // kept, no trailing slash; utm_*, yclid, gclid,
114
+ fbclid, ysclid, _openstat removed. The key alone on stdout; --json adds
115
+ the input and keys_version. Not a URL: INVALID_ARGUMENTS (exit 2).
116
+
117
+ Batch: several values and/or --input FILE (one per line, '-' = stdin,
118
+ empty lines skipped) in one call. Human output: one key per line; --json:
119
+ {ok, fn, count, keys_version, results: [{input, key}]} in input order,
120
+ duplicates kept. One value without --input: the single envelope above.
121
+
122
+ Example: {cli} url 'https://www.example.com/Catalog/?utm_source=x&p=2' --json
123
+ """
124
+ _emit(ctx, "url", values, input_path, norm_url)