]> dev.renevier.net Git - syp.git/blob - openlayers/tools/mergejs.py
initial commit
[syp.git] / openlayers / tools / mergejs.py
1 #!/usr/bin/env python
2 #
3 # Merge multiple JavaScript source code files into one.
4 #
5 # Usage:
6 # This script requires source files to have dependencies specified in them.
7 #
8 # Dependencies are specified with a comment of the form:
9 #
10 #     // @requires <file path>
11 #
12 #  e.g.
13 #
14 #    // @requires Geo/DataSource.js
15 #
16 # This script should be executed like so:
17 #
18 #     mergejs.py <output.js> <directory> [...]
19 #
20 # e.g.
21 #
22 #     mergejs.py openlayers.js Geo/ CrossBrowser/
23 #
24 #  This example will cause the script to walk the `Geo` and
25 #  `CrossBrowser` directories--and subdirectories thereof--and import
26 #  all `*.js` files encountered. The dependency declarations will be extracted
27 #  and then the source code from imported files will be output to 
28 #  a file named `openlayers.js` in an order which fulfils the dependencies
29 #  specified.
30 #
31 #
32 # Note: This is a very rough initial version of this code.
33 #
34 # -- Copyright 2005-2008 MetaCarta, Inc. / OpenLayers project --
35 #
36
37 # TODO: Allow files to be excluded. e.g. `Crossbrowser/DebugMode.js`?
38 # TODO: Report error when dependency can not be found rather than KeyError.
39
40 import re
41 import os
42 import sys
43
44 SUFFIX_JAVASCRIPT = ".js"
45
46 RE_REQUIRE = "@requires:? (.*)\n" # TODO: Ensure in comment?
47 class SourceFile:
48     """
49     Represents a Javascript source code file.
50     """
51
52     def __init__(self, filepath, source):
53         """
54         """
55         self.filepath = filepath
56         self.source = source
57
58         self.requiredBy = []
59
60
61     def _getRequirements(self):
62         """
63         Extracts the dependencies specified in the source code and returns
64         a list of them.
65         """
66         # TODO: Cache?
67         return re.findall(RE_REQUIRE, self.source)
68
69     requires = property(fget=_getRequirements, doc="")
70
71
72
73 def usage(filename):
74     """
75     Displays a usage message.
76     """
77     print "%s [-c <config file>] <output.js> <directory> [...]" % filename
78
79
80 class Config:
81     """
82     Represents a parsed configuration file.
83
84     A configuration file should be of the following form:
85
86         [first]
87         3rd/prototype.js
88         core/application.js
89         core/params.js
90         # A comment
91
92         [last]
93         core/api.js # Another comment
94
95         [exclude]
96         3rd/logger.js
97
98     All headings are required.
99
100     The files listed in the `first` section will be forced to load
101     *before* all other files (in the order listed). The files in `last`
102     section will be forced to load *after* all the other files (in the
103     order listed).
104
105     The files list in the `exclude` section will not be imported.
106
107     Any text appearing after a # symbol indicates a comment.
108     
109     """
110
111     def __init__(self, filename):
112         """
113         Parses the content of the named file and stores the values.
114         """
115         lines = [re.sub("#.*?$", "", line).strip() # Assumes end-of-line character is present
116                  for line in open(filename)
117                  if line.strip() and not line.strip().startswith("#")] # Skip blank lines and comments
118
119         self.forceFirst = lines[lines.index("[first]") + 1:lines.index("[last]")]
120
121         self.forceLast = lines[lines.index("[last]") + 1:lines.index("[include]")]
122         self.include =  lines[lines.index("[include]") + 1:lines.index("[exclude]")]
123         self.exclude =  lines[lines.index("[exclude]") + 1:]
124
125 def run (sourceDirectory, outputFilename = None, configFile = None):
126     cfg = None
127     if configFile:
128         cfg = Config(configFile)
129
130     allFiles = []
131
132     ## Find all the Javascript source files
133     for root, dirs, files in os.walk(sourceDirectory):
134         for filename in files:
135             if filename.endswith(SUFFIX_JAVASCRIPT) and not filename.startswith("."):
136                 filepath = os.path.join(root, filename)[len(sourceDirectory)+1:]
137                 filepath = filepath.replace("\\", "/")
138                 if cfg and cfg.include:
139                     if filepath in cfg.include or filepath in cfg.forceFirst:
140                         allFiles.append(filepath)
141                 elif (not cfg) or (filepath not in cfg.exclude):
142                     allFiles.append(filepath)
143
144     ## Header inserted at the start of each file in the output
145     HEADER = "/* " + "=" * 70 + "\n    %s\n" + "   " + "=" * 70 + " */\n\n"
146
147     files = {}
148
149     order = [] # List of filepaths to output, in a dependency satisfying order 
150
151     ## Import file source code
152     ## TODO: Do import when we walk the directories above?
153     for filepath in allFiles:
154         print "Importing: %s" % filepath
155         fullpath = os.path.join(sourceDirectory, filepath).strip()
156         content = open(fullpath, "U").read() # TODO: Ensure end of line @ EOF?
157         files[filepath] = SourceFile(filepath, content) # TODO: Chop path?
158
159     print
160
161     from toposort import toposort
162
163     complete = False
164     resolution_pass = 1
165
166     while not complete:
167         order = [] # List of filepaths to output, in a dependency satisfying order 
168         nodes = []
169         routes = []
170         ## Resolve the dependencies
171         print "Resolution pass %s... " % resolution_pass
172         resolution_pass += 1 
173
174         for filepath, info in files.items():
175             nodes.append(filepath)
176             for neededFilePath in info.requires:
177                 routes.append((neededFilePath, filepath))
178
179         for dependencyLevel in toposort(nodes, routes):
180             for filepath in dependencyLevel:
181                 order.append(filepath)
182                 if not files.has_key(filepath):
183                     print "Importing: %s" % filepath
184                     fullpath = os.path.join(sourceDirectory, filepath).strip()
185                     content = open(fullpath, "U").read() # TODO: Ensure end of line @ EOF?
186                     files[filepath] = SourceFile(filepath, content) # TODO: Chop path?
187         
188
189
190         # Double check all dependencies have been met
191         complete = True
192         try:
193             for fp in order:
194                 if max([order.index(rfp) for rfp in files[fp].requires] +
195                        [order.index(fp)]) != order.index(fp):
196                     complete = False
197         except:
198             complete = False
199         
200         print    
201
202
203     ## Move forced first and last files to the required position
204     if cfg:
205         print "Re-ordering files..."
206         order = cfg.forceFirst + [item
207                      for item in order
208                      if ((item not in cfg.forceFirst) and
209                          (item not in cfg.forceLast))] + cfg.forceLast
210     
211     print
212     ## Output the files in the determined order
213     result = []
214
215     for fp in order:
216         f = files[fp]
217         print "Exporting: ", f.filepath
218         result.append(HEADER % f.filepath)
219         source = f.source
220         result.append(source)
221         if not source.endswith("\n"):
222             result.append("\n")
223
224     print "\nTotal files merged: %d " % len(files)
225
226     if outputFilename:
227         print "\nGenerating: %s" % (outputFilename)
228         open(outputFilename, "w").write("".join(result))
229     return "".join(result)
230
231 if __name__ == "__main__":
232     import getopt
233
234     options, args = getopt.getopt(sys.argv[1:], "-c:")
235     
236     try:
237         outputFilename = args[0]
238     except IndexError:
239         usage(sys.argv[0])
240         raise SystemExit
241     else:
242         sourceDirectory = args[1]
243         if not sourceDirectory:
244             usage(sys.argv[0])
245             raise SystemExit
246
247     configFile = None
248     if options and options[0][0] == "-c":
249         configFile = options[0][1]
250         print "Parsing configuration file: %s" % filename
251
252     run( sourceDirectory, outputFilename, configFile )