Project

General

Profile

Patch #939 » gen.py

new website/bin/gen.py - Alex Turbov, 20 Dec 2013 18:13

 
1
#! /usr/bin/env python
2
# ----------------------------------------------------------------------
3
# Settings
4
vardir = "./var"
5
date_format = "%d-%b-%Y"
6

    
7
# ----------------------------------------------------------------------
8
# functions
9
def usage():
10
   print("""Usage: gen.py file.in [...]
11
   Substitute placeholders in input files with content
12
   """)
13

    
14
def gen_html(file):
15
   """Replace variables in the file with their content"""
16
   text = open(file).read()
17
   for var in vars:
18
      vartext = open(vardir + "/" + var).read()
19
      text = text.replace(var, vartext)
20
   text = last_modified(text)
21
   return text
22

    
23
def last_modified(text):
24
   """Substitute variable __last_modified__ with the current date"""
25
   date = time.strftime(date_format, time.localtime())
26
   text = text.replace("__last_modified__", date)
27
   return text
28

    
29
# ----------------------------------------------------------------------
30
# main
31
import sys
32
import os
33
import re
34
import time
35

    
36
# Check command line arguments
37
if len(sys.argv) == 1:
38
   usage()
39
   sys.exit()
40

    
41
# The input files from the command line
42
input = sys.argv[1:]
43

    
44
# Get a list of all variables (files in the form __*__) from vardir 
45
vars = os.listdir(vardir)
46
for i in range(len(vars)-1, -1, -1):
47
   if re.match("^__.*__$", vars[i]): continue
48
   del vars[i]
49
vars.sort()
50

    
51
# Substitute variables in all input files
52
print("Substituting variables {0}".format(vars))
53
for file in input:
54
   print("Processing {0}...".format(file))
55
   text = gen_html(file)
56
   file = file.replace(".in", "")
57
   open(file, 'w').write(text)
(5-5/5)