Files
workspace/tools/gen.py

147 lines
4.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""
gen - Content generators
Generate passwords, UUIDs, lorem ipsum, and more.
"""
import sys
import random
import string
import uuid
import hashlib
from datetime import datetime
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. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""
WORDS = LOREM.replace(',', '').replace('.', '').lower().split()
def password(length: int = 16, simple: bool = False):
"""Generate a secure password."""
if simple:
chars = string.ascii_letters + string.digits
else:
chars = string.ascii_letters + string.digits + "!@#$%^&*"
pwd = ''.join(random.choice(chars) for _ in range(length))
print(pwd)
def gen_uuid():
"""Generate a UUID."""
print(uuid.uuid4())
def lorem(words: int = 50):
"""Generate lorem ipsum text."""
output = []
for i in range(words):
word = random.choice(WORDS)
if i == 0 or output[-1].endswith('.'):
word = word.capitalize()
output.append(word)
# Add periods
text = ' '.join(output)
# Every ~10 words add punctuation
words_list = text.split()
result = []
for i, word in enumerate(words_list):
result.append(word)
if (i + 1) % random.randint(8, 12) == 0 and i < len(words_list) - 1:
if random.random() < 0.7:
result[-1] += '.'
else:
result[-1] += ','
print(' '.join(result) + '.')
def hash_text(text: str, algorithm: str = 'sha256'):
"""Hash some text."""
if algorithm == 'md5':
h = hashlib.md5(text.encode()).hexdigest()
elif algorithm == 'sha1':
h = hashlib.sha1(text.encode()).hexdigest()
else:
h = hashlib.sha256(text.encode()).hexdigest()
print(h)
def random_number(min_val: int = 1, max_val: int = 100):
"""Generate a random number."""
print(random.randint(min_val, max_val))
def random_choice(options: list):
"""Pick a random option."""
choice = random.choice(options)
print(f"🎲 {choice}")
def slug(text: str):
"""Generate a URL slug from text."""
slug = text.lower()
slug = ''.join(c if c.isalnum() or c == ' ' else '' for c in slug)
slug = '-'.join(slug.split())
print(slug)
def timestamp():
"""Generate current timestamp."""
now = datetime.now()
print(f"ISO: {now.isoformat()}")
print(f"Unix: {int(now.timestamp())}")
print(f"Date: {now.strftime('%Y-%m-%d')}")
print(f"Time: {now.strftime('%H:%M:%S')}")
def main():
if len(sys.argv) < 2:
print("Usage:")
print(" gen pass [length] - Generate password")
print(" gen pass simple [n] - Simple password (no symbols)")
print(" gen uuid - Generate UUID")
print(" gen lorem [words] - Lorem ipsum text")
print(" gen hash <text> - SHA256 hash")
print(" gen rand [min] [max] - Random number")
print(" gen pick <options> - Random choice")
print(" gen slug <text> - URL slug")
print(" gen time - Current timestamps")
return
cmd = sys.argv[1]
if cmd in ['pass', 'password', 'pw']:
simple = 'simple' in sys.argv
length = 16
for arg in sys.argv[2:]:
if arg.isdigit():
length = int(arg)
password(length, simple)
elif cmd == 'uuid':
gen_uuid()
elif cmd == 'lorem':
words = int(sys.argv[2]) if len(sys.argv) > 2 else 50
lorem(words)
elif cmd == 'hash' and len(sys.argv) > 2:
text = ' '.join(sys.argv[2:])
hash_text(text)
elif cmd in ['rand', 'random']:
min_v = int(sys.argv[2]) if len(sys.argv) > 2 else 1
max_v = int(sys.argv[3]) if len(sys.argv) > 3 else 100
random_number(min_v, max_v)
elif cmd == 'pick' and len(sys.argv) > 2:
options = sys.argv[2:]
random_choice(options)
elif cmd == 'slug' and len(sys.argv) > 2:
text = ' '.join(sys.argv[2:])
slug(text)
elif cmd in ['time', 'timestamp']:
timestamp()
else:
print("Unknown command. Run 'gen' for help.")
if __name__ == "__main__":
main()