File: file2string.py

package info (click to toggle)
mpv 0.40.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,676 kB
  • sloc: ansic: 152,062; python: 1,228; sh: 646; javascript: 612; cpp: 461; objc: 302; pascal: 49; xml: 29; makefile: 19
file content (45 lines) | stat: -rwxr-xr-x 1,679 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python3

# Convert the contents of a file into a C string constant.
# Note that the compiler will implicitly add an extra 0 byte at the end
# of every string, so code using the string may need to remove that to get
# the exact contents of the original file.

#
# This file is part of mpv.
#
# mpv is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# mpv is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import sys


def file2string(infilename, infile, outfile):
    outfile.write(f"// Generated from {infilename}\n\n")

    conv = [f"\\{c:03o}" for c in range(256)]
    safe_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" \
                 "0123456789!#%&'()*+,-./:;<=>[]^_{|}~ "

    for c in safe_chars:
        conv[ord(c)] = c
    for c, esc in [("\n", "n"), ("\t", "t"), ("\\", "\\"), ('"', '"')]:
        conv[ord(c)] = "\\" + esc
    for line in infile:
        outfile.write('"' + "".join(conv[c] for c in line) + '"\n')

if __name__ == "__main__":
    with open(sys.argv[1], "rb") as infile, open(sys.argv[2], "w") as outfile:
        file2string(os.path.relpath(sys.argv[1], sys.argv[3]), infile, outfile)