aibi-toolkit 1.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.
aibi_toolkit/lint.py ADDED
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from .metadata import Model
4
+
5
+ """Static checks for DAX expressions and measure definitions."""
6
+
7
+ import re
8
+
9
+ BAD_FUNCTIONS = {
10
+ "ALLSELECTED()": "no-argument ALLSELECTED is ambiguous in visuals",
11
+ "CALCULATE([])": "empty CALCULATE filter",
12
+ }
13
+
14
+ def lint_dax(expression: str) -> list[str]:
15
+ """Return lint findings for a single DAX expression."""
16
+ findings = []
17
+ if "/" in expression and re.search(r"(?i)\bDIVIDE\s*\(", expression) is None:
18
+ findings.append("use DIVIDE instead of / to guard divide-by-zero")
19
+ for token, reason in BAD_FUNCTIONS.items():
20
+ if token in expression:
21
+ findings.append(reason)
22
+ if re.search(r"(?i)\bIFERROR\b", expression):
23
+ findings.append("IFERROR hides real errors; handle specific cases")
24
+ return findings
25
+
26
+ def lint_model(model: Model) -> dict[str, list[str]]:
27
+ """Lint every measure in the model, grouped by measure name."""
28
+ from .metadata import list_measures
29
+ out: dict[str, list[str]] = {}
30
+ for m in list_measures(model):
31
+ findings = lint_dax(m.get("expression", ""))
32
+ if findings:
33
+ out[m["name"]] = findings
34
+ return out
@@ -0,0 +1,131 @@
1
+ from __future__ import annotations
2
+
3
+ """Format-string helpers for DAX measures."""
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ CURRENCY_SYMBOLS = {"USD": "$", "EUR": "€", "GBP": "£", "INR": "₹"}
9
+
10
+
11
+ def currency_format(code: str, decimals: int = 2) -> str:
12
+ """Build a currency format string, e.g. $#,0.00."""
13
+ symbol = CURRENCY_SYMBOLS.get(code.upper(), code)
14
+ return f"{symbol}#,0.{('0' * decimals) if decimals else ''}".rstrip(".")
15
+
16
+
17
+ def percent_format(decimals: int = 1) -> str:
18
+ """Build a percentage format string, e.g. 0.0%."""
19
+ return f"0.{('0' * decimals) if decimals else ''}%"
20
+
21
+
22
+ def thousands_format(decimals: int = 0) -> str:
23
+ """Build a thousands-separated format string, e.g. #,0.00."""
24
+ return f"#,0.{('0' * decimals) if decimals else ''}".rstrip(".")
25
+
26
+
27
+ def detect_format(sample_value: float | bool) -> str:
28
+ """Guess a format string from a sample numeric value."""
29
+ if isinstance(sample_value, bool):
30
+ return "TRUE/FALSE"
31
+ if isinstance(sample_value, int):
32
+ return "#,0"
33
+ if isinstance(sample_value, float):
34
+ if abs(sample_value) < 10:
35
+ return percent_format(1)
36
+ return "#,0.00"
37
+ raise TypeError(f"Unsupported sample type: {type(sample_value)!r}")
38
+
39
+
40
+ DATE_FORMATS = {"short": "dd/MM/yyyy", "iso": "yyyy-MM-dd", "long": "d MMMM yyyy"}
41
+
42
+
43
+ def date_format(style: str = "short") -> str:
44
+ """Look up a date format string by style name."""
45
+ return DATE_FORMATS[style]
46
+
47
+
48
+ def format_report(model: dict[str, Any], path: str | Path) -> None:
49
+ """Apply detected formats to every numeric measure and write a report."""
50
+ import csv as _csv
51
+ with Path(path).open("w", newline="", encoding="utf-8") as f:
52
+ w = _csv.writer(f)
53
+ w.writerow(["table", "name", "suggested_format"])
54
+ for t in model.get("tables", []):
55
+ for m in t.get("measures", []):
56
+ if m.get("expression", "").startswith("SUM"):
57
+ w.writerow([t["name"], m["name"], "#,0.00"])
58
+
59
+
60
+ def merge_formats(*maps: dict[str, str]) -> dict[str, str]:
61
+ """Merge format maps, later maps winning on conflicts."""
62
+ out: dict[str, str] = {}
63
+ for m in maps:
64
+ out.update(m)
65
+ return out
66
+
67
+
68
+ def smart_format(value: float, currency: str = "USD") -> str:
69
+ """Pick currency vs plain format based on value magnitude."""
70
+ if value >= 1000:
71
+ return currency_format(currency)
72
+ if value < 1:
73
+ return percent_format(2)
74
+ return thousands_format(2)
75
+
76
+
77
+ FORMAT_ALIASES = {
78
+ "money": "$#,0.00",
79
+ "pct": "0.0%",
80
+ "count": "#,0",
81
+ "seconds": "#,0.0 s",
82
+ }
83
+
84
+
85
+ def resolve_format(key: str) -> str:
86
+ """Resolve a friendly alias to a full format string."""
87
+ try:
88
+ return FORMAT_ALIASES[key]
89
+ except KeyError:
90
+ raise ValueError(f"Unknown format alias: {key!r}") from None
91
+
92
+
93
+ SHORT_SCALE = [("", 1), ("K", 1_000), ("M", 1_000_000), ("B", 1_000_000_000)]
94
+
95
+
96
+ def human_readable(value: float) -> str:
97
+ """Render a number like 1.2M / 340K for CLI and docs output."""
98
+ for suffix, scale in reversed(SHORT_SCALE):
99
+ if abs(value) >= scale > 1:
100
+ return f"{value / scale:.1f}{suffix}"
101
+ if scale == 1:
102
+ return f"{value:,.0f}"
103
+ return str(value)
104
+
105
+
106
+ def format_key_from_format(fmt: str) -> str:
107
+ """Map a format string to a stable category key for grouping."""
108
+ if fmt.endswith("%"):
109
+ return "percent"
110
+ if fmt.count(",") and "$" in fmt:
111
+ return "currency"
112
+ return "number"
113
+
114
+
115
+ def validate_format(fmt: str) -> list[str]:
116
+ """Check a custom format string for common mistakes."""
117
+ issues: list[str] = []
118
+ if fmt.count("{") != fmt.count("}"):
119
+ issues.append("unbalanced braces")
120
+ if "%" in fmt and "$" in fmt:
121
+ issues.append("mixes percent and currency tokens")
122
+ if fmt and fmt[0].isdigit():
123
+ issues.append("should not start with a digit")
124
+ return issues
125
+
126
+
127
+ def scale_number(value: float) -> float:
128
+ """Clamp extreme display values into a readable band."""
129
+ if abs(value) >= 1e12:
130
+ return round(value / 1e12, 2) * 1e12
131
+ return round(value, 2)
@@ -0,0 +1,92 @@
1
+ """Load and inspect semantic-model metadata dumps (TMDL-exported JSON)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ Model = dict[str, Any]
10
+ Measure = dict[str, Any]
11
+ Table = dict[str, Any]
12
+
13
+
14
+ def load_model(path: str) -> Model:
15
+ """Load a model JSON dump from disk."""
16
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
17
+ if not isinstance(data, dict):
18
+ raise TypeError("model dump must be a JSON object")
19
+ return data
20
+
21
+
22
+ def list_tables(model: Model) -> list[str]:
23
+ """Return all table names in the model."""
24
+ return [t["name"] for t in model.get("tables", [])]
25
+
26
+
27
+ def list_measures(model: Model, table: str | None = None) -> list[Measure]:
28
+ """List measures, optionally filtered to one table."""
29
+ out: list[Measure] = []
30
+ for t in model.get("tables", []):
31
+ if table and t["name"] != table:
32
+ continue
33
+ for m in t.get("measures", []):
34
+ out.append({**m, "table": t["name"]})
35
+ return out
36
+
37
+
38
+ def model_summary(model: Model) -> dict[str, int]:
39
+ """High-level counts for a quick model health glance."""
40
+ tables = model.get("tables", [])
41
+ return {
42
+ "tables": len(tables),
43
+ "measures": sum(len(t.get("measures", [])) for t in tables),
44
+ "columns": sum(len(t.get("columns", [])) for t in tables),
45
+ }
46
+
47
+
48
+ def find_unused_measures(model: Model) -> list[str]:
49
+ """Best-effort scan for measures with no format string set."""
50
+ return [
51
+ m["name"]
52
+ for t in model.get("tables", [])
53
+ for m in t.get("measures", [])
54
+ if not m.get("formatString")
55
+ ]
56
+
57
+
58
+ def count_standalone_measures(model: Model) -> int:
59
+ """Measures that live on tables with no columns (helper/measure tables)."""
60
+ return sum(
61
+ len(t.get("measures", []))
62
+ for t in model.get("tables", [])
63
+ if not t.get("columns")
64
+ )
65
+
66
+
67
+ def relationships(model: Model) -> list[dict[str, Any]]:
68
+ """List model relationships in a readable form."""
69
+ return [
70
+ {"from": r.get("fromTable"), "to": r.get("toTable"), "active": r.get("isActive", True)}
71
+ for r in model.get("relationships", [])
72
+ ]
73
+
74
+
75
+ def hidden_objects(model: Model) -> list[str]:
76
+ """List objects marked hidden in the model."""
77
+ out: list[str] = []
78
+ for t in model.get("tables", []):
79
+ if t.get("isHidden"):
80
+ out.append(f"table:{t['name']}")
81
+ out.extend(f"column:{c['name']}" for c in t.get("columns", []) if c.get("isHidden"))
82
+ return out
83
+
84
+
85
+ def calculated_columns(model: Model) -> list[dict[str, Any]]:
86
+ """List calculated columns with their expressions."""
87
+ return [
88
+ {"table": t["name"], "name": c["name"], "expression": c.get("expression", "")}
89
+ for t in model.get("tables", [])
90
+ for c in t.get("columns", [])
91
+ if c.get("type") == "calculated"
92
+ ]
aibi_toolkit/naming.py ADDED
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ """Name normalization helpers for tables, columns and measures."""
4
+
5
+ import re
6
+
7
+
8
+ def to_snake_case(name: str) -> str:
9
+ """Convert a human-readable name to snake_case."""
10
+ name = re.sub(r"[^\w\s]", " ", name)
11
+ name = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name)
12
+ return re.sub(r"\s+", "_", name.strip()).lower()
13
+
14
+
15
+ def to_display_name(name: str) -> str:
16
+ """Convert snake_case or camelCase to a Title Case display name."""
17
+ name = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name)
18
+ name = name.replace("_", " ").strip()
19
+ return " ".join(w.capitalize() for w in name.split())
20
+
21
+
22
+ ABBREVIATIONS = {
23
+ "qty": "quantity",
24
+ "amt": "amount",
25
+ "cust": "customer",
26
+ "rev": "revenue",
27
+ "ytd": "year to date",
28
+ }
29
+
30
+
31
+ def expand_abbreviations(name: str, mapping: dict[str, str] | None = None) -> str:
32
+ """Expand common BI abbreviations to their full words."""
33
+ mapping = mapping or ABBREVIATIONS
34
+ words = name.replace("_", " ").split()
35
+ return " ".join(mapping.get(w.lower(), w) for w in words)
36
+
37
+
38
+ def sanitize_table_name(name: str) -> str:
39
+ """Remove characters that break Power BI / SQL identifiers."""
40
+ name = re.sub(r"[^\w\s()-]", "", name)
41
+ return re.sub(r"\s+", " ", name).strip()
42
+
43
+
44
+ MEASURE_PREFIXES = {
45
+ "count": "Count of",
46
+ "sum": "Total",
47
+ "avg": "Average",
48
+ "ratio": "%",
49
+ }
50
+
51
+
52
+ def suggest_measure_prefix(aggregation: str) -> str:
53
+ """Suggest a display prefix for a measure based on its aggregation."""
54
+ return MEASURE_PREFIXES.get(aggregation.lower(), aggregation.capitalize() + " of")
55
+
56
+
57
+ def dedupe_names(names: list[str]) -> list[str]:
58
+ """Ensure unique names by appending 2, 3, ... on conflicts."""
59
+ seen, out = set(), []
60
+ for n in names:
61
+ base, i = n, 1
62
+ while n.lower() in seen:
63
+ i += 1
64
+ n = f"{base} {i}"
65
+ seen.add(n.lower())
66
+ out.append(n)
67
+ return out
68
+
69
+
70
+ def truncate_name(name: str, limit: int = 64) -> str:
71
+ """Truncate a name to a character limit without trailing spaces."""
72
+ return name[:limit].rstrip()
73
+
74
+
75
+ def normalize_all(names: list[str]) -> list[str]:
76
+ """snake_case, de-abbreviate, then dedupe in one pass."""
77
+ cleaned = [expand_abbreviations(to_snake_case(n)) for n in names]
78
+ return dedupe_names(cleaned)
79
+
80
+
81
+ def pascal_case(name: str) -> str:
82
+ """Convert any name style to PascalCase."""
83
+ words = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name).replace("_", " ").split()
84
+ return "".join(w.capitalize() for w in words)
85
+
86
+
87
+ def validate_name(name: str) -> list[str]:
88
+ """Return a list of naming-violation messages (empty = clean)."""
89
+ issues = []
90
+ if name != name.strip():
91
+ issues.append("leading/trailing whitespace")
92
+ if " " in name or "__" in name:
93
+ issues.append("repeated separators")
94
+ if len(name) > 64:
95
+ issues.append("longer than 64 chars")
96
+ return issues
97
+
98
+
99
+ def kebab_case(name: str) -> str:
100
+ """Convert any name style to kebab-case."""
101
+ words = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name).replace("_", " ").split()
102
+ return "-".join(w.lower() for w in words)
103
+
104
+
105
+ def strip_numbers(name: str) -> str:
106
+ """Remove numeric suffixes such as 'Table 2' -> 'Table'."""
107
+ return re.sub(r"\s+\d+$", "", name).strip()
108
+
109
+
110
+ VOWELS = "aeiouAEIOU"
111
+
112
+
113
+ def a_or_an(word: str) -> str:
114
+ """Return the correct article for a word."""
115
+ return "an" if word and word[0] in VOWELS else "a"
116
+
117
+
118
+ def pluralize(word: str) -> str:
119
+ """Naive pluralization for table names."""
120
+ if word.endswith(("s", "x", "ch", "sh")):
121
+ return word + "es"
122
+ if word.endswith("y") and len(word) > 1 and word[-2] not in VOWELS:
123
+ return word[:-1] + "ies"
124
+ return word + "s"
125
+
126
+
127
+ def split_words(name: str) -> list[str]:
128
+ """Split any naming style into words without separators."""
129
+ spaced = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name)
130
+ spaced = re.sub(r"[(){}\[\]]", " ", spaced)
131
+ return [w for w in spaced.replace("_", " ").replace("-", " ").split() if w]
132
+
133
+
134
+ def initials(name: str) -> str:
135
+ """Abbreviate a name to initials, e.g. 'Total Sales' -> 'TS'."""
136
+ return "".join(w[0].upper() for w in split_words(name))
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from .metadata import Model
6
+
7
+ """Profile a model's expression complexity and weight."""
8
+
9
+ EXPRESSION_WEIGHTS = {
10
+ None: 0,
11
+ "": 0,
12
+ }
13
+
14
+
15
+ def expression_weight(expression: str) -> int:
16
+ """Rough complexity score for a DAX expression."""
17
+ if not expression:
18
+ return 0
19
+ weight = 1
20
+ lowered = expression.lower()
21
+ weight += lowered.count("calculate(")
22
+ weight += lowered.count("filter(")
23
+ weight += lowered.count("var ")
24
+ weight += lowered.count("return")
25
+ return weight
26
+
27
+
28
+ def profile_model(model: Model) -> dict[str, Any]:
29
+ """Aggregate complexity stats across all measures."""
30
+ from .metadata import list_measures
31
+ measures = list_measures(model)
32
+ weights = sorted(expression_weight(m.get("expression", "")) for m in measures)
33
+ if not weights:
34
+ return {"count": 0, "max": 0, "avg": 0, "heavy": []}
35
+ avg = round(sum(weights) / len(weights), 1)
36
+ heavy = [
37
+ m["name"] for m in measures
38
+ if expression_weight(m.get("expression", "")) >= 5
39
+ ]
40
+ return {"count": len(weights), "max": weights[-1], "avg": avg, "heavy": heavy}
41
+
42
+
43
+ def heavy_meaning_change(model: Model) -> dict[str, Any]:
44
+ """Profile with a stricter 'heavy' threshold for reports."""
45
+ from .metadata import list_measures
46
+ measures = list_measures(model)
47
+ heavy = [
48
+ {"name": m["name"], "weight": expression_weight(m.get("expression", ""))}
49
+ for m in measures
50
+ ]
51
+ heavy.sort(key=lambda x: -x["weight"])
52
+ return {"top5": heavy[:5], "worst": heavy[0]["weight"] if heavy else 0}
53
+
54
+
55
+ def weight_tier(weight: int) -> str:
56
+ """Classify a weight into light/medium/heavy for display."""
57
+ if weight <= 2:
58
+ return "light"
59
+ if weight <= 5:
60
+ return "medium"
61
+ return "heavy"
aibi_toolkit/py.typed ADDED
File without changes
aibi_toolkit/report.py ADDED
@@ -0,0 +1,79 @@
1
+ """Generate a markdown audit report for a semantic model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from .audit import audit_measures, audit_score, audit_tables
8
+ from .integrity import check_cardinality, check_relationships, orphan_tables
9
+ from .metadata import Model
10
+ from .tables import markdown_table
11
+
12
+
13
+ def generate_report(model: Model, title: str = "Model Audit Report") -> str:
14
+ """Build a full markdown report string."""
15
+ sections = [f"# {title}", ""]
16
+ sections += _overview(model)
17
+ sections += _measure_findings(model)
18
+ sections += _table_findings(model)
19
+ sections += _relationship_findings(model)
20
+ return "\n".join(sections)
21
+
22
+
23
+ def _overview(model: Model) -> list[str]:
24
+ from .metadata import model_summary
25
+ s = model_summary(model)
26
+ return [
27
+ "## Overview",
28
+ "",
29
+ f"Score: **{audit_score(model)}/100**",
30
+ "",
31
+ f"- Tables: {s['tables']}",
32
+ f"- Measures: {s['measures']}",
33
+ f"- Columns: {s['columns']}",
34
+ "",
35
+ ]
36
+
37
+
38
+ def _measure_findings(model: Model) -> list[str]:
39
+ f = audit_measures(model)
40
+ rows: list[dict[str, object]] = [
41
+ {"category": k, "count": len(v), "examples": ", ".join(v[:3])} for k, v in f.items() if v
42
+ ]
43
+ out = ["## Measure findings", ""]
44
+ out += markdown_table(rows, columns=["category", "count", "examples"]).splitlines() if rows else ["No measure findings."]
45
+ return out + [""]
46
+
47
+
48
+ def _table_findings(model: Model) -> list[str]:
49
+ f = audit_tables(model)
50
+ orphans = orphan_tables(model)
51
+ out: list[str] = ["## Table findings", ""]
52
+ if f["empty"]:
53
+ out += [f"- Empty tables ({len(f['empty'])}): {', '.join(f['empty'][:5])}"]
54
+ if f["bad_names"]:
55
+ out += [f"- Bad table names: {', '.join(f['bad_names'][:5])}"]
56
+ if orphans:
57
+ out += [f"- Orphan tables: {', '.join(orphans[:5])}"]
58
+ if not out[2:]:
59
+ out += ["No table findings."]
60
+ return out + [""]
61
+
62
+
63
+ def _relationship_findings(model: Model) -> list[str]:
64
+ r = check_relationships(model)
65
+ missing = check_cardinality(model)
66
+ out: list[str] = [
67
+ "## Relationship findings",
68
+ "",
69
+ f"- Inactive relationships: {len(r['inactive'])}",
70
+ f"- Bidirectional filters: {len(r['bidirectional'])}",
71
+ f"- Missing cardinality: {len(missing)}",
72
+ "",
73
+ ]
74
+ return out
75
+
76
+
77
+ def write_report(model: Model, path: str | Path, title: str = "Model Audit Report") -> None:
78
+ """Generate and write the report to a markdown file."""
79
+ Path(path).write_text(generate_report(model, title), encoding="utf-8")
aibi_toolkit/sample.py ADDED
@@ -0,0 +1,54 @@
1
+ """Build small demo models for tests, docs and screenshots."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from .metadata import Model
10
+
11
+
12
+ def sample_model(tables: int = 3, measures_per_table: int = 2, seed: int = 42) -> Model:
13
+ """Deterministically generate a fake model for demos."""
14
+ rng = random.Random(seed)
15
+ dims = ["Customer", "Product", "Date"][: max(0, tables - 1)]
16
+ tables_list: list[dict[str, Any]] = []
17
+ for name in ["Sales", *dims][:tables]:
18
+ t: dict[str, Any] = {
19
+ "name": name,
20
+ "columns": [{"name": f"{name[:3].lower()}_id"}],
21
+ "measures": [],
22
+ }
23
+ for i in range(measures_per_table):
24
+ m: dict[str, Any] = {"name": f"Measure {i + 1}"}
25
+ if rng.random() < 0.5:
26
+ m["formatString"] = "#,0.00"
27
+ t["measures"].append(m)
28
+ tables_list.append(t)
29
+ relationships = [
30
+ {
31
+ "fromTable": "Sales",
32
+ "toTable": tables_list[i]["name"],
33
+ "isActive": True,
34
+ "cardinality": "manyToOne",
35
+ }
36
+ for i in range(1, len(tables_list))
37
+ ]
38
+ return {"tables": tables_list, "relationships": relationships}
39
+
40
+
41
+ def sample_csv(path: str | Path, rows: int = 20, seed: int = 42) -> int:
42
+ """Write a demo measures CSV; returns row count."""
43
+ from .csvio import export_measures
44
+ rng = random.Random(seed)
45
+ rows_data = [
46
+ {
47
+ "table": rng.choice(["Sales", "Customer", "Product"]),
48
+ "name": f"Measure {n}",
49
+ "expression": "SUM()",
50
+ "formatString": "" if n % 3 else "#,0",
51
+ }
52
+ for n in range(1, rows + 1)
53
+ ]
54
+ return export_measures(rows_data, path)
aibi_toolkit/tables.py ADDED
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ """Plain-text table rendering for CLI output."""
6
+
7
+
8
+ def markdown_table(rows: list[dict[str, Any]], columns: list[str] | None = None) -> str:
9
+ """Render rows as a GitHub-flavored markdown table."""
10
+ if not rows:
11
+ return ""
12
+ columns = columns or list(rows[0].keys())
13
+ widths = [max(len(str(c)), *(len(str(r.get(c, ""))) for r in rows)) for c in columns]
14
+ header = "| " + " | ".join(c.ljust(w) for c, w in zip(columns, widths)) + " |"
15
+ sep = "| " + " | ".join("-" * w for w in widths) + " |"
16
+ body = [
17
+ "| " + " | ".join(str(r.get(c, "")).ljust(w) for c, w in zip(columns, widths)) + " |"
18
+ for r in rows
19
+ ]
20
+ return "\n".join([header, sep, *body])
21
+
22
+
23
+ def align_column(rows: list[dict[str, Any]], column: str, right: bool = False) -> list[dict[str, Any]]:
24
+ """Pad a column's values for aligned plain-text output."""
25
+ width = max((len(str(r.get(column, ""))) for r in rows), default=0)
26
+ return [
27
+ {**r, column: str(r.get(column, "")).rjust(width) if right else str(r.get(column, "")).ljust(width)}
28
+ for r in rows
29
+ ]
30
+
31
+
32
+ def plain_table(rows: list[dict[str, Any]], columns: list[str] | None = None) -> str:
33
+ """Render rows as a bordered plain-text table for terminals."""
34
+ if not rows:
35
+ return ""
36
+ columns = columns or list(rows[0].keys())
37
+ widths = [max(len(str(c)), *(len(str(r.get(c, ""))) for r in rows)) for c in columns]
38
+ header = " ".join(str(c).ljust(w) for c, w in zip(columns, widths))
39
+ sep = "-" * len(header)
40
+ lines = [header, sep]
41
+ for r in rows:
42
+ lines.append(" ".join(str(r.get(c, "")).ljust(w) for c, w in zip(columns, widths)))
43
+ return "\n".join(lines)