identicon/main.py

53 lines
1.0 KiB
Python

from sys import argv, stdin
from sys import exit as sysexit
from select import select
from hashlib import blake2b
from io import BytesIO
from identicon import Identicon
DIGEST_SIZE = 20
BUF_SIZE = 4096
def main():
if not (stream := get_input_stream()):
print_usage_and_exit()
i = Identicon(get_digest(stream))
i.calculate()
print(i)
def get_input_stream():
io = None
if len(argv) == 2:
io = BytesIO(argv[1].encode())
elif stdin_has_data():
io = stdin.buffer
return io
def stdin_has_data():
return bool(select([stdin], [], [], 0.0)[0])
def print_usage_and_exit():
print('Usage: identicon [TEXT]')
print('Print OpenSSH style randomart identicon for arbitrary data.\n')
print('If TEXT is not supplied, data is read from STDIN.')
sysexit(1)
def get_digest(stream):
hasher = blake2b(digest_size=DIGEST_SIZE)
while data := stream.read(BUF_SIZE):
hasher.update(data)
return hasher.digest()
if __name__ == '__main__':
main()