#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2024 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from base64 import b64encode from mimetypes import guess_type from sys import argv, exit, stderr, stdout info = ''' datauri [options...] [filepaths/URIs...] Turn each named input (file/URI) given into a data-URI line. Data-URIs are base64-encoded text representations of arbitrary data, which include their payload's MIME-type, and which are directly useable/shareable in web-browsers as links, despite not looking like normal links/URIs. ''' # no args or a leading help-option arg means show the help message and quit if len(argv) == 1 or argv[1] in ('-h', '--h', '-help', '--help'): print(info.strip(), file=stderr) exit(0) def seems_url(s: str) -> bool: protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') return any(s.startswith(p) for p in protocols) def handle_input(w, src, path: str) -> None: mime = '' # get MIME-type from response headers, if input is an HTTP response if hasattr(inp, 'getheader'): mime = inp.getheader('content-type') # failing that, guess the MIME-type from the input's name/URI if not mime: (mime, _) = guess_type(path) if not mime: raise Exception(f'{path}: can\'t guess MIME-type') w.write(b'data:') w.write(bytes(mime, encoding='utf-8')) w.write(b';base64,') w.write(b64encode(src.read())) w.write(b'\n') try: if '-' in argv: raise Exception('can\'t use standard input, only named sources') if any(seems_url(e) for e in argv): from urllib.request import urlopen for path in argv[1:]: if seems_url(path): with urlopen(path) as inp: handle_input(stdout.buffer, inp, path) continue with open(path, mode='rb') as inp: handle_input(stdout.buffer, inp, path) except BrokenPipeError: # quit quietly, instead of showing a confusing error message stderr.close() except KeyboardInterrupt: exit(2) except Exception as e: print(f'\x1b[31m{e}\x1b[0m', file=stderr) exit(1)