Tool for inserting changelog into rst documents (i.e. manual)
[mussa.git] / doc / manual / insert_change_log.py
1 #!/usr/bin/python
2
3 import re
4 import subprocess
5 import sys
6
7 COMMAND = 'darcs'
8 CHANGE_LOG_ARG = 'changes'
9 BUILDS_TO_SHOW = 10
10
11 search = re.compile('^(Mon)|(Tue)|(Wed)|(Thu)|(Fri)|(Sat)|(Sun)', re.MULTILINE)
12
13 searchStartInsert = re.compile('^\.\. INSERT CHANGE LOG HERE', re.MULTILINE)
14 searchEndInsert = re.compile('^\.\. END INSERT CHANGE LOG', re.MULTILINE)
15
16 MUST_HAVE = """
17 .. INSERT CHANGE LOG HERE
18 .. END INSERT CHANGE LOG
19 """
20
21 def getBuildCount(data):
22   """returns number of latest build (a.k.a. total number of builds)
23   """
24   return len(search.findall(data))
25
26
27 def process(filePath, buildsToShow=BUILDS_TO_SHOW):
28   p = subprocess.Popen([COMMAND, CHANGE_LOG_ARG], stdout=subprocess.PIPE)
29
30   data = p.stdout.read()
31   buildCount = getBuildCount(data)
32
33   buildNumIter = iter(range(buildCount, 0, -1))
34
35   new_data = []
36   count = 0
37   for line in data.split('\n'):
38     #Find a new build or move on
39     if not search.search(line):
40       new_data.append(line)
41     else:
42       if count < buildsToShow:
43         new_data.append('Build: %s - %s\n' % (buildNumIter.next(), line))
44       else:
45         break
46       count += 1
47   
48   #Time to insert changelog
49   f = open(filePath, 'r')
50   dataInsert = f.read()
51   f.close()
52
53   new_data = ".. INSERT CHANGE LOG HERE\n\n::\n\n  " \
54         + '\n  '.join(new_data) + "\n.. END INSERT CHANGE LOG\n"
55   
56   moStart = searchStartInsert.search(dataInsert)
57   moEnd = searchEndInsert.search(dataInsert)
58   
59   if moStart is None or moEnd is None:
60     msg = 'Document %s must have the folling within the file: %s' % (filePath, MUST_HAVE)
61     raise ValueError, msg
62   
63   data = dataInsert[:moStart.start()] + new_data + dataInsert[moEnd.end():]
64
65   f = open(filePath, 'w')
66   f.write(data)
67   f.close()
68     
69   
70
71 if __name__ == '__main__':
72   if len(sys.argv) != 3:
73     print 'Usage: %s <n_builds_to_show> <insert_into_filename> ' % (sys.argv[0])
74     sys.exit(1)
75   else:
76     filePath = sys.argv[2]
77     buildsToShow = int(sys.argv[1])
78     process(filePath, buildsToShow)