-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevutils.py
More file actions
268 lines (237 loc) · 10.1 KB
/
devutils.py
File metadata and controls
268 lines (237 loc) · 10.1 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
#!/usr/bin/env python3
"""
devutils — Developer string & data utility toolkit.
Stop Googling "base64 encode" and "epoch to date". One CLI, zero deps,
no pasting secrets into sketchy websites.
Usage:
py devutils.py b64e "hello world" # Base64 encode
py devutils.py b64d "aGVsbG8gd29ybGQ=" # Base64 decode
py devutils.py urle "hello world&foo=bar" # URL encode
py devutils.py urld "hello%20world" # URL decode
py devutils.py uuid # Generate UUID v4
py devutils.py uuid 5 # Generate 5 UUIDs
py devutils.py md5 "hello" # MD5 hash
py devutils.py sha256 "hello" # SHA-256 hash
py devutils.py jwt "eyJhbG..." # Decode JWT (no verification)
py devutils.py epoch # Current epoch timestamp
py devutils.py epoch 1712345678 # Epoch to human date
py devutils.py epoch "2026-04-10 12:00:00" # Date to epoch
py devutils.py rand 32 # Random 32-char string
py devutils.py rand 16 --hex # Random hex string
py devutils.py rand 20 --password # Random password
py devutils.py snake "myVariableName" # camelCase -> snake_case
py devutils.py camel "my_variable_name" # snake_case -> camelCase
py devutils.py kebab "my_variable_name" # -> kebab-case
py devutils.py count "some text here" # Word/char/line count
py devutils.py json '{"a":1,"b":[2,3]}' # Pretty-print JSON
py devutils.py lorem 3 # Generate 3 lorem ipsum paragraphs
"""
import argparse
import base64
import hashlib
import json
import os
import random
import re
import secrets
import string
import sys
import time
import uuid
from datetime import datetime, timezone
from urllib.parse import quote, unquote
def cmd_b64e(text):
"""Base64 encode."""
print(base64.b64encode(text.encode()).decode())
def cmd_b64d(text):
"""Base64 decode."""
# Handle URL-safe base64 and padding
text = text.replace("-", "+").replace("_", "/")
padding = 4 - len(text) % 4
if padding != 4:
text += "=" * padding
print(base64.b64decode(text).decode())
def cmd_urle(text):
"""URL encode."""
print(quote(text, safe=""))
def cmd_urld(text):
"""URL decode."""
print(unquote(text))
def cmd_uuid(count=1):
"""Generate UUID(s)."""
for _ in range(count):
print(str(uuid.uuid4()))
def cmd_md5(text):
"""MD5 hash."""
print(hashlib.md5(text.encode()).hexdigest())
def cmd_sha256(text):
"""SHA-256 hash."""
print(hashlib.sha256(text.encode()).hexdigest())
def cmd_sha1(text):
"""SHA-1 hash."""
print(hashlib.sha1(text.encode()).hexdigest())
def cmd_jwt(token):
"""Decode JWT payload (no signature verification)."""
parts = token.split(".")
if len(parts) < 2:
print("Error: invalid JWT format", file=sys.stderr)
return
for i, label in enumerate(["Header", "Payload"]):
if i >= len(parts):
break
padded = parts[i] + "=" * (4 - len(parts[i]) % 4)
try:
decoded = base64.urlsafe_b64decode(padded)
data = json.loads(decoded)
print(f"{label}:")
print(json.dumps(data, indent=2))
# Show expiry if present
if "exp" in data:
exp_dt = datetime.fromtimestamp(data["exp"], tz=timezone.utc)
now = datetime.now(tz=timezone.utc)
status = "EXPIRED" if exp_dt < now else "valid"
print(f" -> Expires: {exp_dt.isoformat()} ({status})")
if "iat" in data:
iat_dt = datetime.fromtimestamp(data["iat"], tz=timezone.utc)
print(f" -> Issued: {iat_dt.isoformat()}")
except Exception as e:
print(f"{label}: <decode error: {e}>")
def cmd_epoch(value=None):
"""Epoch timestamp conversion."""
if value is None:
# Current time
now = time.time()
dt = datetime.now(tz=timezone.utc)
print(f"Epoch: {int(now)}")
print(f"Millis: {int(now * 1000)}")
print(f"UTC: {dt.strftime('%Y-%m-%d %H:%M:%S UTC')}")
print(f"Local: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
elif value.isdigit() or (value.startswith("-") and value[1:].isdigit()):
# Epoch to date
ts = int(value)
if ts > 1e12: # milliseconds
ts = ts / 1000
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
print(f"UTC: {dt.strftime('%Y-%m-%d %H:%M:%S UTC')}")
print(f"Local: {datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')}")
print(f"ISO: {dt.isoformat()}")
else:
# Date string to epoch
for fmt in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d", "%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M:%SZ", "%d/%m/%Y", "%m/%d/%Y"]:
try:
dt = datetime.strptime(value, fmt)
print(f"Epoch: {int(dt.timestamp())}")
print(f"Millis: {int(dt.timestamp() * 1000)}")
return
except ValueError:
continue
print(f"Error: cannot parse date '{value}'", file=sys.stderr)
def cmd_rand(length=32, mode="alphanumeric"):
"""Generate random string."""
if mode == "hex":
print(secrets.token_hex(length // 2 + 1)[:length])
elif mode == "password":
chars = string.ascii_letters + string.digits + "!@#$%^&*()-_=+"
pwd = "".join(secrets.choice(chars) for _ in range(length))
# Ensure at least one of each type
while not (any(c.isupper() for c in pwd) and any(c.islower() for c in pwd)
and any(c.isdigit() for c in pwd) and any(c in "!@#$%^&*()-_=+" for c in pwd)):
pwd = "".join(secrets.choice(chars) for _ in range(length))
print(pwd)
elif mode == "alpha":
print("".join(secrets.choice(string.ascii_letters) for _ in range(length)))
elif mode == "numeric":
print("".join(secrets.choice(string.digits) for _ in range(length)))
else:
print(secrets.token_urlsafe(length)[:length])
def cmd_snake(text):
"""Convert to snake_case."""
# camelCase -> snake_case
s = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', text)
s = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', s)
s = s.replace("-", "_").replace(" ", "_")
print(s.lower())
def cmd_camel(text):
"""Convert to camelCase."""
parts = re.split(r'[_\-\s]+', text)
print(parts[0].lower() + "".join(p.capitalize() for p in parts[1:]))
def cmd_pascal(text):
"""Convert to PascalCase."""
parts = re.split(r'[_\-\s]+', text)
print("".join(p.capitalize() for p in parts))
def cmd_kebab(text):
"""Convert to kebab-case."""
s = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1-\2', text)
s = re.sub(r'([a-z\d])([A-Z])', r'\1-\2', s)
s = s.replace("_", "-").replace(" ", "-")
print(s.lower())
def cmd_count(text):
"""Count characters, words, lines."""
chars = len(text)
words = len(text.split())
lines = text.count("\n") + (1 if text else 0)
print(f"Characters: {chars}")
print(f"Words: {words}")
print(f"Lines: {lines}")
def cmd_json_pretty(text):
"""Pretty-print JSON."""
try:
data = json.loads(text)
print(json.dumps(data, indent=2, ensure_ascii=False))
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}", file=sys.stderr)
LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."
def cmd_lorem(paragraphs=1):
"""Generate lorem ipsum text."""
words = LOREM.split()
for i in range(paragraphs):
# Shuffle for variety after first paragraph
if i > 0:
shuffled = words.copy()
random.shuffle(shuffled)
print(" ".join(shuffled))
else:
print(LOREM)
if i < paragraphs - 1:
print()
def main():
if len(sys.argv) < 2:
print(__doc__)
return
cmd = sys.argv[1].lower()
args = sys.argv[2:]
commands = {
"b64e": lambda: cmd_b64e(args[0] if args else sys.stdin.read().strip()),
"b64d": lambda: cmd_b64d(args[0] if args else sys.stdin.read().strip()),
"urle": lambda: cmd_urle(args[0] if args else sys.stdin.read().strip()),
"urld": lambda: cmd_urld(args[0] if args else sys.stdin.read().strip()),
"uuid": lambda: cmd_uuid(int(args[0]) if args else 1),
"md5": lambda: cmd_md5(args[0] if args else sys.stdin.read().strip()),
"sha1": lambda: cmd_sha1(args[0] if args else sys.stdin.read().strip()),
"sha256": lambda: cmd_sha256(args[0] if args else sys.stdin.read().strip()),
"jwt": lambda: cmd_jwt(args[0] if args else sys.stdin.read().strip()),
"epoch": lambda: cmd_epoch(args[0] if args else None),
"rand": lambda: cmd_rand(
int(args[0]) if args else 32,
"hex" if "--hex" in args else "password" if "--password" in args
else "alpha" if "--alpha" in args else "alphanumeric"
),
"snake": lambda: cmd_snake(args[0] if args else sys.stdin.read().strip()),
"camel": lambda: cmd_camel(args[0] if args else sys.stdin.read().strip()),
"pascal": lambda: cmd_pascal(args[0] if args else sys.stdin.read().strip()),
"kebab": lambda: cmd_kebab(args[0] if args else sys.stdin.read().strip()),
"count": lambda: cmd_count(args[0] if args else sys.stdin.read()),
"json": lambda: cmd_json_pretty(args[0] if args else sys.stdin.read()),
"lorem": lambda: cmd_lorem(int(args[0]) if args else 1),
}
if cmd in commands:
try:
commands[cmd]()
except (IndexError, ValueError) as e:
print(f"Error: {e}", file=sys.stderr)
else:
print(f"Unknown command: {cmd}")
print(f"Available: {', '.join(sorted(commands.keys()))}")
if __name__ == "__main__":
main()