blob: 0235a57cea897dc1d47f1eb54924d92008bae534 [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")
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030027 args = parser.parse_args()
28
Anas Nashif72565532017-12-12 08:19:25 -050029
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030030def get_nice_string(list_or_iterator):
Anas Nashif72565532017-12-12 08:19:25 -050031 return ", ".join("0x" + str(x) for x in list_or_iterator)
32
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030033
34def make_hex(chunk):
35 hexdata = codecs.encode(chunk, 'hex').decode("utf-8")
Anas Nashif72565532017-12-12 08:19:25 -050036 hexlist = map(''.join, zip(*[iter(hexdata)] * 2))
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030037 print(get_nice_string(hexlist) + ',')
38
Anas Nashif72565532017-12-12 08:19:25 -050039
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030040def main():
41 parse_args()
42
43 if args.gzip:
44 with open(args.file, 'rb') as fg:
45 content = io.BytesIO(gzip.compress(fg.read(), compresslevel=9))
46 for chunk in iter(lambda: content.read(8), b''):
47 make_hex(chunk)
48 else:
49 with open(args.file, "rb") as fp:
50 for chunk in iter(lambda: fp.read(8), b''):
51 make_hex(chunk)
52
Anas Nashif72565532017-12-12 08:19:25 -050053
Jukka Rissanen0ff4c252017-09-13 10:43:30 +030054if __name__ == "__main__":
55 main()