1#!/usr/bin/env python3 2# 3# Copyright (c) 2017 Intel Corporation 4# 5# SPDX-License-Identifier: Apache-2.0 6 7 8"""Convert a file to a list of hex characters 9 10The list of hex characters can then be included to a source file. Optionally, 11the output can be compressed. 12 13""" 14 15import argparse 16import codecs 17import gzip 18import io 19 20 21def parse_args(): 22 global args 23 24 parser = argparse.ArgumentParser( 25 description=__doc__, 26 formatter_class=argparse.RawDescriptionHelpFormatter) 27 28 parser.add_argument("-f", "--file", required=True, help="Input file") 29 parser.add_argument("-g", "--gzip", action="store_true", 30 help="Compress the file using gzip before output") 31 parser.add_argument("-t", "--gzip-mtime", type=int, default=0, 32 nargs='?', const=None, 33 help="""mtime seconds in the gzip header. 34 Defaults to zero to keep builds deterministic. For 35 current date and time (= "now") use this option 36 without any value.""") 37 args = parser.parse_args() 38 39 40def get_nice_string(list_or_iterator): 41 return ", ".join("0x" + str(x) for x in list_or_iterator) 42 43 44def make_hex(chunk): 45 hexdata = codecs.encode(chunk, 'hex').decode("utf-8") 46 hexlist = map(''.join, zip(*[iter(hexdata)] * 2)) 47 print(get_nice_string(hexlist) + ',') 48 49 50def main(): 51 parse_args() 52 53 if args.gzip: 54 with io.BytesIO() as content: 55 with open(args.file, 'rb') as fg: 56 with gzip.GzipFile(fileobj=content, mode='w', 57 mtime=args.gzip_mtime, 58 compresslevel=9) as gz_obj: 59 gz_obj.write(fg.read()) 60 61 content.seek(0) 62 for chunk in iter(lambda: content.read(8), b''): 63 make_hex(chunk) 64 else: 65 with open(args.file, "rb") as fp: 66 for chunk in iter(lambda: fp.read(8), b''): 67 make_hex(chunk) 68 69 70if __name__ == "__main__": 71 main() 72