48 lines
1.9 KiB
Python
Executable File
48 lines
1.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# uuidgen - generate UUIDs (v4) and short ids
|
|
# Usage: uuidgen [--count N] [--short [LEN]] [--upper] [--v1]
|
|
# Default: one random UUID v4. --short gives a compact base62 id (default 12 chars).
|
|
import argparse, base64, secrets, string, sys, uuid
|
|
|
|
B62 = string.digits + string.ascii_uppercase + string.ascii_lowercase
|
|
|
|
def short_id(length=12):
|
|
return "".join(secrets.choice(B62) for _ in range(length))
|
|
|
|
def selftest():
|
|
u = str(uuid.uuid4())
|
|
assert len(u) == 36 and u[14] == "4" and u[19] in "89ab"
|
|
assert uuid.UUID(u).version == 4
|
|
s = short_id(12)
|
|
assert len(s) == 12 and all(c in B62 for c in s)
|
|
assert len({short_id(8) for _ in range(50)}) > 40
|
|
print("uuidgen selftest: ok (v4 shape/version, short-id charset, uniqueness)")
|
|
return 0
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(prog="uuidgen",
|
|
description="Generate UUIDs (v4) and short ids.")
|
|
p.add_argument("--count", type=int, default=1, help="how many (default 1)")
|
|
p.add_argument("--short", nargs="?", const=12, type=int, metavar="LEN",
|
|
help="generate short base62 ids of LEN chars (default 12)")
|
|
p.add_argument("--upper", action="store_true", help="uppercase UUIDs")
|
|
p.add_argument("--v1", action="store_true", help="time-based UUID v1 instead of v4")
|
|
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
if a.count < 1:
|
|
print("uuidgen: --count must be >= 1", file=sys.stderr); return 2
|
|
for _ in range(a.count):
|
|
if a.short is not None:
|
|
if a.short < 4 or a.short > 64:
|
|
print("uuidgen: short length 4-64", file=sys.stderr); return 2
|
|
print(short_id(a.short))
|
|
else:
|
|
u = str(uuid.uuid1() if a.v1 else uuid.uuid4())
|
|
print(u.upper() if a.upper else u)
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|