-
-
Notifications
You must be signed in to change notification settings - Fork 316
/
Copy pathpack-file.py
executable file
·61 lines (52 loc) · 1.28 KB
/
pack-file.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python3
import argparse
import sys
from io import StringIO
from typing import Union, TextIO
import os.path
def encode_bytes(data: Union[bytes, bytearray], outfile: TextIO):
"""
Encode data as a string of C-style escape sequences
"""
for i,v in enumerate(data):
if i % 16 == 0:
outfile.write('\t"')
outfile.write('\\x%02x' % v)
if i % 16 == 15:
outfile.write('"\n')
if i % 16 != 15:
outfile.write('"')
def encode_bytes_str(data: Union[bytes, bytearray]):
outfile = StringIO()
encode_bytes(data, outfile)
outfile.seek(0)
return outfile.read()
def main():
ap = argparse.ArgumentParser()
ap.add_argument('path')
ap.add_argument('cout')
ap.add_argument('hout')
args = ap.parse_args()
data = bytearray(open(args.path, 'rb').read())
fname, _ = os.path.splitext(os.path.basename(args.path))
ident = ''.join([c if c.isalnum() else '_' for c in fname])
with open(args.hout, 'w') as f:
f.write(
f'''\
#ifndef DATA_{ident.upper()}_H
#define DATA_{ident.upper()}_H
extern const unsigned int {ident}_size;
extern const unsigned char {ident}_data[];
#endif
'''
)
with open(args.cout, 'w') as f:
f.write(
f'''\
const unsigned int {ident}_size = {len(data)};
const unsigned char {ident}_data[] =
{encode_bytes_str(data)};
'''
)
if __name__ == '__main__':
main()