blob: 613be1daa7bab58a3a7cac7d0d637e9a609808dc [file] [log] [blame]
Jukka Rissanen0ff4c252017-09-13 10:43:30 +03001#!/usr/bin/env python3
2#
3# Copyright (c) 2017 Intel Corporation
4#
5# SPDX-License-Identifier: Apache-2.0
6
7# This converts a file to a list of hex characters which can then
8# be included to a source file.
9# Optionally, the output can be compressed if needed.
10
11import argparse
12import codecs
13import gzip
14import io
15
Anas Nashif72565532017-12-12 08:19:25 -050016
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030017def parse_args():
18 global args
19
Anas Nashif72565532017-12-12 08:19:25 -050020 parser = argparse.ArgumentParser(
21 description=__doc__,
22 formatter_class=argparse.RawDescriptionHelpFormatter)
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030023
24 parser.add_argument("-f", "--file", required=True, help="Input file")
25 parser.add_argument("-g", "--gzip", action="store_true",
Anas Nashif72565532017-12-12 08:19:25 -050026 help="Compress the file using gzip before output")
Marc Herbert3061c922019-03-21 14:40:45 -070027 parser.add_argument("-t", "--gzip-mtime", type=int, default=0,
28 nargs='?', const=None,
29 help="""mtime seconds in the gzip header.
30 Defaults to zero to keep builds deterministic. For
31 current date and time (= "now") use this option
32 without any value.""")
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030033 args = parser.parse_args()
34
Anas Nashif72565532017-12-12 08:19:25 -050035
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030036def get_nice_string(list_or_iterator):
Anas Nashif72565532017-12-12 08:19:25 -050037 return ", ".join("0x" + str(x) for x in list_or_iterator)
38
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030039
40def make_hex(chunk):
41 hexdata = codecs.encode(chunk, 'hex').decode("utf-8")
Anas Nashif72565532017-12-12 08:19:25 -050042 hexlist = map(''.join, zip(*[iter(hexdata)] * 2))
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030043 print(get_nice_string(hexlist) + ',')
44
Anas Nashif72565532017-12-12 08:19:25 -050045
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030046def main():
47 parse_args()
48
49 if args.gzip:
Marc Herbert195195a2019-03-21 14:24:00 -070050 with io.BytesIO() as content:
51 with open(args.file, 'rb') as fg:
52 with gzip.GzipFile(fileobj=content, mode='w',
Marc Herbert3061c922019-03-21 14:40:45 -070053 mtime=args.gzip_mtime,
Marc Herbert195195a2019-03-21 14:24:00 -070054 compresslevel=9) as gz_obj:
55 gz_obj.write(fg.read())
56
57 content.seek(0)
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030058 for chunk in iter(lambda: content.read(8), b''):
59 make_hex(chunk)
60 else:
61 with open(args.file, "rb") as fp:
62 for chunk in iter(lambda: fp.read(8), b''):
63 make_hex(chunk)
64
Anas Nashif72565532017-12-12 08:19:25 -050065
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030066if __name__ == "__main__":
67 main()