summaryrefslogtreecommitdiffstats
path: root/scripts/quotestring.py
blob: 1038719e700aa740133e8e63972220f4622b6883 (plain)
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
62
#! /usr/bin/python

import re
import getopt
import sys

def usage():
    print >> sys.stderr, (
        "Usage: %s <input> [output]\n"
        "Summary:\n"
        "    Creates a quoted string suitable for inclusion in a C char*\n\n"
        "Options:\n"
        "    <input>   Input file to quote\n"
        "    <output>  Output quoted string [stdout]\n"
        % sys.argv[0]
    )

def main():
    global inc_list

    OPTS = ""
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], OPTS)
    except getopt.GetoptError, err:
        print >> sys.stderr, str(err)
        usage()
        sys.exit(2)

    for o, a in opts:
        usage()
        assert False, "unhandled option"

    if len(args) > 2 or len(args) < 1:
        usage()
        sys.exit(2)

    try:
        infile = open(args[0])
    except Exception, err:
        print >> sys.stderr, ( "Error: %s"  % str(err) )
        sys.exit(1)

    if len(args) > 1:
        try:
            outfile = open(args[1], "w")
        except Exception, err:
            print >> sys.stderr, ( "Error: %s"  % str(err))
            sys.exit(1)
    else:
        outfile = sys.stdout

    ss = infile.read()
    ss = re.sub(r'\\', r'\\\\', ss)
    ss = re.sub(r'"', r'\\"', ss)
    pattern = re.compile("$", re.M)
    ss = re.sub(pattern, r'\\n"', ss)
    pattern = re.compile("^", re.M)
    ss = re.sub(pattern, "\"", ss)
    outfile.write(ss)

main()