OpenLayers OpenLayers

root/trunk/openlayers/tools/mergejs.py

Revision 7353, 7.2 kB (checked in by tschaub, 3 months ago)

comment change only - since this breaks our doc building, removing the suggestion

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
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
91         [last]
92         core/api.js
93
94         [exclude]
95         3rd/logger.js
96
97     All headings are required.
98
99     The files listed in the `first` section will be forced to load
100     *before* all other files (in the order listed). The files in `last`
101     section will be forced to load *after* all the other files (in the
102     order listed).
103
104     The files list in the `exclude` section will not be imported.
105     
106     """
107
108     def __init__(self, filename):
109         """
110         Parses the content of the named file and stores the values.
111         """
112         lines = [line.strip() # Assumes end-of-line character is present
113                  for line in open(filename)
114                  if line.strip()] # Skip blank lines
115
116         self.forceFirst = lines[lines.index("[first]") + 1:lines.index("[last]")]
117
118         self.forceLast = lines[lines.index("[last]") + 1:lines.index("[include]")]
119         self.include =  lines[lines.index("[include]") + 1:lines.index("[exclude]")]
120         self.exclude =  lines[lines.index("[exclude]") + 1:]
121
122 def run (sourceDirectory, outputFilename = None, configFile = None):
123     cfg = None
124     if configFile:
125         cfg = Config(configFile)
126
127     allFiles = []
128
129     ## Find all the Javascript source files
130     for root, dirs, files in os.walk(sourceDirectory):
131         for filename in files:
132             if filename.endswith(SUFFIX_JAVASCRIPT) and not filename.startswith("."):
133                 filepath = os.path.join(root, filename)[len(sourceDirectory)+1:]
134                 filepath = filepath.replace("\\", "/")
135                 if cfg and cfg.include:
136                     if filepath in cfg.include or filepath in cfg.forceFirst:
137                         allFiles.append(filepath)
138                 elif (not cfg) or (filepath not in cfg.exclude):
139                     allFiles.append(filepath)
140
141     ## Header inserted at the start of each file in the output
142     HEADER = "/* " + "=" * 70 + "\n    %s\n" + "   " + "=" * 70 + " */\n\n"
143
144     files = {}
145
146     order = [] # List of filepaths to output, in a dependency satisfying order
147
148     ## Import file source code
149     ## TODO: Do import when we walk the directories above?
150     for filepath in allFiles:
151         print "Importing: %s" % filepath
152         fullpath = os.path.join(sourceDirectory, filepath)
153         content = open(fullpath, "U").read() # TODO: Ensure end of line @ EOF?
154         files[filepath] = SourceFile(filepath, content) # TODO: Chop path?
155
156     print
157
158     from toposort import toposort
159
160     complete = False
161     resolution_pass = 1
162
163     while not complete:
164         order = [] # List of filepaths to output, in a dependency satisfying order
165         nodes = []
166         routes = []
167         ## Resolve the dependencies
168         print "Resolution pass %s... " % resolution_pass
169         resolution_pass += 1
170
171         for filepath, info in files.items():
172             nodes.append(filepath)
173             for neededFilePath in info.requires:
174                 routes.append((neededFilePath, filepath))
175
176         for dependencyLevel in toposort(nodes, routes):
177             for filepath in dependencyLevel:
178                 order.append(filepath)
179                 if not files.has_key(filepath):
180                     print "Importing: %s" % filepath
181                     fullpath = os.path.join(sourceDirectory, filepath)
182                     content = open(fullpath, "U").read() # TODO: Ensure end of line @ EOF?
183                     files[filepath] = SourceFile(filepath, content) # TODO: Chop path?
184         
185
186
187         # Double check all dependencies have been met
188         complete = True
189         try:
190             for fp in order:
191                 if max([order.index(rfp) for rfp in files[fp].requires] +
192                        [order.index(fp)]) != order.index(fp):
193                     complete = False
194         except:
195             complete = False
196        
197         print   
198
199
200     ## Move forced first and last files to the required position
201     if cfg:
202         print "Re-ordering files..."
203         order = cfg.forceFirst + [item
204                      for item in order
205                      if ((item not in cfg.forceFirst) and
206                          (item not in cfg.forceLast))] + cfg.forceLast
207    
208     print
209     ## Output the files in the determined order
210     result = []
211
212     for fp in order:
213         f = files[fp]
214         print "Exporting: ", f.filepath
215         result.append(HEADER % f.filepath)
216         source = f.source
217         result.append(source)
218         if not source.endswith("\n"):
219             result.append("\n")
220
221     print "\nTotal files merged: %d " % len(files)
222
223     if outputFilename:
224         print "\nGenerating: %s" % (outputFilename)
225         open(outputFilename, "w").write("".join(result))
226     return "".join(result)
227
228 if __name__ == "__main__":
229     import getopt
230
231     options, args = getopt.getopt(sys.argv[1:], "-c:")
232    
233     try:
234         outputFilename = args[0]
235     except IndexError:
236         usage(sys.argv[0])
237         raise SystemExit
238     else:
239         sourceDirectory = args[1]
240         if not sourceDirectory:
241             usage(sys.argv[0])
242             raise SystemExit
243
244     configFile = None
245     if options and options[0][0] == "-c":
246         configFile = options[0][1]
247         print "Parsing configuration file: %s" % filename
248
249     run( sourceDirectory, outputFilename, configFile )
Note: See TracBrowser for help on using the browser.