942464472c72cf6331bc94850f118c2581987641
[plcapi.git] / migrations / extract-views.py
1 #!/usr/bin/env python3
2
3 import sys
4 import re
5
6 class Schema:
7
8     def __init__ (self,input,output=None):
9         self.input=input
10         self.output=output
11
12     # left part is non-greedy
13     comment = re.compile("(.*?)--.*")
14     spaces = re.compile("^\s+(\S.*)")
15     view = re.compile("(?i)\s*create\s+(or\s+replace)?\s+view.*")
16
17     def parse (self):
18         if self.output:
19             outfile = open(self.output, "a")
20         else:
21             outfile = sys.stdout
22         with open(self.input) as feed:
23             contents = feed.read()
24         parts = contents.split(";")
25         for part in parts:
26             # normalize: remove comments, linebreaks, trailing spaces..
27             normalized=''
28             lines=part.split('\n');
29             out_lines = []
30             for line in lines:
31                 # remove comment
32                 match = Schema.comment.match(line)
33                 if match:
34                     line = match.group(1)
35                 out_lines.append(line)
36             # get them together
37             out_line = " ".join(out_lines)
38             # remove trailing spaces
39             match = Schema.spaces.match(out_line)
40             if match:
41                 out_line = match.group(1)
42             match = Schema.view.match(out_line)
43             if match:
44                 outfile.write("{};\n".format(out_line))
45         if outfile != sys.stdout:
46             outfile.close()
47
48 if __name__ == '__main__':
49     if len(sys.argv) not in [2, 3]:
50         print('Usage:', sys.argv[0], 'input [output]')
51         sys.exit(1)
52     input = sys.argv[1]
53     try:
54         output = sys.argv[2]
55     except:
56         output = None
57     Schema(input, output).parse()
58