2 # Copyright © 2018 Intel Corporation
4 # Permission is hereby granted, free of charge, to any person obtaining a
5 # copy of this software and associated documentation files (the "Software"),
6 # to deal in the Software without restriction, including without limitation
7 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Software, and to permit persons to whom the
9 # Software is furnished to do so, subject to the following conditions:
11 # The above copyright notice and this permission notice (including the next
12 # paragraph) shall be included in all copies or substantial portions of the
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 # Converts a file to a C/C++ #include containing a string
25 from __future__
import unicode_literals
33 parser
= argparse
.ArgumentParser()
34 parser
.add_argument('input', help="Name of input file")
35 parser
.add_argument('output', help="Name of output file")
36 parser
.add_argument("-n", "--name",
37 help="Name of C variable")
38 args
= parser
.parse_args()
42 def filename_to_C_identifier(n
):
43 if n
[0] != '_' and not n
[0].isalpha():
46 return "".join([c
if c
.isalnum() or c
== "_" else "_" for c
in n
])
50 if ord(b
) == ord('\n'):
51 f
.write(b
"\\n\"\n \"")
53 elif ord(b
) == ord('\r'):
54 f
.write(b
"\\r\"\n \"")
56 elif ord(b
) == ord('\t'):
59 elif ord(b
) == ord('"'):
62 elif ord(b
) == ord('\\'):
66 if ord(b
) >= ord(' ') and ord(b
) <= ord('~'):
71 f
.write("\\x{:x}{:x}".format(hi
, lo
).encode('utf-8'))
74 def process_file(args
):
75 with io
.open(args
.input, "rb") as infile
:
77 with io
.open(args
.output
, "wb") as outfile
:
78 # If a name was not specified on the command line, pick one based on the
79 # name of the input file. If no input filename was specified, use
81 if args
.name
is not None:
84 name
= filename_to_C_identifier(args
.input)
86 outfile
.write("static const char {}[] =\n \"".format(name
).encode('utf-8'))
93 emit_byte(outfile
, byte
)
95 outfile
.write(b
"\"\n ;\n")
97 # In the event that anything goes wrong, delete the output file,
98 # then re-raise the exception. Deleteing the output file should
99 # ensure that the build system doesn't try to use the stale,
100 # half-generated file.
101 os
.unlink(args
.output
)
110 if __name__
== "__main__":