pricegraph-cli 0.1.0__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.
- pricegraph_cli/__init__.py +3 -0
- pricegraph_cli/client.py +162 -0
- pricegraph_cli/formatting.py +72 -0
- pricegraph_cli/handoff.py +161 -0
- pricegraph_cli/main.py +486 -0
- pricegraph_cli-0.1.0.dist-info/METADATA +60 -0
- pricegraph_cli-0.1.0.dist-info/RECORD +10 -0
- pricegraph_cli-0.1.0.dist-info/WHEEL +5 -0
- pricegraph_cli-0.1.0.dist-info/entry_points.txt +2 -0
- pricegraph_cli-0.1.0.dist-info/top_level.txt +1 -0
pricegraph_cli/client.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Bounded, fail-closed HTTP client for PriceGraph UK public REST APIs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
from urllib.parse import urlparse
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
|
|
15
|
+
DEFAULT_API_BASE = "https://www.pricegraph.co.uk"
|
|
16
|
+
DEFAULT_TIMEOUT_SECONDS = 15.0
|
|
17
|
+
MAX_RESPONSE_BYTES = 2 * 1024 * 1024 # 2 MiB hard response cap
|
|
18
|
+
MAX_RETRY_AFTER_SECONDS = 10.0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CliExitCode:
|
|
22
|
+
OK = 0
|
|
23
|
+
INVALID_INPUT = 2
|
|
24
|
+
NOT_FOUND = 3
|
|
25
|
+
RESTRICTED = 4
|
|
26
|
+
UNAVAILABLE = 5
|
|
27
|
+
TRANSPORT_ERROR = 6
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class ApiError(Exception):
|
|
32
|
+
exit_code: int
|
|
33
|
+
message: str
|
|
34
|
+
status_code: Optional[int] = None
|
|
35
|
+
error_code: Optional[str] = None
|
|
36
|
+
retryable: bool = False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def validate_api_base(raw_base: Optional[str] = None) -> str:
|
|
40
|
+
"""Ensure API base URL uses HTTPS (except localhost/127.0.0.1 for local dev)."""
|
|
41
|
+
base = (raw_base or os.environ.get("PRICEGRAPH_API_BASE") or DEFAULT_API_BASE).strip().rstrip("/")
|
|
42
|
+
parsed = urlparse(base)
|
|
43
|
+
host = (parsed.hostname or "").lower()
|
|
44
|
+
if parsed.scheme == "https" and host:
|
|
45
|
+
return base
|
|
46
|
+
if parsed.scheme == "http" and host in {"localhost", "127.0.0.1"}:
|
|
47
|
+
return base
|
|
48
|
+
raise ApiError(
|
|
49
|
+
exit_code=CliExitCode.INVALID_INPUT,
|
|
50
|
+
message=f"Unsafe PRICEGRAPH_API_BASE '{base}': HTTPS is required (http allowed only for localhost/127.0.0.1).",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class PriceGraphClient:
|
|
55
|
+
"""Thin, stateless REST adapter to PriceGraph's public /api/agent/v1/* endpoints."""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
base_url: Optional[str] = None,
|
|
60
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
61
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
self.base_url = validate_api_base(base_url)
|
|
64
|
+
self.timeout = timeout
|
|
65
|
+
telemetry_disabled = (
|
|
66
|
+
os.environ.get("PRICEGRAPH_NO_TELEMETRY", "").strip() == "1"
|
|
67
|
+
or os.environ.get("PRICEGRAPH_TELEMETRY", "").strip() == "0"
|
|
68
|
+
)
|
|
69
|
+
headers: Dict[str, str] = {"Accept": "application/json"}
|
|
70
|
+
if telemetry_disabled:
|
|
71
|
+
headers["User-Agent"] = "python-httpx"
|
|
72
|
+
else:
|
|
73
|
+
headers["User-Agent"] = f"pricegraph-cli/{__version__}"
|
|
74
|
+
headers["X-PriceGraph-Client"] = f"cli/{__version__}"
|
|
75
|
+
self._client = httpx.Client(
|
|
76
|
+
base_url=self.base_url,
|
|
77
|
+
timeout=httpx.Timeout(timeout),
|
|
78
|
+
verify=True,
|
|
79
|
+
follow_redirects=False,
|
|
80
|
+
transport=transport,
|
|
81
|
+
headers=headers,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def close(self) -> None:
|
|
85
|
+
self._client.close()
|
|
86
|
+
|
|
87
|
+
def __enter__(self) -> "PriceGraphClient":
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
91
|
+
self.close()
|
|
92
|
+
|
|
93
|
+
def request_json(
|
|
94
|
+
self,
|
|
95
|
+
method: str,
|
|
96
|
+
path: str,
|
|
97
|
+
*,
|
|
98
|
+
params: Optional[Dict[str, Any]] = None,
|
|
99
|
+
json_body: Optional[Dict[str, Any]] = None,
|
|
100
|
+
max_retries: int = 1,
|
|
101
|
+
) -> Dict[str, Any]:
|
|
102
|
+
"""Execute a bounded JSON request with Retry-After support and schema validation."""
|
|
103
|
+
attempt = 0
|
|
104
|
+
while True:
|
|
105
|
+
try:
|
|
106
|
+
resp = self._client.request(method, path, params=params, json=json_body)
|
|
107
|
+
except (httpx.TimeoutException, httpx.TransportError) as exc:
|
|
108
|
+
raise ApiError(
|
|
109
|
+
exit_code=CliExitCode.TRANSPORT_ERROR,
|
|
110
|
+
message=f"Network error contacting {self.base_url}{path}: {exc}",
|
|
111
|
+
retryable=True,
|
|
112
|
+
) from exc
|
|
113
|
+
|
|
114
|
+
if len(resp.content) > MAX_RESPONSE_BYTES:
|
|
115
|
+
raise ApiError(
|
|
116
|
+
exit_code=CliExitCode.TRANSPORT_ERROR,
|
|
117
|
+
message="Response exceeded 2 MiB safety limit.",
|
|
118
|
+
status_code=resp.status_code,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
if resp.status_code in (429, 503) and attempt < max_retries:
|
|
122
|
+
raw_retry = resp.headers.get("Retry-After", "")
|
|
123
|
+
try:
|
|
124
|
+
delay = float(raw_retry)
|
|
125
|
+
except ValueError:
|
|
126
|
+
delay = 1.0
|
|
127
|
+
if 0 < delay <= MAX_RETRY_AFTER_SECONDS:
|
|
128
|
+
attempt += 1
|
|
129
|
+
time.sleep(delay)
|
|
130
|
+
continue
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
data = resp.json()
|
|
134
|
+
except ValueError as exc:
|
|
135
|
+
raise ApiError(
|
|
136
|
+
exit_code=CliExitCode.TRANSPORT_ERROR,
|
|
137
|
+
message=f"Malformed JSON response (HTTP {resp.status_code}) from {path}.",
|
|
138
|
+
status_code=resp.status_code,
|
|
139
|
+
) from exc
|
|
140
|
+
|
|
141
|
+
if not isinstance(data, dict):
|
|
142
|
+
raise ApiError(
|
|
143
|
+
exit_code=CliExitCode.TRANSPORT_ERROR,
|
|
144
|
+
message=f"Unexpected non-object JSON payload (HTTP {resp.status_code}) from {path}.",
|
|
145
|
+
status_code=resp.status_code,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
if resp.status_code == 200:
|
|
149
|
+
return data
|
|
150
|
+
|
|
151
|
+
error_msg = str(data.get("error") or data.get("reason") or f"HTTP {resp.status_code}")
|
|
152
|
+
error_code = str(data.get("error_code") or "")
|
|
153
|
+
|
|
154
|
+
if resp.status_code == 400:
|
|
155
|
+
raise ApiError(CliExitCode.INVALID_INPUT, error_msg, resp.status_code, error_code)
|
|
156
|
+
if resp.status_code == 404:
|
|
157
|
+
raise ApiError(CliExitCode.NOT_FOUND, error_msg, resp.status_code, error_code)
|
|
158
|
+
if resp.status_code in (401, 402, 403):
|
|
159
|
+
raise ApiError(CliExitCode.RESTRICTED, error_msg, resp.status_code, error_code)
|
|
160
|
+
if resp.status_code in (429, 503):
|
|
161
|
+
raise ApiError(CliExitCode.UNAVAILABLE, error_msg, resp.status_code, error_code, retryable=True)
|
|
162
|
+
raise ApiError(CliExitCode.TRANSPORT_ERROR, error_msg, resp.status_code, error_code)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Output sanitization, formatting, and CSV formula-safety helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any, Iterable, Sequence
|
|
10
|
+
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
|
|
14
|
+
_CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
|
15
|
+
_FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def sanitize_terminal_text(value: Any, max_len: int = 200) -> str:
|
|
19
|
+
"""Strip ASCII/C1 control characters and ANSI escapes before terminal output."""
|
|
20
|
+
if value is None:
|
|
21
|
+
return ""
|
|
22
|
+
text = str(value)
|
|
23
|
+
text = _CONTROL_CHAR_RE.sub(" ", text).strip()
|
|
24
|
+
if len(text) > max_len:
|
|
25
|
+
return text[: max_len - 1] + "…"
|
|
26
|
+
return text
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def sanitize_csv_cell(value: Any) -> str:
|
|
30
|
+
"""Neutralize spreadsheet formula-injection prefixes in CSV cells."""
|
|
31
|
+
if value is None:
|
|
32
|
+
return ""
|
|
33
|
+
text = _CONTROL_CHAR_RE.sub(" ", str(value))
|
|
34
|
+
if text.startswith(_FORMULA_PREFIXES):
|
|
35
|
+
return f"'{text}"
|
|
36
|
+
return text
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def format_price_gbp(value: Any) -> str:
|
|
40
|
+
"""Format a numeric GBP price cleanly."""
|
|
41
|
+
if value is None or value == "":
|
|
42
|
+
return "—"
|
|
43
|
+
try:
|
|
44
|
+
return f"£{float(value):.2f}"
|
|
45
|
+
except (TypeError, ValueError):
|
|
46
|
+
return sanitize_terminal_text(value, 32)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def emit_json(payload: Any) -> None:
|
|
50
|
+
"""Write deterministic, banner-free JSON to stdout."""
|
|
51
|
+
print(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def emit_csv(headers: Sequence[str], rows: Iterable[Sequence[Any]]) -> None:
|
|
55
|
+
"""Write formula-safe CSV to stdout."""
|
|
56
|
+
buf = io.StringIO()
|
|
57
|
+
writer = csv.writer(buf, lineterminator="\n")
|
|
58
|
+
writer.writerow([sanitize_csv_cell(h) for h in headers])
|
|
59
|
+
for row in rows:
|
|
60
|
+
writer.writerow([sanitize_csv_cell(cell) for cell in row])
|
|
61
|
+
print(buf.getvalue(), end="")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def render_table(title: str, columns: Sequence[str], rows: Sequence[Sequence[Any]]) -> None:
|
|
65
|
+
"""Render a clean Rich table to stdout."""
|
|
66
|
+
console = Console(stderr=False)
|
|
67
|
+
table = Table(title=sanitize_terminal_text(title, 120), show_lines=False)
|
|
68
|
+
for col in columns:
|
|
69
|
+
table.add_column(sanitize_terminal_text(col, 64))
|
|
70
|
+
for row in rows:
|
|
71
|
+
table.add_row(*[sanitize_terminal_text(cell, 160) for cell in row])
|
|
72
|
+
console.print(table)
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Safe first-party website handoff, URL validation, and short-TTL result references."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import time
|
|
9
|
+
from typing import Any, Dict, List, Optional
|
|
10
|
+
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
|
|
11
|
+
import webbrowser
|
|
12
|
+
|
|
13
|
+
from .client import ApiError, CliExitCode
|
|
14
|
+
|
|
15
|
+
RECENT_REFS_TTL_SECONDS = 900 # 15 minutes
|
|
16
|
+
MAX_RECENT_REFS = 25
|
|
17
|
+
APPROVED_HOSTS = {"www.pricegraph.co.uk", "pricegraph.co.uk"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_refs_path() -> Path:
|
|
21
|
+
override = os.environ.get("PRICEGRAPH_REFS_PATH", "").strip()
|
|
22
|
+
if override:
|
|
23
|
+
return Path(override)
|
|
24
|
+
return Path.home() / ".cache" / "pricegraph-cli" / "recent_refs.json"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def validate_first_party_product_url(raw_url: str, base_url: str) -> str:
|
|
28
|
+
"""Validate that a URL is a genuine first-party PriceGraph /product/* destination."""
|
|
29
|
+
if not isinstance(raw_url, str) or not raw_url.strip():
|
|
30
|
+
raise ApiError(CliExitCode.INVALID_INPUT, "Product URL is empty.")
|
|
31
|
+
|
|
32
|
+
cleaned = raw_url.strip()
|
|
33
|
+
if any(ord(ch) < 32 or ord(ch) == 127 for ch in cleaned):
|
|
34
|
+
raise ApiError(CliExitCode.INVALID_INPUT, "Product URL contains invalid control characters.")
|
|
35
|
+
|
|
36
|
+
parsed = urlparse(cleaned)
|
|
37
|
+
base_parsed = urlparse(base_url)
|
|
38
|
+
base_host = (base_parsed.hostname or "").lower()
|
|
39
|
+
host = (parsed.hostname or "").lower()
|
|
40
|
+
|
|
41
|
+
if parsed.username or parsed.password:
|
|
42
|
+
raise ApiError(CliExitCode.INVALID_INPUT, "Product URL must not contain credentials.")
|
|
43
|
+
|
|
44
|
+
is_local_base = base_parsed.scheme == "http" and base_host in {"localhost", "127.0.0.1"}
|
|
45
|
+
if is_local_base and host == base_host and parsed.scheme == "http":
|
|
46
|
+
pass
|
|
47
|
+
elif parsed.scheme == "https" and (host in APPROVED_HOSTS or (base_parsed.scheme == "https" and host == base_host)):
|
|
48
|
+
pass
|
|
49
|
+
else:
|
|
50
|
+
raise ApiError(
|
|
51
|
+
CliExitCode.INVALID_INPUT,
|
|
52
|
+
f"Refusing to open non-PriceGraph or insecure URL: {cleaned}",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if parsed.path.startswith("/go/") or parsed.path == "/go":
|
|
56
|
+
raise ApiError(
|
|
57
|
+
CliExitCode.INVALID_INPUT,
|
|
58
|
+
"Refusing to open affiliate redirect (/go/*) directly from CLI.",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
if "\\" in parsed.path or "%2e" in parsed.path.lower() or any(seg in {".", ".."} for seg in parsed.path.split("/")):
|
|
62
|
+
raise ApiError(
|
|
63
|
+
CliExitCode.INVALID_INPUT,
|
|
64
|
+
f"Product URL contains unsafe path traversal segment: {cleaned}",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
if not parsed.path.startswith("/product/") or len(parsed.path) <= len("/product/"):
|
|
68
|
+
raise ApiError(
|
|
69
|
+
CliExitCode.INVALID_INPUT,
|
|
70
|
+
f"Only canonical /product/<slug> pages may be opened (got '{parsed.path}').",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
return urlunparse((parsed.scheme, parsed.netloc, parsed.path, "", parsed.query, ""))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def apply_cli_attribution(product_url: str, *, include_utm: bool = True) -> str:
|
|
77
|
+
"""Append approved first-party acquisition marker (utm_source=cli) without altering canonical URLs."""
|
|
78
|
+
if not include_utm:
|
|
79
|
+
return product_url
|
|
80
|
+
parsed = urlparse(product_url)
|
|
81
|
+
params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=False) if k != "utm_source"]
|
|
82
|
+
params.append(("utm_source", "cli"))
|
|
83
|
+
return urlunparse((parsed.scheme, parsed.netloc, parsed.path, "", urlencode(params), ""))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def save_recent_refs(items: List[Dict[str, str]], base_url: str, now: Optional[float] = None) -> None:
|
|
87
|
+
"""Persist bounded, short-TTL product page references (no prices/offers/catalogue cache)."""
|
|
88
|
+
refs_path = get_refs_path()
|
|
89
|
+
ts = float(now if now is not None else time.time())
|
|
90
|
+
bounded = []
|
|
91
|
+
for idx, it in enumerate(items[:MAX_RECENT_REFS], start=1):
|
|
92
|
+
purl = it.get("product_url") or ""
|
|
93
|
+
if not purl:
|
|
94
|
+
continue
|
|
95
|
+
bounded.append({
|
|
96
|
+
"index": idx,
|
|
97
|
+
"gtin": it.get("gtin") or "",
|
|
98
|
+
"slug": it.get("slug") or "",
|
|
99
|
+
"name": (it.get("name") or "")[:120],
|
|
100
|
+
"product_url": purl,
|
|
101
|
+
})
|
|
102
|
+
payload = {
|
|
103
|
+
"saved_at": ts,
|
|
104
|
+
"ttl_seconds": RECENT_REFS_TTL_SECONDS,
|
|
105
|
+
"base_url": base_url,
|
|
106
|
+
"items": bounded,
|
|
107
|
+
}
|
|
108
|
+
try:
|
|
109
|
+
refs_path.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
refs_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
|
111
|
+
except OSError:
|
|
112
|
+
# Non-fatal if cache dir is read-only
|
|
113
|
+
pass
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def resolve_recent_ref(index: int, base_url: str, now: Optional[float] = None) -> Dict[str, str]:
|
|
117
|
+
"""Resolve a 1-based numbered reference, failing closed if missing, expired, or mismatched."""
|
|
118
|
+
if index < 1:
|
|
119
|
+
raise ApiError(CliExitCode.INVALID_INPUT, "Selection index must be >= 1.")
|
|
120
|
+
|
|
121
|
+
refs_path = get_refs_path()
|
|
122
|
+
if not refs_path.exists():
|
|
123
|
+
raise ApiError(
|
|
124
|
+
CliExitCode.NOT_FOUND,
|
|
125
|
+
"No recent search/deals/batch results found. Run 'pricegraph search <query>' first or pass a GTIN/URL.",
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
data = json.loads(refs_path.read_text(encoding="utf-8"))
|
|
130
|
+
except (OSError, ValueError) as exc:
|
|
131
|
+
raise ApiError(CliExitCode.INVALID_INPUT, f"Could not read recent result references: {exc}") from exc
|
|
132
|
+
|
|
133
|
+
ts = float(now if now is not None else time.time())
|
|
134
|
+
saved_at = float(data.get("saved_at") or 0)
|
|
135
|
+
ttl = float(data.get("ttl_seconds") or RECENT_REFS_TTL_SECONDS)
|
|
136
|
+
if saved_at <= 0 or (ts - saved_at) > ttl:
|
|
137
|
+
raise ApiError(
|
|
138
|
+
CliExitCode.INVALID_INPUT,
|
|
139
|
+
"Recent result references have expired (15-minute limit). Re-run search/deals/batch before opening by number.",
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
if data.get("base_url") != base_url:
|
|
143
|
+
raise ApiError(
|
|
144
|
+
CliExitCode.INVALID_INPUT,
|
|
145
|
+
"Recent result references belong to a different PRICEGRAPH_API_BASE. Re-run search before opening by number.",
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
items = data.get("items") or []
|
|
149
|
+
for it in items:
|
|
150
|
+
if it.get("index") == index:
|
|
151
|
+
return it
|
|
152
|
+
|
|
153
|
+
raise ApiError(
|
|
154
|
+
CliExitCode.NOT_FOUND,
|
|
155
|
+
f"Selection #{index} is out of range (last command returned {len(items)} item(s)).",
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def launch_browser(url: str) -> bool:
|
|
160
|
+
"""Launch user's default browser to a validated URL without shell interpolation."""
|
|
161
|
+
return bool(webbrowser.open(url, new=2))
|
pricegraph_cli/main.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
"""PriceGraph UK CLI command definitions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Any, Dict, List, Optional
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .client import ApiError, CliExitCode, PriceGraphClient, validate_api_base
|
|
13
|
+
from .formatting import emit_csv, emit_json, format_price_gbp, render_table, sanitize_terminal_text
|
|
14
|
+
from .handoff import (
|
|
15
|
+
apply_cli_attribution,
|
|
16
|
+
launch_browser,
|
|
17
|
+
resolve_recent_ref,
|
|
18
|
+
save_recent_refs,
|
|
19
|
+
validate_first_party_product_url,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
app = typer.Typer(
|
|
23
|
+
name="pricegraph",
|
|
24
|
+
help="PriceGraph UK CLI — UK retail price comparison and product discovery.",
|
|
25
|
+
no_args_is_help=True,
|
|
26
|
+
add_completion=False,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
_GTIN_RE = re.compile(r"^\d{8,14}$")
|
|
30
|
+
MAX_BATCH_GTINS = 10
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _fail(err: ApiError) -> None:
|
|
34
|
+
typer.echo(f"Error [{err.status_code or err.exit_code}]: {sanitize_terminal_text(err.message, 300)}", err=True)
|
|
35
|
+
raise typer.Exit(code=err.exit_code)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _canonical_product_url(item: Dict[str, Any], base_url: str) -> str:
|
|
39
|
+
url = item.get("product_url") or item.get("canonical_url")
|
|
40
|
+
if isinstance(url, str) and url.startswith("https://"):
|
|
41
|
+
return url
|
|
42
|
+
slug = item.get("slug")
|
|
43
|
+
if isinstance(slug, str) and slug.strip():
|
|
44
|
+
return f"{base_url}/product/{slug.strip()}"
|
|
45
|
+
return ""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _read_gtins_from_stdin(max_tokens: int = MAX_BATCH_GTINS + 1) -> List[str]:
|
|
49
|
+
if sys.stdin.isatty():
|
|
50
|
+
return []
|
|
51
|
+
tokens: List[str] = []
|
|
52
|
+
for line in sys.stdin:
|
|
53
|
+
for part in re.split(r"[\s,]+", line[:512].strip()):
|
|
54
|
+
if part:
|
|
55
|
+
tokens.append(part)
|
|
56
|
+
if len(tokens) >= max_tokens:
|
|
57
|
+
return tokens
|
|
58
|
+
return tokens
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@app.command("search")
|
|
62
|
+
def cmd_search(
|
|
63
|
+
query: str = typer.Argument(..., help="Search keyword, brand, MPN, or GTIN"),
|
|
64
|
+
limit: int = typer.Option(10, "--limit", "-n", min=1, max=25, help="Max results (1..25)"),
|
|
65
|
+
as_json: bool = typer.Option(False, "--json", help="Emit raw JSON to stdout"),
|
|
66
|
+
as_csv: bool = typer.Option(False, "--csv", help="Emit CSV to stdout"),
|
|
67
|
+
) -> None:
|
|
68
|
+
"""Search PriceGraph UK products."""
|
|
69
|
+
q = query.strip()
|
|
70
|
+
if not q:
|
|
71
|
+
_fail(ApiError(CliExitCode.INVALID_INPUT, "Search query cannot be empty."))
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
with PriceGraphClient() as client:
|
|
75
|
+
data = client.request_json("GET", "/api/agent/v1/search", params={"q": q, "limit": limit})
|
|
76
|
+
base_url = client.base_url
|
|
77
|
+
except ApiError as err:
|
|
78
|
+
_fail(err)
|
|
79
|
+
|
|
80
|
+
if as_json:
|
|
81
|
+
emit_json(data)
|
|
82
|
+
return
|
|
83
|
+
|
|
84
|
+
candidates = data.get("results") or data.get("candidates") or []
|
|
85
|
+
refs_to_save = []
|
|
86
|
+
headers = ["#", "GTIN", "Name", "Brand", "Lowest Price", "Merchants", "Product URL"]
|
|
87
|
+
rows = []
|
|
88
|
+
for idx, c in enumerate(candidates, start=1):
|
|
89
|
+
purl = _canonical_product_url(c, base_url)
|
|
90
|
+
refs_to_save.append({
|
|
91
|
+
"gtin": c.get("gtin") or "",
|
|
92
|
+
"slug": c.get("slug") or "",
|
|
93
|
+
"name": c.get("name") or "",
|
|
94
|
+
"product_url": purl,
|
|
95
|
+
})
|
|
96
|
+
rows.append([
|
|
97
|
+
idx,
|
|
98
|
+
c.get("gtin") or "",
|
|
99
|
+
c.get("name") or "",
|
|
100
|
+
c.get("brand") or "",
|
|
101
|
+
format_price_gbp(c.get("lowest_price") if c.get("lowest_price") is not None else c.get("min_price")),
|
|
102
|
+
c.get("merchant_count") if c.get("merchant_count") is not None else "",
|
|
103
|
+
purl,
|
|
104
|
+
])
|
|
105
|
+
if refs_to_save:
|
|
106
|
+
save_recent_refs(refs_to_save, base_url)
|
|
107
|
+
if as_csv:
|
|
108
|
+
emit_csv(headers[1:], [r[1:] for r in rows])
|
|
109
|
+
return
|
|
110
|
+
if not rows:
|
|
111
|
+
typer.echo(f"No products found for '{sanitize_terminal_text(q, 80)}'.")
|
|
112
|
+
return
|
|
113
|
+
render_table(f"PriceGraph Search: {q}", headers, rows)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@app.command("compare")
|
|
117
|
+
def cmd_compare(
|
|
118
|
+
target: str = typer.Argument(..., help="GTIN/EAN barcode or product query"),
|
|
119
|
+
history: bool = typer.Option(False, "--history", help="Include price history (requires Pro API key)"),
|
|
120
|
+
as_json: bool = typer.Option(False, "--json", help="Emit raw JSON to stdout"),
|
|
121
|
+
as_csv: bool = typer.Option(False, "--csv", help="Emit CSV offer table to stdout"),
|
|
122
|
+
) -> None:
|
|
123
|
+
"""Compare UK merchant offers for a product by GTIN or query."""
|
|
124
|
+
cleaned = target.strip()
|
|
125
|
+
if not cleaned:
|
|
126
|
+
_fail(ApiError(CliExitCode.INVALID_INPUT, "Barcode or query cannot be empty."))
|
|
127
|
+
|
|
128
|
+
params: Dict[str, Any] = {"barcode": cleaned} if _GTIN_RE.match(cleaned) else {"q": cleaned}
|
|
129
|
+
if history:
|
|
130
|
+
params["history"] = "true"
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
with PriceGraphClient() as client:
|
|
134
|
+
data = client.request_json("GET", "/api/agent/v1/compare", params=params)
|
|
135
|
+
base_url = client.base_url
|
|
136
|
+
except ApiError as err:
|
|
137
|
+
_fail(err)
|
|
138
|
+
|
|
139
|
+
if as_json:
|
|
140
|
+
emit_json(data)
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
offers = data.get("offers") or []
|
|
144
|
+
headers = ["Merchant", "Price", "Delivery", "Total", "Stock", "Freshness"]
|
|
145
|
+
rows = [
|
|
146
|
+
[
|
|
147
|
+
o.get("merchant") or o.get("merchant_name") or "",
|
|
148
|
+
format_price_gbp(o.get("item_price") if o.get("item_price") is not None else o.get("price")),
|
|
149
|
+
format_price_gbp(o.get("delivery_cost")),
|
|
150
|
+
format_price_gbp(o.get("total_landed_price") if o.get("total_landed_price") is not None else o.get("price")),
|
|
151
|
+
o.get("stock_status") or o.get("availability") or "unknown",
|
|
152
|
+
o.get("offer_freshness") or "",
|
|
153
|
+
]
|
|
154
|
+
for o in offers
|
|
155
|
+
]
|
|
156
|
+
if as_csv:
|
|
157
|
+
emit_csv(headers, rows)
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
title = data.get("name") or data.get("product_name") or cleaned
|
|
161
|
+
render_table(f"Offers: {title}", headers, rows)
|
|
162
|
+
purl = _canonical_product_url(data, base_url)
|
|
163
|
+
if purl:
|
|
164
|
+
typer.echo(f"Product page: {purl}")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@app.command("resolve")
|
|
168
|
+
def cmd_resolve(
|
|
169
|
+
brand: Optional[str] = typer.Option(None, "--brand", "-b", help="Brand name"),
|
|
170
|
+
mpn: Optional[str] = typer.Option(None, "--mpn", "-m", help="Manufacturer part number"),
|
|
171
|
+
q: Optional[str] = typer.Option(None, "--q", help="Free-text product query"),
|
|
172
|
+
as_json: bool = typer.Option(False, "--json", help="Emit raw JSON to stdout"),
|
|
173
|
+
) -> None:
|
|
174
|
+
"""Resolve brand/MPN/query to canonical GTIN product identity."""
|
|
175
|
+
params: Dict[str, Any] = {}
|
|
176
|
+
if brand:
|
|
177
|
+
params["brand"] = brand.strip()
|
|
178
|
+
if mpn:
|
|
179
|
+
params["mpn"] = mpn.strip()
|
|
180
|
+
if q:
|
|
181
|
+
params["q"] = q.strip()
|
|
182
|
+
if not params:
|
|
183
|
+
_fail(ApiError(CliExitCode.INVALID_INPUT, "Provide at least one of --brand, --mpn, or --q."))
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
with PriceGraphClient() as client:
|
|
187
|
+
data = client.request_json("GET", "/api/agent/v1/resolve", params=params)
|
|
188
|
+
except ApiError as err:
|
|
189
|
+
_fail(err)
|
|
190
|
+
|
|
191
|
+
if as_json:
|
|
192
|
+
emit_json(data)
|
|
193
|
+
return
|
|
194
|
+
|
|
195
|
+
matches = data.get("matches") or data.get("candidates") or []
|
|
196
|
+
if not matches:
|
|
197
|
+
typer.echo("No canonical product match found.")
|
|
198
|
+
return
|
|
199
|
+
headers = ["GTIN", "Brand", "MPN", "Name", "Confidence"]
|
|
200
|
+
rows = [
|
|
201
|
+
[m.get("gtin") or "", m.get("brand") or "", m.get("mpn") or "", m.get("name") or "", m.get("confidence") or ""]
|
|
202
|
+
for m in matches
|
|
203
|
+
]
|
|
204
|
+
render_table("Resolved Product Matches", headers, rows)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@app.command("batch")
|
|
208
|
+
def cmd_batch(
|
|
209
|
+
gtins: List[str] = typer.Argument(None, help="Up to 10 GTIN/EAN barcodes"),
|
|
210
|
+
from_stdin: bool = typer.Option(False, "--stdin", help="Read GTINs from stdin"),
|
|
211
|
+
as_json: bool = typer.Option(False, "--json", help="Emit raw JSON to stdout"),
|
|
212
|
+
as_csv: bool = typer.Option(False, "--csv", help="Emit CSV to stdout"),
|
|
213
|
+
) -> None:
|
|
214
|
+
"""Batch-compare up to 10 GTINs in one request."""
|
|
215
|
+
raw_list = list(gtins or [])
|
|
216
|
+
if from_stdin or not raw_list:
|
|
217
|
+
raw_list.extend(_read_gtins_from_stdin())
|
|
218
|
+
|
|
219
|
+
cleaned: List[str] = []
|
|
220
|
+
seen = set()
|
|
221
|
+
invalid: List[str] = []
|
|
222
|
+
for item in raw_list:
|
|
223
|
+
token = item.strip()
|
|
224
|
+
if not token:
|
|
225
|
+
continue
|
|
226
|
+
if not _GTIN_RE.match(token):
|
|
227
|
+
invalid.append(token)
|
|
228
|
+
continue
|
|
229
|
+
if token not in seen:
|
|
230
|
+
seen.add(token)
|
|
231
|
+
cleaned.append(token)
|
|
232
|
+
|
|
233
|
+
if invalid:
|
|
234
|
+
_fail(ApiError(CliExitCode.INVALID_INPUT, f"Invalid GTIN(s): {', '.join(invalid[:5])}"))
|
|
235
|
+
if not cleaned:
|
|
236
|
+
_fail(ApiError(CliExitCode.INVALID_INPUT, "Provide 1 to 10 valid 8-14 digit GTINs."))
|
|
237
|
+
if len(cleaned) > MAX_BATCH_GTINS:
|
|
238
|
+
_fail(ApiError(CliExitCode.INVALID_INPUT, f"Batch size {len(cleaned)} exceeds max {MAX_BATCH_GTINS} GTINs."))
|
|
239
|
+
|
|
240
|
+
try:
|
|
241
|
+
with PriceGraphClient() as client:
|
|
242
|
+
data = client.request_json("POST", "/api/agent/v1/compare/batch", json_body={"gtins": cleaned})
|
|
243
|
+
base_url = client.base_url
|
|
244
|
+
except ApiError as err:
|
|
245
|
+
_fail(err)
|
|
246
|
+
|
|
247
|
+
if as_json:
|
|
248
|
+
emit_json(data)
|
|
249
|
+
return
|
|
250
|
+
|
|
251
|
+
if data.get("degraded"):
|
|
252
|
+
typer.echo("Warning: partial catalog read errors occurred for one or more GTINs.", err=True)
|
|
253
|
+
|
|
254
|
+
items = data.get("items") or data.get("results") or data.get("products") or []
|
|
255
|
+
refs_to_save = []
|
|
256
|
+
headers = ["#", "GTIN", "Status", "Name", "Best Price", "Merchants", "Product URL"]
|
|
257
|
+
rows = []
|
|
258
|
+
for idx, it in enumerate(items, start=1):
|
|
259
|
+
best_offer = it.get("best_new_offer") or it.get("best_outlet_offer") or {}
|
|
260
|
+
best_price = best_offer.get("price") if isinstance(best_offer, dict) else it.get("min_price")
|
|
261
|
+
status_label = it.get("status") or ("ok" if it.get("found", True) and it.get("name") else "not_found")
|
|
262
|
+
purl = _canonical_product_url(it, base_url)
|
|
263
|
+
if purl:
|
|
264
|
+
refs_to_save.append({
|
|
265
|
+
"gtin": it.get("gtin") or "",
|
|
266
|
+
"slug": it.get("slug") or "",
|
|
267
|
+
"name": it.get("name") or "",
|
|
268
|
+
"product_url": purl,
|
|
269
|
+
})
|
|
270
|
+
rows.append([
|
|
271
|
+
idx,
|
|
272
|
+
it.get("gtin") or "",
|
|
273
|
+
status_label,
|
|
274
|
+
it.get("name") or "",
|
|
275
|
+
format_price_gbp(best_price),
|
|
276
|
+
it.get("merchant_count") if it.get("merchant_count") is not None else "",
|
|
277
|
+
purl,
|
|
278
|
+
])
|
|
279
|
+
if refs_to_save:
|
|
280
|
+
save_recent_refs(refs_to_save, base_url)
|
|
281
|
+
if as_csv:
|
|
282
|
+
emit_csv(headers[1:], [r[1:] for r in rows])
|
|
283
|
+
return
|
|
284
|
+
render_table(f"Batch Comparison ({len(cleaned)} GTINs)", headers, rows)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@app.command("categories")
|
|
288
|
+
def cmd_categories(
|
|
289
|
+
limit: int = typer.Option(25, "--limit", "-n", min=1, max=50),
|
|
290
|
+
offset: int = typer.Option(0, "--offset", min=0),
|
|
291
|
+
published_only: bool = typer.Option(False, "--published-only"),
|
|
292
|
+
as_json: bool = typer.Option(False, "--json"),
|
|
293
|
+
as_csv: bool = typer.Option(False, "--csv"),
|
|
294
|
+
) -> None:
|
|
295
|
+
"""List canonical UK retail categories."""
|
|
296
|
+
params: Dict[str, Any] = {"limit": limit, "offset": offset}
|
|
297
|
+
if published_only:
|
|
298
|
+
params["published_only"] = "true"
|
|
299
|
+
try:
|
|
300
|
+
with PriceGraphClient() as client:
|
|
301
|
+
data = client.request_json("GET", "/api/agent/v1/categories", params=params)
|
|
302
|
+
except ApiError as err:
|
|
303
|
+
_fail(err)
|
|
304
|
+
|
|
305
|
+
if as_json:
|
|
306
|
+
emit_json(data)
|
|
307
|
+
return
|
|
308
|
+
|
|
309
|
+
cats = data.get("categories") or []
|
|
310
|
+
headers = ["Slug", "Name", "Products", "Intelligence Published"]
|
|
311
|
+
rows = [
|
|
312
|
+
[c.get("slug") or "", c.get("name") or "", c.get("product_count") or 0, bool(c.get("intelligence_published"))]
|
|
313
|
+
for c in cats
|
|
314
|
+
]
|
|
315
|
+
if as_csv:
|
|
316
|
+
emit_csv(headers, rows)
|
|
317
|
+
return
|
|
318
|
+
render_table("PriceGraph Categories", headers, rows)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@app.command("merchants")
|
|
322
|
+
def cmd_merchants(
|
|
323
|
+
q: Optional[str] = typer.Option(None, "--q", help="Filter merchants by name"),
|
|
324
|
+
as_json: bool = typer.Option(False, "--json"),
|
|
325
|
+
as_csv: bool = typer.Option(False, "--csv"),
|
|
326
|
+
) -> None:
|
|
327
|
+
"""List participating UK retail merchants."""
|
|
328
|
+
params = {"q": q.strip()} if q and q.strip() else None
|
|
329
|
+
try:
|
|
330
|
+
with PriceGraphClient() as client:
|
|
331
|
+
data = client.request_json("GET", "/api/agent/v1/merchants", params=params)
|
|
332
|
+
except ApiError as err:
|
|
333
|
+
_fail(err)
|
|
334
|
+
|
|
335
|
+
if as_json:
|
|
336
|
+
emit_json(data)
|
|
337
|
+
return
|
|
338
|
+
|
|
339
|
+
merchants = data.get("merchants") or []
|
|
340
|
+
headers = ["Slug", "Name", "Products", "Sector"]
|
|
341
|
+
rows = [
|
|
342
|
+
[
|
|
343
|
+
m.get("slug") or "",
|
|
344
|
+
m.get("name") or "",
|
|
345
|
+
m.get("product_count") if m.get("product_count") is not None else (m.get("offer_count") or ""),
|
|
346
|
+
m.get("primary_sector") or m.get("network") or "",
|
|
347
|
+
]
|
|
348
|
+
for m in merchants
|
|
349
|
+
]
|
|
350
|
+
if as_csv:
|
|
351
|
+
emit_csv(headers, rows)
|
|
352
|
+
return
|
|
353
|
+
render_table("PriceGraph UK Merchants", headers, rows)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
@app.command("deals")
|
|
357
|
+
def cmd_deals(
|
|
358
|
+
limit: int = typer.Option(20, "--limit", "-n", min=1, max=50),
|
|
359
|
+
as_json: bool = typer.Option(False, "--json"),
|
|
360
|
+
as_csv: bool = typer.Option(False, "--csv"),
|
|
361
|
+
) -> None:
|
|
362
|
+
"""List current verified UK retail deals."""
|
|
363
|
+
try:
|
|
364
|
+
with PriceGraphClient() as client:
|
|
365
|
+
data = client.request_json("GET", "/api/agent/v1/deals", params={"limit": limit})
|
|
366
|
+
base_url = client.base_url
|
|
367
|
+
except ApiError as err:
|
|
368
|
+
_fail(err)
|
|
369
|
+
|
|
370
|
+
if as_json:
|
|
371
|
+
emit_json(data)
|
|
372
|
+
return
|
|
373
|
+
|
|
374
|
+
deals = data.get("deals") or data.get("items") or []
|
|
375
|
+
refs_to_save = []
|
|
376
|
+
headers = ["#", "Title", "Lowest Price", "Saving %", "Product URL"]
|
|
377
|
+
rows = []
|
|
378
|
+
for idx, d in enumerate(deals, start=1):
|
|
379
|
+
purl = _canonical_product_url(d, base_url)
|
|
380
|
+
if purl:
|
|
381
|
+
refs_to_save.append({
|
|
382
|
+
"gtin": d.get("gtin") or "",
|
|
383
|
+
"slug": d.get("slug") or "",
|
|
384
|
+
"name": d.get("name") or d.get("title") or "",
|
|
385
|
+
"product_url": purl,
|
|
386
|
+
})
|
|
387
|
+
rows.append([
|
|
388
|
+
idx,
|
|
389
|
+
d.get("name") or d.get("title") or "",
|
|
390
|
+
format_price_gbp(
|
|
391
|
+
d.get("lowest_price") if d.get("lowest_price") is not None
|
|
392
|
+
else (d.get("price") if d.get("price") is not None else d.get("min_price"))
|
|
393
|
+
),
|
|
394
|
+
d.get("savings_pct") if d.get("savings_pct") is not None else (d.get("discount_pct") or ""),
|
|
395
|
+
purl,
|
|
396
|
+
])
|
|
397
|
+
if refs_to_save:
|
|
398
|
+
save_recent_refs(refs_to_save, base_url)
|
|
399
|
+
if as_csv:
|
|
400
|
+
emit_csv(headers[1:], [r[1:] for r in rows])
|
|
401
|
+
return
|
|
402
|
+
render_table("PriceGraph UK Deals", headers, rows)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
@app.command("open")
|
|
406
|
+
def cmd_open(
|
|
407
|
+
target: str = typer.Argument(..., help="Result # (e.g. 1), GTIN barcode, product slug, or PriceGraph product URL"),
|
|
408
|
+
no_utm: bool = typer.Option(False, "--no-utm", help="Omit ?utm_source=cli attribution parameter"),
|
|
409
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="Validate and print URL without launching browser"),
|
|
410
|
+
as_json: bool = typer.Option(False, "--json", help="Emit JSON result to stdout"),
|
|
411
|
+
) -> None:
|
|
412
|
+
"""Explicitly open a validated PriceGraph product page in your browser."""
|
|
413
|
+
cleaned = target.strip()
|
|
414
|
+
if not cleaned:
|
|
415
|
+
_fail(ApiError(CliExitCode.INVALID_INPUT, "Target cannot be empty."))
|
|
416
|
+
|
|
417
|
+
try:
|
|
418
|
+
base_url = validate_api_base()
|
|
419
|
+
canonical_url = ""
|
|
420
|
+
|
|
421
|
+
if cleaned.isdigit() and len(cleaned) <= 3:
|
|
422
|
+
ref = resolve_recent_ref(int(cleaned), base_url)
|
|
423
|
+
canonical_url = ref.get("product_url") or ""
|
|
424
|
+
elif cleaned.startswith(("http://", "https://")):
|
|
425
|
+
canonical_url = cleaned
|
|
426
|
+
elif _GTIN_RE.match(cleaned):
|
|
427
|
+
with PriceGraphClient(base_url=base_url) as client:
|
|
428
|
+
data = client.request_json("GET", "/api/agent/v1/compare", params={"barcode": cleaned})
|
|
429
|
+
canonical_url = _canonical_product_url(data, base_url)
|
|
430
|
+
if not canonical_url:
|
|
431
|
+
raise ApiError(CliExitCode.NOT_FOUND, f"No canonical product URL returned for GTIN '{cleaned}'.")
|
|
432
|
+
else:
|
|
433
|
+
slug = cleaned.lstrip("/")
|
|
434
|
+
if slug.startswith("product/"):
|
|
435
|
+
slug = slug[len("product/"):]
|
|
436
|
+
canonical_url = f"{base_url}/product/{slug}"
|
|
437
|
+
|
|
438
|
+
validated_url = validate_first_party_product_url(canonical_url, base_url)
|
|
439
|
+
launch_url = apply_cli_attribution(validated_url, include_utm=not no_utm)
|
|
440
|
+
|
|
441
|
+
opened = False
|
|
442
|
+
if not dry_run:
|
|
443
|
+
opened = launch_browser(launch_url)
|
|
444
|
+
except ApiError as err:
|
|
445
|
+
_fail(err)
|
|
446
|
+
|
|
447
|
+
if as_json:
|
|
448
|
+
emit_json({
|
|
449
|
+
"canonical_url": validated_url,
|
|
450
|
+
"launch_url": launch_url,
|
|
451
|
+
"dry_run": dry_run,
|
|
452
|
+
"opened": opened,
|
|
453
|
+
})
|
|
454
|
+
return
|
|
455
|
+
|
|
456
|
+
if dry_run:
|
|
457
|
+
typer.echo(launch_url)
|
|
458
|
+
elif opened:
|
|
459
|
+
typer.echo(f"Opened {launch_url}")
|
|
460
|
+
else:
|
|
461
|
+
typer.echo(f"Open in browser: {launch_url}")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
@app.command("version")
|
|
465
|
+
def cmd_version(
|
|
466
|
+
remote: bool = typer.Option(False, "--remote", help="Also query hosted /api/version"),
|
|
467
|
+
as_json: bool = typer.Option(False, "--json"),
|
|
468
|
+
) -> None:
|
|
469
|
+
"""Show CLI version (and optionally hosted API version)."""
|
|
470
|
+
info: Dict[str, Any] = {"cli_version": __version__}
|
|
471
|
+
if remote:
|
|
472
|
+
try:
|
|
473
|
+
with PriceGraphClient() as client:
|
|
474
|
+
info["api_version"] = client.request_json("GET", "/api/version")
|
|
475
|
+
except ApiError as err:
|
|
476
|
+
_fail(err)
|
|
477
|
+
if as_json:
|
|
478
|
+
emit_json(info)
|
|
479
|
+
return
|
|
480
|
+
typer.echo(f"pricegraph-cli {__version__}")
|
|
481
|
+
if "api_version" in info:
|
|
482
|
+
typer.echo(f"remote: {info['api_version'].get('version', 'unknown')}")
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
if __name__ == "__main__":
|
|
486
|
+
app()
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pricegraph-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official PriceGraph UK command-line interface for product discovery and price comparison
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: typer<1.0.0,>=0.12.0
|
|
8
|
+
Requires-Dist: httpx<1.0.0,>=0.27.0
|
|
9
|
+
Requires-Dist: rich<16.0.0,>=13.7.0
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest<10.0.0,>=8.0.0; extra == "dev"
|
|
12
|
+
|
|
13
|
+
# PriceGraph CLI (`pricegraph-cli`)
|
|
14
|
+
|
|
15
|
+
Official, lightweight, read-only command-line interface for **PriceGraph UK** (`https://www.pricegraph.co.uk`).
|
|
16
|
+
|
|
17
|
+
## Installation (Once Published)
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pipx install pricegraph-cli
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Local Development Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install --no-deps --no-build-isolation -e ./cli
|
|
27
|
+
pricegraph --help
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Uninstall
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip uninstall -y pricegraph-cli
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Commands
|
|
37
|
+
|
|
38
|
+
| Command | Description | Example |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `search` | Search UK retail products | `pricegraph search "sony wh1000xm5" --limit 5` |
|
|
41
|
+
| `compare` | Compare live UK offers by GTIN or query | `pricegraph compare 4548736132566` |
|
|
42
|
+
| `resolve` | Resolve Brand + MPN to canonical GTIN | `pricegraph resolve --brand Sony --mpn WH1000XM5` |
|
|
43
|
+
| `batch` | Batch-compare up to 10 GTINs (args or `--stdin`) | `pricegraph batch 4548736132566 5036108314256` |
|
|
44
|
+
| `categories` | List canonical UK retail categories | `pricegraph categories --published-only` |
|
|
45
|
+
| `merchants` | List participating UK retail merchants | `pricegraph merchants --q laptop` |
|
|
46
|
+
| `deals` | List current verified UK retail deals | `pricegraph deals --limit 10` |
|
|
47
|
+
| `open` | Explicitly open a validated `/product/<slug>` page | `pricegraph open 1` or `pricegraph open 4548736132566 --dry-run` |
|
|
48
|
+
| `version` | Show CLI version (offline by default; `--remote` checks API) | `pricegraph version --json` |
|
|
49
|
+
|
|
50
|
+
## Machine Output & Exit Codes
|
|
51
|
+
|
|
52
|
+
* `--json` and `--csv` write strictly to `stdout` (no banners or spinners); errors and warnings write to `stderr`.
|
|
53
|
+
* CSV output neutralizes spreadsheet formula prefixes (`=`, `+`, `-`, `@`, `\t`, `\r`).
|
|
54
|
+
* Exit codes: `0` OK, `2` invalid input, `3` not found (`404`), `4` restricted (`401`/`402`/`403`), `5` rate-limited/unavailable (`429`/`503`), `6` transport/malformed response.
|
|
55
|
+
|
|
56
|
+
## Privacy & Commercial Model
|
|
57
|
+
|
|
58
|
+
* **No affiliate links or redirects:** The CLI never contains affiliate URLs, sets affiliate cookies, or opens `/go/*` endpoints. `pricegraph open` launches only validated first-party `https://www.pricegraph.co.uk/product/<slug>?utm_source=cli` pages (`--no-utm` omits `utm_source=cli`).
|
|
59
|
+
* **Minimal, opt-out telemetry:** By default, requests send `User-Agent: pricegraph-cli/<version>` and `X-PriceGraph-Client: cli/<version>`. Set `PRICEGRAPH_NO_TELEMETRY=1` (or `PRICEGRAPH_TELEMETRY=0`) to omit `X-PriceGraph-Client` and use a generic `User-Agent`.
|
|
60
|
+
* **No persistent catalogue cache:** Only short-TTL (`15m`) product page references for numbered `pricegraph open <n>` are stored locally (`~/.cache/pricegraph-cli/recent_refs.json`).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
pricegraph_cli/__init__.py,sha256=VOcMFrZaaNPPEL2gbsqShZbZym5xvi-Qs_ZBQ_HcbFw,67
|
|
2
|
+
pricegraph_cli/client.py,sha256=tZpHtCn1QsmA6nM34CIAhpWAkg02jZJrrAI9nh_I0Rw,5860
|
|
3
|
+
pricegraph_cli/formatting.py,sha256=oeOgmfiqVTEuo88IXAYBWREMfIf1A_wa-PCyVm52LqA,2291
|
|
4
|
+
pricegraph_cli/handoff.py,sha256=XmvcePeeBko9mVt1FMoXYjB26D4-amcSKMqK0GmZKSc,6254
|
|
5
|
+
pricegraph_cli/main.py,sha256=XMYvBRgyqq4wBJuhaPRVk8jXKwZQmnDbv7kVfequWZA,17344
|
|
6
|
+
pricegraph_cli-0.1.0.dist-info/METADATA,sha256=_cqkhdDtO3Xee4b92uJhqu1MXKhsybsEiGjfq44c2b8,2959
|
|
7
|
+
pricegraph_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
pricegraph_cli-0.1.0.dist-info/entry_points.txt,sha256=lE7fMOhCeNwclzZgoxP0AkrvEJKBU--7PtZKzCoPclo,55
|
|
9
|
+
pricegraph_cli-0.1.0.dist-info/top_level.txt,sha256=aWBjNDn_HLibsxjVvF3wpOmwOD7JEF0jv7sGLA1J2YI,15
|
|
10
|
+
pricegraph_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pricegraph_cli
|