-
Notifications
You must be signed in to change notification settings - Fork 0
/
cembed.py
57 lines (42 loc) · 1.13 KB
/
cembed.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
#!/usr/bin/python3
import os, sys, random, re
def fmt(fmt, dic):
for k in dic:
fmt = fmt.replace("{%s}" % k, str(dic[k]))
return fmt
def makeArray(data):
i = [0]
def fn(x):
x = str(x) + ","
if i[0] + len(x) > 78:
i[0] = len(x)
x = '\n' + x
else:
i[0] += len(x)
return x
return '{' + "".join(map(fn, data)).rstrip(",") + '}'
def safename(filename):
return re.sub("[^a-z0-9]", "_", os.path.basename(filename).lower())
def process(filenames):
if type(filenames) is str:
filenames = [filenames]
strings = []
for filename in filenames:
data = open(filename, "rb").read()
strings.append(
fmt("/* {filename} */\n" +\
"static const char {name}[] = \n{array};",
{
"filename" : os.path.basename(filename),
"name" : safename(filename),
"array" : makeArray(data),
}))
return "/* Automatically generated; do not edit */\n\n" +\
"\n\n".join(strings)
def main():
if len(sys.argv) < 2:
print("usage: embed FILENAMES")
sys.exit(1)
print(process(sys.argv[1:]))
if __name__ == "__main__":
main()