File: rewrite.py

package info (click to toggle)
python2.4 2.4.6-1%2Blenny1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 44,888 kB
  • ctags: 86,995
  • sloc: ansic: 306,391; python: 271,931; sh: 10,210; makefile: 4,248; perl: 3,736; lisp: 3,678; xml: 894; objc: 756; cpp: 7; sed: 2
file content (54 lines) | stat: -rw-r--r-- 1,362 bytes parent folder | download | duplicates (14)
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
"""Simple script to replace @DATE@ and friends with real information.

Usage:  rewrite.py boilerplate.tex [VAR=value] ... <template >output
"""

import sys
import time


def get_info(fp):
    s = fp.read()

    d = {}
    start = s.find(r"\date{")
    if start >= 0:
        end = s.find("}", start)
        date = s[start+6:end]
        if date == r"\today":
            date = time.strftime("%B %d, %Y", time.localtime(time.time()))
        d["DATE"] = date
    return d


def main():
    s = sys.stdin.read()
    if "@" in s:
        # yes, we actully need to load the replacement values
        d = get_info(open(sys.argv[1]))
        for arg in sys.argv[2:]:
            name, value = arg.split("=", 1)
            d[name] = value
        start = 0
        while 1:
            start = s.find("@", start)
            if start < 0:
                break
            end = s.find("@", start+1)
            name = s[start+1:end]
            if name:
                value = d.get(name)
                if value is None:
                    start = end + 1
                else:
                    s = s[:start] + value + s[end+1:]
                    start = start + len(value)
            else:
                # "@@" --> "@"
                s = s[:start] + s[end:]
                start = end
    sys.stdout.write(s)


if __name__ == "__main__":
    main()