gsc-cli 0.2.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.
gsc/cli/multimodal.py ADDED
@@ -0,0 +1,203 @@
1
+ """``gsc multimodal`` — ingest a Search Console UI export filtered to Web: multimodal.
2
+
3
+ The Search Analytics API has no multimodal search type (verified 2026-09-24,
4
+ discovery revision 20260923: ``type`` enum is WEB/IMAGE/VIDEO/NEWS/DISCOVER/
5
+ GOOGLE_NEWS and undocumented values return HTTP 400). The data is only reachable
6
+ through the Performance report's Export, so this command parses that export and
7
+ can join it with API ``web`` totals for the same dates to get the multimodal share.
8
+
9
+ API ``web`` equals the UI's "Web (text)" and excludes multimodal (verified on a
10
+ Bulgarian e-commerce property, 2026-06-22..2026-09-21: API 14,108 clicks / 468,429 impressions = UI
11
+ Web (text) exactly; UI Web (multimodal) 60 / 1,219 on top). Total = text + multimodal.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import io
18
+ import zipfile
19
+ from pathlib import Path
20
+ from urllib.parse import unquote
21
+
22
+ import click
23
+
24
+ from ..client import GSCClient
25
+ from ..formatters import format_output
26
+ from .sites import get_client
27
+
28
+ # Export file per grouping. Queries are absent for multimodal: the query is an image.
29
+ _EXPORT_FILES = {
30
+ "page": "Pages.csv",
31
+ "country": "Countries.csv",
32
+ "device": "Devices.csv",
33
+ "date": "Dates.csv",
34
+ }
35
+ _API_PAGE_SIZE = 25000
36
+
37
+
38
+ def _read_export_file(source: Path, filename: str) -> tuple[str, str | None]:
39
+ """Return (CSV text of ``filename``, Filters.csv text or None) from a zip, dir or CSV."""
40
+ if source.is_file() and source.suffix.lower() == ".csv":
41
+ filters = source.with_name("Filters.csv")
42
+ return (
43
+ source.read_text(encoding="utf-8-sig"),
44
+ filters.read_text(encoding="utf-8-sig") if filters.exists() else None,
45
+ )
46
+ if source.is_file() and zipfile.is_zipfile(source):
47
+ with zipfile.ZipFile(source) as zf:
48
+ names = {Path(n).name.lower(): n for n in zf.namelist()}
49
+
50
+ def _get(name: str) -> str | None:
51
+ member = names.get(name.lower())
52
+ return zf.read(member).decode("utf-8-sig") if member else None
53
+
54
+ text = _get(filename)
55
+ if text is None:
56
+ raise click.BadParameter(
57
+ f"{filename} not found in {source.name}; available: {sorted(names)}. "
58
+ "Pass the CSV path directly if the export is localized."
59
+ )
60
+ return text, _get("Filters.csv")
61
+ if source.is_dir():
62
+ target = source / filename
63
+ if not target.exists():
64
+ raise click.BadParameter(f"{filename} not found in {source}")
65
+ filters = source / "Filters.csv"
66
+ return (
67
+ target.read_text(encoding="utf-8-sig"),
68
+ filters.read_text(encoding="utf-8-sig") if filters.exists() else None,
69
+ )
70
+ raise click.BadParameter(f"Not a GSC export zip, directory or CSV: {source}")
71
+
72
+
73
+ def _is_multimodal_export(filters_text: str | None) -> bool | None:
74
+ """Whether Filters.csv records a multimodal search type; None when there is no Filters.csv.
75
+
76
+ Matched on the value stem ("multimod" / "мултимод") because labels are localized.
77
+ """
78
+ if not filters_text:
79
+ return None
80
+ lowered = filters_text.lower()
81
+ return "multimod" in lowered or "мултимод" in lowered
82
+
83
+
84
+ def _number(value: str) -> float:
85
+ cleaned = value.strip().replace(" ", "").replace(" ", "").rstrip("%")
86
+ if not cleaned:
87
+ return 0.0
88
+ # Localized exports may use a decimal comma ("3,44") with no thousands separator.
89
+ if "," in cleaned and "." not in cleaned:
90
+ cleaned = cleaned.replace(",", ".")
91
+ else:
92
+ cleaned = cleaned.replace(",", "")
93
+ return float(cleaned)
94
+
95
+
96
+ def parse_export_rows(text: str, key_name: str) -> list[dict]:
97
+ """Parse an export CSV positionally: key, clicks, impressions, CTR, position.
98
+
99
+ Header names are ignored because Search Console localizes them to the UI language.
100
+ """
101
+ reader = csv.reader(io.StringIO(text))
102
+ next(reader, None)
103
+ rows: list[dict] = []
104
+ for record in reader:
105
+ if len(record) < 5 or not record[0].strip():
106
+ continue
107
+ clicks = int(_number(record[1]))
108
+ impressions = int(_number(record[2]))
109
+ rows.append(
110
+ {
111
+ key_name: record[0].strip(),
112
+ "clicks": clicks,
113
+ "impressions": impressions,
114
+ "ctr": f"{(clicks / impressions * 100) if impressions else 0:.2f}%",
115
+ "position": round(_number(record[4]), 1),
116
+ }
117
+ )
118
+ return rows
119
+
120
+
121
+ def _fetch_text_by_page(
122
+ client: GSCClient, site_url: str, start_date: str, end_date: str
123
+ ) -> dict[str, tuple[int, int]]:
124
+ """All pages' API ``web`` (= text-based) clicks/impressions, keyed by decoded URL."""
125
+ totals: dict[str, tuple[int, int]] = {}
126
+ start_row = 0
127
+ while True:
128
+ body = GSCClient.build_query_body(
129
+ start_date=start_date,
130
+ end_date=end_date,
131
+ dimensions=["page"],
132
+ search_type="web",
133
+ row_limit=_API_PAGE_SIZE,
134
+ start_row=start_row,
135
+ )
136
+ response = client.query(site_url, body)
137
+ for row in response.rows:
138
+ totals[unquote(row.keys[0])] = (int(row.clicks), int(row.impressions))
139
+ if len(response.rows) < _API_PAGE_SIZE:
140
+ return totals
141
+ start_row += _API_PAGE_SIZE
142
+
143
+
144
+ def _pct(part: float, whole: float) -> str:
145
+ return f"{part / whole * 100:.2f}%" if whole else "n/a"
146
+
147
+
148
+ @click.command()
149
+ @click.argument("site_url")
150
+ @click.argument("export", type=click.Path(exists=True, path_type=Path))
151
+ @click.option(
152
+ "--by",
153
+ "grouping",
154
+ type=click.Choice(sorted(_EXPORT_FILES)),
155
+ default="page",
156
+ help="Which export table to read (default: page). Queries do not exist for multimodal.",
157
+ )
158
+ @click.option("--start-date", default=None, help="Export start date, for --compare.")
159
+ @click.option("--end-date", default=None, help="Export end date, for --compare.")
160
+ @click.option(
161
+ "--compare",
162
+ is_flag=True,
163
+ help="Join with API web (= text-based) by page for the same dates (needs --by page + dates).",
164
+ )
165
+ @click.pass_context
166
+ def multimodal(
167
+ ctx: click.Context,
168
+ site_url: str,
169
+ export: Path,
170
+ grouping: str,
171
+ start_date: str | None,
172
+ end_date: str | None,
173
+ compare: bool,
174
+ ) -> None:
175
+ """Parse a Performance export filtered to Web: multimodal for SITE_URL.
176
+
177
+ EXPORT is the downloaded zip, its extracted folder, or one CSV from it.
178
+ """
179
+ text, filters_text = _read_export_file(export, _EXPORT_FILES[grouping])
180
+ if _is_multimodal_export(filters_text) is False:
181
+ click.echo(
182
+ "Warning: Filters.csv does not show a multimodal search type. "
183
+ "Re-export with Search type -> Web -> Multimodal.",
184
+ err=True,
185
+ )
186
+
187
+ rows = parse_export_rows(text, grouping)
188
+
189
+ if compare:
190
+ if grouping != "page" or not (start_date and end_date):
191
+ raise click.UsageError("--compare needs --by page plus --start-date and --end-date.")
192
+ ctx.obj["site_url"] = site_url
193
+ text_by_page = _fetch_text_by_page(get_client(ctx), site_url, start_date, end_date)
194
+ for row in rows:
195
+ text_clicks, text_impr = text_by_page.get(unquote(row["page"]), (0, 0))
196
+ row["text_clicks"] = text_clicks
197
+ row["text_impressions"] = text_impr
198
+ row["mm_share_impressions"] = _pct(row["impressions"], text_impr + row["impressions"])
199
+ row["text_ctr"] = _pct(text_clicks, text_impr)
200
+
201
+ if grouping != "date":
202
+ rows.sort(key=lambda r: r["impressions"], reverse=True)
203
+ click.echo(format_output(rows, fmt=ctx.obj["format"]))
gsc/cli/query.py ADDED
@@ -0,0 +1,108 @@
1
+ """``gsc query`` command and the filter-string parser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from ..client import GSCClient
8
+ from ..formatters import format_output
9
+ from .sites import get_client
10
+
11
+
12
+ def parse_filter(filter_str: str) -> dict:
13
+ """Parse a ``dimension operator expression`` filter string into an API dict.
14
+
15
+ The string is split into exactly three parts on whitespace, so the
16
+ expression may itself contain spaces (e.g. ``query contains best shoes``).
17
+ """
18
+ parts = filter_str.split(None, 2)
19
+ if len(parts) != 3:
20
+ raise click.BadParameter(
21
+ f"Filter must be 'dimension operator expression', got: {filter_str!r}"
22
+ )
23
+ dimension, operator, expression = parts
24
+ return {
25
+ "dimension": dimension,
26
+ "operator": operator,
27
+ "expression": expression,
28
+ }
29
+
30
+
31
+ @click.command()
32
+ @click.argument("site_url")
33
+ @click.option("--start-date", required=True, help="Start date (YYYY-MM-DD).")
34
+ @click.option("--end-date", required=True, help="End date (YYYY-MM-DD).")
35
+ @click.option(
36
+ "--dimensions",
37
+ "-d",
38
+ default="",
39
+ help="Comma-separated dimensions (query,page,country,device,date,searchAppearance).",
40
+ )
41
+ @click.option(
42
+ "--search-type",
43
+ default=None,
44
+ help="Search type: web, image, video, news, discover, googleNews.",
45
+ )
46
+ @click.option(
47
+ "--filter",
48
+ "filters",
49
+ multiple=True,
50
+ help="Filter as 'dimension operator expression'. Repeatable.",
51
+ )
52
+ @click.option(
53
+ "--aggregation", "aggregation_type", default=None, help="auto, byPage, or byProperty."
54
+ )
55
+ @click.option("--row-limit", type=int, default=1000, help="Max rows (1-25000).")
56
+ @click.option("--start-row", type=int, default=0, help="Pagination start row.")
57
+ @click.option(
58
+ "--data-state",
59
+ default=None,
60
+ help="all (include fresh) or final (default Google behaviour).",
61
+ )
62
+ @click.pass_context
63
+ def query(
64
+ ctx: click.Context,
65
+ site_url: str,
66
+ start_date: str,
67
+ end_date: str,
68
+ dimensions: str,
69
+ search_type: str | None,
70
+ filters: tuple[str, ...],
71
+ aggregation_type: str | None,
72
+ row_limit: int,
73
+ start_row: int,
74
+ data_state: str | None,
75
+ ) -> None:
76
+ """Query Search Analytics for SITE_URL."""
77
+ ctx.obj["site_url"] = site_url
78
+ client = get_client(ctx)
79
+
80
+ dimension_list = [d.strip() for d in dimensions.split(",") if d.strip()]
81
+ parsed_filters = [parse_filter(f) for f in filters]
82
+
83
+ body = GSCClient.build_query_body(
84
+ start_date=start_date,
85
+ end_date=end_date,
86
+ dimensions=dimension_list or None,
87
+ search_type=search_type,
88
+ filters=parsed_filters or None,
89
+ aggregation_type=aggregation_type,
90
+ row_limit=row_limit,
91
+ start_row=start_row,
92
+ data_state=data_state,
93
+ )
94
+
95
+ response = client.query(site_url, body)
96
+ rows = [_format_row(row, dimension_list) for row in response.rows]
97
+ click.echo(format_output(rows, fmt=ctx.obj["format"]))
98
+
99
+
100
+ def _format_row(row, dimensions: list[str]) -> dict:
101
+ out: dict = {}
102
+ for name, value in zip(dimensions, row.keys):
103
+ out[name] = value
104
+ out["clicks"] = int(row.clicks)
105
+ out["impressions"] = int(row.impressions)
106
+ out["ctr"] = f"{row.ctr * 100:.2f}%"
107
+ out["position"] = round(row.position, 1)
108
+ return out
gsc/cli/sitemaps.py ADDED
@@ -0,0 +1,62 @@
1
+ """``gsc sitemaps`` group: list, get, submit, delete."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict
6
+
7
+ import click
8
+
9
+ from ..formatters import format_output
10
+ from .sites import get_client
11
+
12
+
13
+ @click.group()
14
+ def sitemaps() -> None:
15
+ """List and manage submitted sitemaps."""
16
+
17
+
18
+ @sitemaps.command("list")
19
+ @click.argument("site_url")
20
+ @click.pass_context
21
+ def list_sitemaps(ctx: click.Context, site_url: str) -> None:
22
+ """List all sitemaps for SITE_URL."""
23
+ ctx.obj["site_url"] = site_url
24
+ client = get_client(ctx)
25
+ rows = [asdict(s) for s in client.list_sitemaps(site_url)]
26
+ click.echo(format_output(rows, fmt=ctx.obj["format"]))
27
+
28
+
29
+ @sitemaps.command("get")
30
+ @click.argument("site_url")
31
+ @click.argument("feedpath")
32
+ @click.pass_context
33
+ def get_sitemap(ctx: click.Context, site_url: str, feedpath: str) -> None:
34
+ """Show details for a single sitemap FEEDPATH."""
35
+ ctx.obj["site_url"] = site_url
36
+ client = get_client(ctx)
37
+ sitemap = client.get_sitemap(site_url, feedpath)
38
+ click.echo(format_output(asdict(sitemap), fmt=ctx.obj["format"]))
39
+
40
+
41
+ @sitemaps.command("submit")
42
+ @click.argument("site_url")
43
+ @click.argument("feedpath")
44
+ @click.pass_context
45
+ def submit_sitemap(ctx: click.Context, site_url: str, feedpath: str) -> None:
46
+ """Submit FEEDPATH as a sitemap for SITE_URL."""
47
+ ctx.obj["site_url"] = site_url
48
+ client = get_client(ctx, writable=True)
49
+ client.submit_sitemap(site_url, feedpath)
50
+ click.echo(format_output({"submitted": feedpath, "site_url": site_url}, fmt=ctx.obj["format"]))
51
+
52
+
53
+ @sitemaps.command("delete")
54
+ @click.argument("site_url")
55
+ @click.argument("feedpath")
56
+ @click.pass_context
57
+ def delete_sitemap(ctx: click.Context, site_url: str, feedpath: str) -> None:
58
+ """Delete (unsubmit) sitemap FEEDPATH for SITE_URL."""
59
+ ctx.obj["site_url"] = site_url
60
+ client = get_client(ctx, writable=True)
61
+ client.delete_sitemap(site_url, feedpath)
62
+ click.echo(format_output({"deleted": feedpath, "site_url": site_url}, fmt=ctx.obj["format"]))
gsc/cli/sites.py ADDED
@@ -0,0 +1,54 @@
1
+ """``gsc sites`` group and the shared client factory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict
6
+
7
+ import click
8
+
9
+ from ..auth import get_credentials, resolve_profile
10
+ from ..client import GSCClient
11
+ from ..formatters import format_output
12
+
13
+
14
+ def get_client(ctx: click.Context, writable: bool = False) -> GSCClient:
15
+ """Resolve a profile from ``ctx.obj`` and build a :class:`GSCClient`.
16
+
17
+ Honours an explicit ``--profile`` first, then auto-detects from
18
+ ``ctx.obj["site_url"]`` (set by data commands), then falls back to
19
+ ``default``.
20
+ """
21
+ profile_name = ctx.obj.get("profile")
22
+ site_url = ctx.obj.get("site_url")
23
+ profile = resolve_profile(name=profile_name, site_url=site_url)
24
+ if profile is None:
25
+ raise click.ClickException(
26
+ "No matching auth profile. Run 'gsc auth login' or 'gsc auth add-profile' first."
27
+ )
28
+ credentials = get_credentials(profile, writable=writable)
29
+ return GSCClient(credentials)
30
+
31
+
32
+ @click.group()
33
+ def sites() -> None:
34
+ """List and inspect verified Search Console properties."""
35
+
36
+
37
+ @sites.command("list")
38
+ @click.pass_context
39
+ def list_sites(ctx: click.Context) -> None:
40
+ """List all properties you can access."""
41
+ client = get_client(ctx)
42
+ rows = [asdict(site) for site in client.list_sites()]
43
+ click.echo(format_output(rows, fmt=ctx.obj["format"]))
44
+
45
+
46
+ @sites.command("get")
47
+ @click.argument("site_url")
48
+ @click.pass_context
49
+ def get_site(ctx: click.Context, site_url: str) -> None:
50
+ """Show details for a single property."""
51
+ ctx.obj["site_url"] = site_url
52
+ client = get_client(ctx)
53
+ site = client.get_site(site_url)
54
+ click.echo(format_output(asdict(site), fmt=ctx.obj["format"]))
gsc/client.py ADDED
@@ -0,0 +1,90 @@
1
+ """Thin wrapper over the two Google Search Console discovery services."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from googleapiclient.discovery import build
8
+
9
+ from .models import (
10
+ InspectionResult,
11
+ SearchAnalyticsResponse,
12
+ Site,
13
+ Sitemap,
14
+ )
15
+
16
+
17
+ class GSCClient:
18
+ """Wraps ``webmasters`` v3 and ``searchconsole`` v1; methods return models."""
19
+
20
+ def __init__(self, credentials: Any) -> None:
21
+ self.credentials = credentials
22
+ self.webmasters = build("webmasters", "v3", credentials=credentials, cache_discovery=False)
23
+ self.searchconsole = build(
24
+ "searchconsole", "v1", credentials=credentials, cache_discovery=False
25
+ )
26
+
27
+ def list_sites(self) -> list[Site]:
28
+ response = self.webmasters.sites().list().execute()
29
+ return [Site.from_api(entry) for entry in response.get("siteEntry", [])]
30
+
31
+ def get_site(self, site_url: str) -> Site:
32
+ response = self.webmasters.sites().get(siteUrl=site_url).execute()
33
+ return Site.from_api(response)
34
+
35
+ def query(self, site_url: str, body: dict) -> SearchAnalyticsResponse:
36
+ response = self.webmasters.searchanalytics().query(siteUrl=site_url, body=body).execute()
37
+ return SearchAnalyticsResponse.from_api(response)
38
+
39
+ def list_sitemaps(self, site_url: str) -> list[Sitemap]:
40
+ response = self.webmasters.sitemaps().list(siteUrl=site_url).execute()
41
+ return [Sitemap.from_api(entry) for entry in response.get("sitemap", [])]
42
+
43
+ def get_sitemap(self, site_url: str, feedpath: str) -> Sitemap:
44
+ response = self.webmasters.sitemaps().get(siteUrl=site_url, feedpath=feedpath).execute()
45
+ return Sitemap.from_api(response)
46
+
47
+ def submit_sitemap(self, site_url: str, feedpath: str) -> None:
48
+ self.webmasters.sitemaps().submit(siteUrl=site_url, feedpath=feedpath).execute()
49
+
50
+ def delete_sitemap(self, site_url: str, feedpath: str) -> None:
51
+ self.webmasters.sitemaps().delete(siteUrl=site_url, feedpath=feedpath).execute()
52
+
53
+ def inspect_url(self, site_url: str, inspection_url: str) -> InspectionResult:
54
+ body = {"siteUrl": site_url, "inspectionUrl": inspection_url}
55
+ response = self.searchconsole.urlInspection().index().inspect(body=body).execute()
56
+ return InspectionResult.from_api(response)
57
+
58
+ @staticmethod
59
+ def build_query_body(
60
+ start_date: str,
61
+ end_date: str,
62
+ dimensions: list[str] | None = None,
63
+ search_type: str | None = None,
64
+ filters: list[dict] | None = None,
65
+ aggregation_type: str | None = None,
66
+ row_limit: int | None = None,
67
+ start_row: int | None = None,
68
+ data_state: str | None = None,
69
+ ) -> dict:
70
+ """Build a searchanalytics request body, omitting unset optional fields.
71
+
72
+ ``filters`` are wrapped in a single ``dimensionFilterGroups`` entry with
73
+ ``groupType: "and"``.
74
+ """
75
+ body: dict[str, Any] = {"startDate": start_date, "endDate": end_date}
76
+ if dimensions:
77
+ body["dimensions"] = dimensions
78
+ if search_type:
79
+ body["type"] = search_type
80
+ if filters:
81
+ body["dimensionFilterGroups"] = [{"groupType": "and", "filters": filters}]
82
+ if aggregation_type:
83
+ body["aggregationType"] = aggregation_type
84
+ if row_limit is not None:
85
+ body["rowLimit"] = row_limit
86
+ if start_row is not None:
87
+ body["startRow"] = start_row
88
+ if data_state:
89
+ body["dataState"] = data_state
90
+ return body
@@ -0,0 +1,54 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "name": "SEO Search Analytics Benchmarks",
4
+ "version": "1.0.0",
5
+ "updated": "2026-07",
6
+ "description": "Open reference dataset of Google Search Console / organic-search benchmarks: expected click-through rate by ranking position, position bands, and indexing-health thresholds. Maintained alongside gsc-cli.",
7
+ "source": "gsc-cli",
8
+ "homepage": "https://seoconsult.bg",
9
+ "repository": "https://github.com/seoconsultbg/gsc-cli",
10
+ "license": "CC-BY-4.0",
11
+ "attribution": "Data by SEO Consult (https://seoconsult.bg), CC BY 4.0. Attribution required.",
12
+ "ctr_by_position": {
13
+ "unit": "fraction",
14
+ "note": "Expected organic CTR for web results. Values materially below the band for a position indicate a title/meta opportunity.",
15
+ "values": {
16
+ "1": 0.28,
17
+ "2": 0.15,
18
+ "3": 0.11,
19
+ "4": 0.08,
20
+ "5": 0.06,
21
+ "6": 0.045,
22
+ "7": 0.035,
23
+ "8": 0.03,
24
+ "9": 0.025,
25
+ "10": 0.02
26
+ }
27
+ },
28
+ "position_bands": [
29
+ { "min": 1, "max": 3, "label": "top", "action": "Defend; monitor for volatility." },
30
+ { "min": 4, "max": 10, "label": "first_page", "action": "Improve CTR vs. band (title/meta) to lift clicks." },
31
+ { "min": 11, "max": 20, "label": "striking_distance", "action": "Prime quick-win zone: small gains push to page 1." },
32
+ { "min": 21, "max": null, "label": "deep", "action": "Needs content/authority investment or consolidation." }
33
+ ],
34
+ "quick_wins": {
35
+ "striking_distance": "Queries at position 11-20 with high impressions.",
36
+ "low_ctr_page_one": "Queries at position 4-10 with CTR below the expected band."
37
+ },
38
+ "cannibalization": {
39
+ "rule": "One query served by >= 2 URLs, each with meaningful impressions, that split authority and CTR.",
40
+ "min_urls": 2
41
+ },
42
+ "indexing_health": {
43
+ "stale_crawl_days": 30,
44
+ "not_indexed_states": [
45
+ "Crawled - currently not indexed",
46
+ "Discovered - currently not indexed"
47
+ ],
48
+ "note": "A 'not indexed' coverage state on a top page is a priority issue."
49
+ },
50
+ "caveats": {
51
+ "data_lag_days": 3,
52
+ "note": "GSC data is delayed ~2-3 days; always state the analysis window."
53
+ }
54
+ }
gsc/formatters.py ADDED
@@ -0,0 +1,55 @@
1
+ """Render dicts / lists-of-dicts as JSON, a simple table, or CSV."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import io
7
+ import json
8
+ from typing import Any
9
+
10
+ from tabulate import tabulate
11
+
12
+
13
+ def format_output(data: Any, *, fmt: str = "table") -> str:
14
+ """Render ``data`` according to ``fmt`` (``json``, ``table``, or ``csv``).
15
+
16
+ A single dict is coerced to a one-row list for table/CSV rendering. Empty
17
+ input yields ``"No data."`` for tables and ``""`` for CSV.
18
+ """
19
+ if fmt == "json":
20
+ return json.dumps(data, indent=2, default=str)
21
+
22
+ rows = _as_rows(data)
23
+ if fmt == "csv":
24
+ return _format_csv(rows)
25
+ return _format_table(rows)
26
+
27
+
28
+ def _as_rows(data: Any) -> list[dict]:
29
+ if data is None:
30
+ return []
31
+ if isinstance(data, dict):
32
+ return [data]
33
+ return list(data)
34
+
35
+
36
+ def _format_table(rows: list[dict]) -> str:
37
+ if not rows:
38
+ return "No data."
39
+ return tabulate(rows, headers="keys", tablefmt="simple")
40
+
41
+
42
+ def _format_csv(rows: list[dict]) -> str:
43
+ if not rows:
44
+ return ""
45
+ fieldnames: list[str] = []
46
+ for row in rows:
47
+ for key in row:
48
+ if key not in fieldnames:
49
+ fieldnames.append(key)
50
+ buffer = io.StringIO()
51
+ writer = csv.DictWriter(buffer, fieldnames=fieldnames)
52
+ writer.writeheader()
53
+ for row in rows:
54
+ writer.writerow(row)
55
+ return buffer.getvalue().strip("\r\n")