-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli_utils.py
More file actions
172 lines (137 loc) Β· 4.63 KB
/
cli_utils.py
File metadata and controls
172 lines (137 loc) Β· 4.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env python3
"""
CLI utilities and helpers.
Usage:
python cli_utils.py <command> [options]
"""
import sys
from pathlib import Path
try:
import codomyrmex
except ImportError:
project_root = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(project_root / "src"))
import argparse
import shutil
from typing import Union
try:
from typing import Literal
except ImportError:
from typing import Literal
# Bootstrap path only β not needed when package is already installed
try:
from codomyrmex.utils.cli_helpers import (
print_error,
print_info,
print_success,
setup_logging,
)
except ImportError:
sys.path.insert(
0, str(Path(__file__).resolve().parent.parent.parent.parent / "src")
)
from codomyrmex.utils.cli_helpers import (
print_error,
print_info,
print_success,
setup_logging,
)
# ββ Module-level constants ββββββ
_DEFAULT_LIMIT: int = 5
def get_terminal_size() -> tuple[int, int]:
"""Get terminal dimensions."""
size = shutil.get_terminal_size((80, 24))
return size.columns, size.lines
def print_table(
headers: list[str | int | float],
rows: list[list[str | int | float]],
widths: None | list[int] = None,
) -> None:
"""Print formatted table."""
if not widths:
widths = [
max(len(str(r[i])) for r in [headers, *rows]) + 2
for i in range(len(headers))
]
header_row = "".join(h.ljust(w) for h, w in zip(headers, widths, strict=False))
print(header_row)
print("-" * sum(widths))
for row in rows:
print("".join(str(c).ljust(w) for c, w in zip(row, widths, strict=False)))
def print_progress(current: int, total: int, width: int = 40) -> None:
"""Print progress bar."""
pct = current / total if total > 0 else 0
filled = int(width * pct)
bar = "β" * filled + "β" * (width - filled)
print(f"\r[{bar}] {pct:.0%} ({current}/{total})", end="", flush=True)
def colorize(text: str, color: str) -> str:
"""Add ANSI color to text."""
colors: Literal["red", "green", "yellow", "blue", "magenta", "cyan", "reset"] = {
"red": "\033[91m",
"green": "\033[92m",
"yellow": "\033[93m",
"blue": "\033[94m",
"magenta": "\033[95m",
"cyan": "\033[96m",
"reset": "\033[0m",
}
return f"{colors.get(color, '')}{text}{colors['reset']}"
def main() -> int:
# Auto-injected: Load configuration
from pathlib import Path
import yaml
config_path = (
Path(__file__).resolve().parent.parent.parent / "config" / "cli" / "config.yaml"
)
if config_path.exists():
with open(config_path) as f:
yaml.safe_load(f) or {}
print("Loaded config from config/cli/config.yaml")
parser = argparse.ArgumentParser(description="CLI utilities")
subparsers = parser.add_subparsers(dest="command")
# Demo table
subparsers.add_parser("demo-table", help="Demo table output")
# Demo progress
subparsers.add_parser("demo-progress", help="Demo progress bar")
# Demo colors
subparsers.add_parser("demo-colors", help="Demo colors")
# Terminal info
subparsers.add_parser("info", help="Show terminal info")
args = parser.parse_args()
if not args.command:
print("π₯οΈ CLI Utilities\n")
print("Commands:")
print(" info - Show terminal info")
print(" demo-table - Demo table output")
print(" demo-progress - Demo progress bar")
print(" demo-colors - Demo ANSI colors")
return 0
if args.command == "info":
cols, rows = get_terminal_size()
print("π₯οΈ Terminal Info:\n")
print(f" Size: {cols}x{rows}")
print(f" Python: {sys.version.split()[0]}")
print(f" Platform: {sys.platform}")
elif args.command == "demo-table":
headers = ["Name", "Status", "Score"]
rows = [
["Alpha", "Active", 95],
["Beta", "Pending", 82],
["Gamma", "Complete", 100],
]
print("π Table Demo:\n")
print_table(headers, rows)
elif args.command == "demo-progress":
import time
print("π Progress Demo:\n")
for i in range(101):
print_progress(i, 100)
time.sleep(0.02)
print("\n\n Done!")
elif args.command == "demo-colors":
print("π¨ Color Demo:\n")
for color in ["red", "green", "yellow", "blue", "magenta", "cyan"]:
print(f" {colorize(color.capitalize(), color)}")
return 0
if __name__ == "__main__":
sys.exit(main())