-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevvault.py
More file actions
392 lines (333 loc) Β· 15.7 KB
/
devvault.py
File metadata and controls
392 lines (333 loc) Β· 15.7 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#!/usr/bin/env python3
"""
devvault - π οΈ Swiss-army knife CLI for developers
10+ essential tools in one command.
"""
import sys
import json
import base64
import hashlib
import uuid as _uuid
import random
import string
import argparse
import re
from datetime import datetime, timezone
try:
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from rich import print as rprint
HAS_RICH = True
except ImportError:
HAS_RICH = False
console = Console() if HAS_RICH else None
LOREM_WORDS = [
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit",
"sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore",
"magna", "aliqua", "enim", "ad", "minim", "veniam", "quis", "nostrud",
"exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea", "commodo",
"consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate",
"velit", "esse", "cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint",
"occaecat", "cupidatat", "non", "proident", "sunt", "culpa", "qui", "officia",
"deserunt", "mollit", "anim", "id", "est", "laborum", "perspiciatis", "unde",
"omnis", "iste", "natus", "error", "voluptatem", "accusantium", "doloremque",
"laudantium", "totam", "rem", "aperiam", "eaque", "ipsa", "quae", "ab", "illo",
"inventore", "veritatis", "quasi", "architecto", "beatae", "vitae", "dicta",
"explicabo", "nemo", "ipsam", "voluptas", "aspernatur", "aut", "odit",
"fugit", "consequuntur", "magni", "ratione", "sequi", "nesciunt",
]
def _out(text, style=None):
"""Print with optional rich styling, always works in pipes."""
if HAS_RICH and console and console.is_terminal:
if style:
console.print(text, style=style)
else:
console.print(text)
else:
print(str(text) if not isinstance(text, str) else text)
def _read_stdin():
"""Read from stdin if available."""
if not sys.stdin.isatty():
return sys.stdin.read().strip()
return None
# ββ JSON ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_json_format(args):
text = args.text if args.text else _read_stdin()
if not text:
_out("[red]Error: No input. Provide text or pipe stdin.[/red]" if HAS_RICH else "Error: No input.")
sys.exit(1)
try:
data = json.loads(text)
formatted = json.dumps(data, indent=2, ensure_ascii=False)
if HAS_RICH and console and console.is_terminal:
console.print_json(formatted)
else:
print(formatted)
except json.JSONDecodeError as e:
_out(f"[red]Invalid JSON: {e}[/red]" if HAS_RICH else f"Invalid JSON: {e}")
sys.exit(1)
def cmd_json_minify(args):
text = args.text if args.text else _read_stdin()
if not text:
_out("[red]Error: No input.[/red]" if HAS_RICH else "Error: No input.")
sys.exit(1)
try:
data = json.loads(text)
print(json.dumps(data, separators=(",", ":"), ensure_ascii=False))
except json.JSONDecodeError as e:
_out(f"[red]Invalid JSON: {e}[/red]" if HAS_RICH else f"Invalid JSON: {e}")
sys.exit(1)
# ββ Base64 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_base64_encode(args):
text = args.text if args.text else _read_stdin()
if not text:
_out("[red]Error: No input.[/red]" if HAS_RICH else "Error: No input.")
sys.exit(1)
encoded = base64.b64encode(text.encode()).decode()
_out(encoded, style="green" if HAS_RICH else None)
def cmd_base64_decode(args):
text = args.text if args.text else _read_stdin()
if not text:
_out("[red]Error: No input.[/red]" if HAS_RICH else "Error: No input.")
sys.exit(1)
try:
decoded = base64.b64decode(text).decode()
_out(decoded, style="green" if HAS_RICH else None)
except Exception as e:
_out(f"[red]Decode error: {e}[/red]" if HAS_RICH else f"Decode error: {e}")
sys.exit(1)
# ββ Hash ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_hash(args):
text = args.text if args.text else _read_stdin()
if not text:
_out("[red]Error: No input.[/red]" if HAS_RICH else "Error: No input.")
sys.exit(1)
if HAS_RICH and console and console.is_terminal:
table = Table(title=f"Hashes for: {text[:50]}")
table.add_column("Algorithm", style="cyan", bold=True)
table.add_column("Hash", style="green")
for algo, func in [("MD5", hashlib.md5), ("SHA1", hashlib.sha1), ("SHA256", hashlib.sha256)]:
table.add_row(algo, func(text.encode()).hexdigest())
console.print(table)
else:
print(f"MD5: {hashlib.md5(text.encode()).hexdigest()}")
print(f"SHA1: {hashlib.sha1(text.encode()).hexdigest()}")
print(f"SHA256: {hashlib.sha256(text.encode()).hexdigest()}")
# ββ UUID ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_uuid(args):
count = args.count or 1
for _ in range(count):
_out(str(_uuid.uuid4()), style="green" if HAS_RICH else None)
# ββ Timestamp βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_timestamp(args):
if args.value:
try:
ts = float(args.value)
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
_out(f"UTC: {dt.strftime('%Y-%m-%d %H:%M:%S')}", style="cyan" if HAS_RICH else None)
local = dt.astimezone()
_out(f"Local: {local.strftime('%Y-%m-%d %H:%M:%S %Z')}", style="green" if HAS_RICH else None)
except (ValueError, OSError):
_out(f"[red]Invalid timestamp: {args.value}[/red]" if HAS_RICH else f"Invalid timestamp: {args.value}")
sys.exit(1)
else:
now = datetime.now(timezone.utc)
_out(str(int(now.timestamp())), style="green" if HAS_RICH else None)
# ββ Lorem βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_lorem(args):
count = args.count or 5
words = []
for _ in range(count):
words.append(random.choice(LOREM_WORDS))
if words:
words[0] = words[0].capitalize()
text = " ".join(words) + "."
_out(text, style="white" if HAS_RICH else None)
# ββ Color βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_color(args):
hex_color = args.hex_color.lstrip("#")
if not re.match(r"^[0-9a-fA-F]{6}$", hex_color):
_out("[red]Invalid hex color. Use format: #RRGGBB[/red]" if HAS_RICH else "Invalid hex color.")
sys.exit(1)
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
# Convert to HSL
r_, g_, b_ = r / 255, g / 255, b / 255
mx, mn = max(r_, g_, b_), min(r_, g_, b_)
l = (mx + mn) / 2
if mx == mn:
h = s = 0
else:
d = mx - mn
s = d / (2 - mx - mn) if l > 0.5 else d / (mx + mn)
if mx == r_:
h = (g_ - b_) / d + (6 if g_ < b_ else 0)
elif mx == g_:
h = (b_ - r_) / d + 2
else:
h = (r_ - g_) / d + 4
h /= 6
if HAS_RICH and console and console.is_terminal:
table = Table(title=f"Color #{hex_color.upper()}")
table.add_column("Format", style="cyan", bold=True)
table.add_column("Value", style="green")
table.add_row("HEX", f"#{hex_color.upper()}")
table.add_row("RGB", f"rgb({r}, {g}, {b})")
table.add_row("HSL", f"hsl({int(h*360)}, {int(s*100)}%, {int(l*100)}%)")
console.print(table)
# Show a color swatch
console.print(Panel("ββββββββββββββββ", style=f"rgb({r},{g},{b}) on rgb({r},{g},{b})"))
else:
print(f"HEX: #{hex_color.upper()}")
print(f"RGB: rgb({r}, {g}, {b})")
print(f"HSL: hsl({int(h*360)}, {int(s*100)}%, {int(l*100)}%)")
# ββ QR ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_qr(args):
text = args.text if args.text else _read_stdin()
if not text:
_out("[red]Error: No input.[/red]" if HAS_RICH else "Error: No input.")
sys.exit(1)
output = args.output or None
try:
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=10,
border=2,
)
qr.add_data(text)
qr.make(fit=True)
if output:
img = qr.make_image(fill_color="black", back_color="white")
img.save(output)
_out(f"[green]QR code saved to {output}[/green]" if HAS_RICH else f"QR code saved to {output}")
else:
if HAS_RICH and console and console.is_terminal:
qr.print_ascii(invert=True)
else:
qr.print_ascii(invert=True)
except ImportError:
_out("[red]qrcode library not installed. Run: pip install qrcode[pil][/red]" if HAS_RICH else "qrcode library not installed.")
sys.exit(1)
# ββ Password ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def cmd_password(args):
length = args.length or 16
charset = string.ascii_letters + string.digits
if args.no_symbols is False:
charset += string.punctuation
# Ensure at least one of each type
pwd = [
random.choice(string.ascii_lowercase),
random.choice(string.ascii_uppercase),
random.choice(string.digits),
]
if args.no_symbols is False:
pwd.append(random.choice(string.punctuation))
remaining = length - len(pwd)
pwd.extend(random.choice(charset) for _ in range(remaining))
random.shuffle(pwd)
password = "".join(pwd)
_out(password, style="green" if HAS_RICH else None)
# ββ CLI Setup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_parser():
parser = argparse.ArgumentParser(
prog="dv",
description="π οΈ devvault - Swiss-army knife CLI for developers",
)
subparsers = parser.add_subparsers(dest="command", help="Available tools")
# json
json_parser = subparsers.add_parser("json", help="JSON tools")
json_sub = json_parser.add_subparsers(dest="subcommand", help="JSON subcommands")
jf = json_sub.add_parser("format", help="Format/beautify JSON")
jf.add_argument("text", nargs="?", help="JSON string (or pipe)")
jm = json_sub.add_parser("minify", help="Minify JSON")
jm.add_argument("text", nargs="?", help="JSON string (or pipe)")
# base64
b64_parser = subparsers.add_parser("base64", help="Base64 encode/decode")
b64_sub = b64_parser.add_subparsers(dest="subcommand", help="Base64 subcommands")
be = b64_sub.add_parser("encode", help="Encode to base64")
be.add_argument("text", nargs="?", help="Text to encode (or pipe)")
bd = b64_sub.add_parser("decode", help="Decode from base64")
bd.add_argument("text", nargs="?", help="Base64 string (or pipe)")
# hash
hash_parser = subparsers.add_parser("hash", help="Generate MD5, SHA1, SHA256 hashes")
hash_parser.add_argument("text", nargs="?", help="Text to hash (or pipe)")
# uuid
uuid_parser = subparsers.add_parser("uuid", help="Generate UUID v4")
uuid_parser.add_argument("-n", "--count", type=int, default=1, help="Number of UUIDs")
# timestamp
ts_parser = subparsers.add_parser("timestamp", help="Unix timestamp tools")
ts_parser.add_argument("value", nargs="?", help="Timestamp to convert (default: now)")
# lorem
lorem_parser = subparsers.add_parser("lorem", help="Generate lorem ipsum")
lorem_parser.add_argument("count", nargs="?", type=int, default=5, help="Number of words")
# color
color_parser = subparsers.add_parser("color", help="Convert hex color to RGB/HSL")
color_parser.add_argument("hex_color", help="Hex color (e.g. #FF5733)")
# qr
qr_parser = subparsers.add_parser("qr", help="Generate QR code")
qr_parser.add_argument("text", nargs="?", help="Text/data to encode (or pipe)")
qr_parser.add_argument("-o", "--output", help="Save to file (PNG)")
# password
pw_parser = subparsers.add_parser("password", help="Generate secure password")
pw_parser.add_argument("-l", "--length", type=int, default=16, help="Password length")
pw_parser.add_argument("--no-symbols", action="store_true", default=False, help="Exclude symbols")
return parser
def main():
parser = build_parser()
args = parser.parse_args()
if not args.command:
if HAS_RICH and console and console.is_terminal:
console.print(Panel(
"[bold cyan]π οΈ devvault[/bold cyan] - Swiss-army knife CLI for developers\n\n"
"[bold]Available tools:[/bold]\n"
" [green]dv json format[/green] - Format/beautify JSON\n"
" [green]dv json minify[/green] - Minify JSON\n"
" [green]dv base64 encode[/green] - Encode to base64\n"
" [green]dv base64 decode[/green] - Decode from base64\n"
" [green]dv hash <text>[/green] - MD5, SHA1, SHA256 hashes\n"
" [green]dv uuid[/green] - Generate UUID v4\n"
" [green]dv timestamp[/green] - Unix timestamp tools\n"
" [green]dv lorem[/green] - Lorem ipsum generator\n"
" [green]dv color <hex>[/green] - Color converter\n"
" [green]dv qr <text>[/green] - QR code generator\n"
" [green]dv password[/green] - Secure password generator\n\n"
"[dim]Use dv <tool> --help for more info.[/dim]",
title="devvault v1.0.0",
border_style="bright_blue",
))
else:
print("π οΈ devvault - Swiss-army knife CLI for developers")
print("Use: dv <tool> --help")
return
dispatch = {
("json", "format"): cmd_json_format,
("json", "minify"): cmd_json_minify,
("base64", "encode"): cmd_base64_encode,
("base64", "decode"): cmd_base64_decode,
}
key = (args.command, getattr(args, "subcommand", None))
if key in dispatch:
dispatch[key](args)
elif args.command == "hash":
cmd_hash(args)
elif args.command == "uuid":
cmd_uuid(args)
elif args.command == "timestamp":
cmd_timestamp(args)
elif args.command == "lorem":
cmd_lorem(args)
elif args.command == "color":
cmd_color(args)
elif args.command == "qr":
cmd_qr(args)
elif args.command == "password":
cmd_password(args)
else:
parser.print_help()
if __name__ == "__main__":
main()