3 This script has two main functions:
5 1) Combine several snippets to form Makefile.rules file
6 2) Split Makefile.rules file to the originnal snippets
10 snippet ::= legal? documentation rules
12 legal ::= comment* empty-comment empty-comment
13 documentation := comment*
20 Makefile.rules policies:
22 * All the parts of the Makefile.rules are ordered in the same order
23 as they are in snippets i.e. copyrights, documentations and rules.
25 * On the first line of each part of the Makefile.rules, there is
26 special mark of the form #OMK@<snippet file name><EOL>. This mark
27 is used for splitting modified Makefile.rules back to the
32 from optparse import OptionParser
40 snippetsDir = "snippets"
43 """List of text lines"""
44 def getDiff(self, other):
46 for i in range(len(self)):
47 if self[i] != other[i]:
48 s += (" Line %d differs!\n" % i)
49 s += " -"+self[i].rstrip() + "\n"
50 s += " +"+other[i].rstrip() + "\n"
59 def loadFromFile(self, fname):
60 """Loads itself from file."""
64 sys.stderr.write("Cannot open %s\n" % fname)
67 self.extend(f.readlines())
71 def __init__(self, fname = None):
72 """Initializes the snippet and if fname is given, reads it
75 self.legal = LineList()
77 self.code = LineList()
78 if fname: self.loadFromFile(fname)
80 def loadFromFile(self, fname):
81 """Loads snippet from file."""
85 self.readLines(f.readlines())
89 def readLines(self, lines):
90 """Parses the snippet given as a list and stores it in itself."""
91 currentPart = self.legal
95 if currentPart == self.legal:
96 if line.strip() == "#": counter += 1
98 if counter == 2: currentPart = self.doc
99 if line[0] != "#": currentPart = self.code
101 currentPart.append(line)
104 self.doc = self.legal
105 self.legal = LineList()
107 def asLinesList(self):
109 for type in ['legal', 'doc', 'code']:
110 for line in self.__dict__[type]:
115 return str(self.asLinesList())
118 s = "<Snippet: %s>" % self.name
121 def __cmp__(self, other):
122 ret = cmp(self.name, other.name)
123 if ret != 0: return ret
124 ret = cmp(self.legal, other.legal)
125 if ret != 0: return ret
126 ret = cmp(self.doc, other.doc)
127 if ret != 0: return ret
128 ret = cmp(self.code, other.code)
131 def __getitem__(self, key):
138 def getDiff(self, other):
139 return self.asLinesList().getDiff(other.asLinesList())
142 """Collection of snippets, where snippets can be accessed
143 individually by name (like dictionary) or sequentionaly in the
144 order they were added."""
146 self._snippets = dict()
149 def __iadd__(self, snippet):
150 assert isinstance(snippet, Snippet)
151 self._snippets[snippet.name] = snippet
152 self._order += [snippet]
155 def __getitem__(self, key):
156 return self._snippets[key]
158 def __contains__(self, item):
159 return item in self._snippets
162 return iter(self._order)
164 def __cmp__(self, other):
165 return cmp(self._snippets, other._snippets)
167 def loadFromFiles(self, fnames):
168 """Reads the snippets from several files and adds them to itself."""
172 def loadFromDict(self, snipDict):
173 """Adds snippets to itself from dictionary of LineLists."""
177 snip.readLines(snipDict[s])
180 def getDiff(self, other):
181 assert isinstance(other, Snippets)
184 if (snip != other[snip.name]):
185 s += "Snippet %s:\n" % snip.name
186 s += snip.getDiff(other[snip.name])
189 class MakefileRules(LineList):
191 self.snippets = Snippets()
192 self.rules = LineList()
195 """Combine self.snippets and produces self.rules"""
196 self.rules = LineList()
198 for type in ['legal', 'doc', 'code']:
199 for snip in self.snippets:
201 if len(lines) == 0: continue
202 firstLine = string.rstrip(lines[0])
203 self.rules += [firstLine.ljust(60)+" #OMK@%s\n"%snip.name]
204 self.rules += lines[1:]
205 #self.rules += ['a'] # test error
208 """Split self.rules to the original snippets in self.snippets."""
209 self.snippets = Snippets()
210 snipDict = self._getSnipDicts()
211 self.snippets.loadFromDict(snipDict)
213 def _getSnipDicts(self):
214 """Split self.rules to the original snippets, which are
215 returened as dictionary of LineLists."""
216 snipBegin = re.compile("^(.*)#OMK@(.*)$")
218 currentLinesList = None
220 for line in self.rules:
221 match = snipBegin.match(line)
223 line = match.group(1).rstrip() + "\n"
224 snipName = match.group(2)
225 if not snipName in snipDict:
226 snipDict[snipName] = LineList()
227 currentLinesList = snipDict[snipName]
229 currentLinesList.append(line);
233 def parseCommandLine():
234 parser = OptionParser(usage = """
235 %prog [-o FILE] snippet1 snippet2 ... build Makefile.rules from snippets
236 %prog [-o - ] -s Makfile.rules
238 parser.add_option("-s", "--split",
239 action="store", dest="split", default=False, metavar="RULES",
240 help="Split given Makefile.rules to the original snippets")
241 parser.add_option("-o", "--output",
242 action="store", dest="output", default=False, metavar="RULES",
243 help="Write Makefile.rules to file RULES")
244 parser.add_option("-a", "--all",
245 action="store_true", dest="all",
246 help="Rebuild all rules acording to rulesdef.py")
247 (options, args) = parser.parse_args()
250 def buildRules(fnames, output):
251 rules = MakefileRules()
252 rules.snippets.loadFromFiles(fnames)
255 rulesCheck = MakefileRules()
256 rulesCheck.rules = rules.rules
259 if rules.snippets != rulesCheck.snippets:
260 sys.stderr.write("Consistency error:\n")
261 diff = rules.snippets.getDiff(rulesCheck.snippets)
262 sys.stderr.write(diff)
265 if output: f = open(output,"w+")
267 f.writelines(rules.rules)
270 def splitRules(rulesFN, output):
271 rules = MakefileRules()
272 rules.rules.loadFromFile(rulesFN)
275 rulesCheck = MakefileRules()
276 rulesCheck.snippets = rules.snippets
279 # The comparsion is not that simple. The order of rules might be
281 # if rules.rules != rulesCheck.rules:
282 # sys.stderr.write("Consistency error:\n")
283 # diff = rules.rules.getDiff(rulesCheck.rules)
284 # sys.stderr.write(diff)
287 for snip in rules.snippets:
290 if output == "-": f = sys.stdout
291 else: f = open(snip.name, "w+")
292 f.writelines(snip.asLinesList())
297 os.chdir(snippetsDir)
298 for rules in rulesdef.rules:
299 print 'Building rules: %s' % rules
300 outputDir = os.path.join(sys.path[0], rulesDir, rules)
301 if not os.path.isdir(outputDir): os.makedirs(outputDir)
302 buildRules(rulesdef.rules[rules], os.path.join(outputDir, 'Makefile.rules'))
305 (options, args) = parseCommandLine()
309 splitRules(options.split, options.output)
311 buildRules(args, options.output)
314 if __name__ == "__main__": main()