|
| 1 | +#! /usr/bin/python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +# The MIT License (MIT) |
| 5 | +# |
| 6 | +# Copyright (c) 2016 Peter Hinch |
| 7 | +# |
| 8 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 9 | +# of this software and associated documentation files (the "Software"), to deal |
| 10 | +# in the Software without restriction, including without limitation the rights |
| 11 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 12 | +# copies of the Software, and to permit persons to whom the Software is |
| 13 | +# furnished to do so, subject to the following conditions: |
| 14 | +# |
| 15 | +# The above copyright notice and this permission notice shall be included in |
| 16 | +# all copies or substantial portions of the Software. |
| 17 | +# |
| 18 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 19 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 20 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 21 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 22 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 23 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 24 | +# THE SOFTWARE. |
| 25 | + |
| 26 | +import argparse |
| 27 | +import sys |
| 28 | +import os |
| 29 | + |
| 30 | +# UTILITIES FOR WRITING PYTHON SOURCECODE TO A FILE |
| 31 | + |
| 32 | +# ByteWriter takes as input a variable name and data values and writes |
| 33 | +# Python source to an output stream of the form |
| 34 | +# my_variable = b'\x01\x02\x03\x04\x05\x06\x07\x08'\ |
| 35 | + |
| 36 | +# Lines are broken with \ for readability. |
| 37 | + |
| 38 | + |
| 39 | +class ByteWriter(object): |
| 40 | + bytes_per_line = 16 |
| 41 | + |
| 42 | + def __init__(self, stream, varname): |
| 43 | + self.stream = stream |
| 44 | + self.stream.write('{} =\\\n'.format(varname)) |
| 45 | + self.bytecount = 0 # For line breaks |
| 46 | + |
| 47 | + def _eol(self): |
| 48 | + self.stream.write("'\\\n") |
| 49 | + |
| 50 | + def _eot(self): |
| 51 | + self.stream.write("'\n") |
| 52 | + |
| 53 | + def _bol(self): |
| 54 | + self.stream.write("b'") |
| 55 | + |
| 56 | + # Output a single byte |
| 57 | + def obyte(self, data): |
| 58 | + if not self.bytecount: |
| 59 | + self._bol() |
| 60 | + self.stream.write('\\x{:02x}'.format(data)) |
| 61 | + self.bytecount += 1 |
| 62 | + self.bytecount %= self.bytes_per_line |
| 63 | + if not self.bytecount: |
| 64 | + self._eol() |
| 65 | + |
| 66 | + # Output from a sequence |
| 67 | + def odata(self, bytelist): |
| 68 | + for byt in bytelist: |
| 69 | + self.obyte(byt) |
| 70 | + |
| 71 | + # ensure a correct final line |
| 72 | + def eot(self): # User force EOL if one hasn't occurred |
| 73 | + if self.bytecount: |
| 74 | + self._eot() |
| 75 | + self.stream.write('\n') |
| 76 | + |
| 77 | + |
| 78 | +# PYTHON FILE WRITING |
| 79 | + |
| 80 | +STR01 = """# Code generated by data_to_py.py. |
| 81 | +version = '0.1' |
| 82 | +""" |
| 83 | + |
| 84 | +STR02 = """_mvdata = memoryview(_data) |
| 85 | +
|
| 86 | +def data(): |
| 87 | + return _mvdata |
| 88 | + |
| 89 | +""" |
| 90 | + |
| 91 | +def write_func(stream, name, arg): |
| 92 | + stream.write('def {}():\n return {}\n\n'.format(name, arg)) |
| 93 | + |
| 94 | + |
| 95 | +def write_data(op_path, ip_path): |
| 96 | + try: |
| 97 | + with open(ip_path, 'rb') as ip_stream: |
| 98 | + try: |
| 99 | + with open(op_path, 'w') as op_stream: |
| 100 | + write_stream(ip_stream, op_stream) |
| 101 | + except OSError: |
| 102 | + print("Can't open", op_path, 'for writing') |
| 103 | + return False |
| 104 | + except OSError: |
| 105 | + print("Can't open", ip_path) |
| 106 | + return False |
| 107 | + return True |
| 108 | + |
| 109 | + |
| 110 | +def write_stream(ip_stream, op_stream): |
| 111 | + op_stream.write(STR01) |
| 112 | + op_stream.write('\n') |
| 113 | + data = ip_stream.read() |
| 114 | + bw_data = ByteWriter(op_stream, '_data') |
| 115 | + bw_data.odata(data) |
| 116 | + bw_data.eot() |
| 117 | + op_stream.write(STR02) |
| 118 | + |
| 119 | + |
| 120 | +# PARSE COMMAND LINE ARGUMENTS |
| 121 | + |
| 122 | +def quit(msg): |
| 123 | + print(msg) |
| 124 | + sys.exit(1) |
| 125 | + |
| 126 | +DESC = """data_to_py.py |
| 127 | +Utility to convert an arbitrary binary file to Python source. |
| 128 | +Sample usage: |
| 129 | +data_to_py.py image.jpg image.py |
| 130 | +
|
| 131 | +""" |
| 132 | + |
| 133 | +if __name__ == "__main__": |
| 134 | + parser = argparse.ArgumentParser(__file__, description=DESC, |
| 135 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 136 | + parser.add_argument('infile', type=str, help='Input file path') |
| 137 | + parser.add_argument('outfile', type=str, |
| 138 | + help='Path and name of output file. Must have .py extension.') |
| 139 | + |
| 140 | + |
| 141 | + args = parser.parse_args() |
| 142 | + |
| 143 | + if not os.path.isfile(args.infile): |
| 144 | + quit("Data filename does not exist") |
| 145 | + |
| 146 | + if not os.path.splitext(args.outfile)[1].upper() == '.PY': |
| 147 | + quit('Output filename must have a .py extension.') |
| 148 | + |
| 149 | + print('Writing Python file.') |
| 150 | + if not write_data(args.outfile, args.infile): |
| 151 | + sys.exit(1) |
| 152 | + |
| 153 | + print(args.outfile, 'written successfully.') |
0 commit comments