1b8e80941Smrg# encoding=utf-8
2b8e80941Smrg# Copyright © 2018 Intel Corporation
3b8e80941Smrg#
4b8e80941Smrg# Permission is hereby granted, free of charge, to any person obtaining a
5b8e80941Smrg# copy of this software and associated documentation files (the "Software"),
6b8e80941Smrg# to deal in the Software without restriction, including without limitation
7b8e80941Smrg# the rights to use, copy, modify, merge, publish, distribute, sublicense,
8b8e80941Smrg# and/or sell copies of the Software, and to permit persons to whom the
9b8e80941Smrg# Software is furnished to do so, subject to the following conditions:
10b8e80941Smrg#
11b8e80941Smrg# The above copyright notice and this permission notice (including the next
12b8e80941Smrg# paragraph) shall be included in all copies or substantial portions of the
13b8e80941Smrg# Software.
14b8e80941Smrg#
15b8e80941Smrg# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16b8e80941Smrg# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17b8e80941Smrg# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18b8e80941Smrg# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19b8e80941Smrg# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20b8e80941Smrg# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21b8e80941Smrg# IN THE SOFTWARE.
22b8e80941Smrg
23b8e80941Smrg# Converts a file to a C/C++ #include containing a string
24b8e80941Smrg
25b8e80941Smrgfrom __future__ import unicode_literals
26b8e80941Smrgimport argparse
27b8e80941Smrgimport io
28b8e80941Smrgimport string
29b8e80941Smrgimport sys
30b8e80941Smrg
31b8e80941Smrg
32b8e80941Smrgdef get_args():
33b8e80941Smrg    parser = argparse.ArgumentParser()
34b8e80941Smrg    parser.add_argument('input', help="Name of input file")
35b8e80941Smrg    parser.add_argument('output', help="Name of output file")
36b8e80941Smrg    parser.add_argument("-n", "--name",
37b8e80941Smrg                        help="Name of C variable")
38b8e80941Smrg    args = parser.parse_args()
39b8e80941Smrg    return args
40b8e80941Smrg
41b8e80941Smrg
42b8e80941Smrgdef filename_to_C_identifier(n):
43b8e80941Smrg    if n[0] != '_' and not n[0].isalpha():
44b8e80941Smrg        n = "_" + n[1:]
45b8e80941Smrg
46b8e80941Smrg    return "".join([c if c.isalnum() or c == "_" else "_" for c in n])
47b8e80941Smrg
48b8e80941Smrg
49b8e80941Smrgdef emit_byte(f, b):
50b8e80941Smrg    if ord(b) == ord('\n'):
51b8e80941Smrg        f.write(b"\\n\"\n    \"")
52b8e80941Smrg        return
53b8e80941Smrg    elif ord(b) == ord('\r'):
54b8e80941Smrg        f.write(b"\\r\"\n    \"")
55b8e80941Smrg        return
56b8e80941Smrg    elif ord(b) == ord('\t'):
57b8e80941Smrg        f.write(b"\\t")
58b8e80941Smrg        return
59b8e80941Smrg    elif ord(b) == ord('"'):
60b8e80941Smrg        f.write(b"\\\"")
61b8e80941Smrg        return
62b8e80941Smrg    elif ord(b) == ord('\\'):
63b8e80941Smrg        f.write(b"\\\\")
64b8e80941Smrg        return
65b8e80941Smrg
66b8e80941Smrg    if ord(b) >= ord(' ') and ord(b) <= ord('~'):
67b8e80941Smrg        f.write(b)
68b8e80941Smrg    else:
69b8e80941Smrg        hi = ord(b) >> 4
70b8e80941Smrg        lo = ord(b) & 0x0f
71b8e80941Smrg        f.write("\\x{:x}{:x}".format(hi, lo).encode('utf-8'))
72b8e80941Smrg
73b8e80941Smrg
74b8e80941Smrgdef process_file(args):
75b8e80941Smrg    with io.open(args.input, "rb") as infile:
76b8e80941Smrg        try:
77b8e80941Smrg            with io.open(args.output, "wb") as outfile:
78b8e80941Smrg                # If a name was not specified on the command line, pick one based on the
79b8e80941Smrg                # name of the input file.  If no input filename was specified, use
80b8e80941Smrg                # from_stdin.
81b8e80941Smrg                if args.name is not None:
82b8e80941Smrg                    name = args.name
83b8e80941Smrg                else:
84b8e80941Smrg                    name = filename_to_C_identifier(args.input)
85b8e80941Smrg
86b8e80941Smrg                outfile.write("static const char {}[] =\n \"".format(name).encode('utf-8'))
87b8e80941Smrg
88b8e80941Smrg                while True:
89b8e80941Smrg                    byte = infile.read(1)
90b8e80941Smrg                    if byte == b"":
91b8e80941Smrg                        break
92b8e80941Smrg
93b8e80941Smrg                    emit_byte(outfile, byte)
94b8e80941Smrg
95b8e80941Smrg                outfile.write(b"\"\n    ;\n")
96b8e80941Smrg        except Exception:
97b8e80941Smrg            # In the event that anything goes wrong, delete the output file,
98b8e80941Smrg            # then re-raise the exception. Deleteing the output file should
99b8e80941Smrg            # ensure that the build system doesn't try to use the stale,
100b8e80941Smrg            # half-generated file.
101b8e80941Smrg            os.unlink(args.output)
102b8e80941Smrg            raise
103b8e80941Smrg
104b8e80941Smrg
105b8e80941Smrgdef main():
106b8e80941Smrg    args = get_args()
107b8e80941Smrg    process_file(args)
108b8e80941Smrg
109b8e80941Smrg
110b8e80941Smrgif __name__ == "__main__":
111b8e80941Smrg    main()
112