Created
November 11, 2013 17:12
-
-
Save mccutchen/7416724 to your computer and use it in GitHub Desktop.
Script used to refactor the style of requirejs imports we were using.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import re | |
| example = """define([ | |
| 'jquery', | |
| 'underscore', | |
| 'backbone', | |
| 'lib/db_session', | |
| 'collections/step_templates', | |
| 'collections/tags', | |
| 'models/pattern_template' | |
| ], function($, _, Backbone, DBSession, StepTemplates, Tags, PatternTemplate) { | |
| var hello = 'world'; | |
| """ | |
| pattern = re.compile( | |
| r"""define\(\[([^\]]+).*\], function\(([^\)]+)\) {(.*)""", | |
| re.M | re.S) | |
| def refactor(match): | |
| deps, decls, rest = match.groups() | |
| deps = process_deps(deps) | |
| decls = process_decls(decls) | |
| assert len(deps) == len(decls), (deps, decls) | |
| new_decls = refactor_decls(deps, decls) | |
| return """define(function(require) { | |
| var %s;%s""" % (new_decls, rest) | |
| def process_deps(deps): | |
| return [x.strip().strip("',") for x in deps.splitlines() | |
| if x.strip() and not x.strip().startswith('//')] | |
| def process_decls(decls): | |
| return [x.strip().strip(',') for x in decls.split(',')] | |
| def refactor_decls(deps, decls): | |
| new_decls = ["{} = require('{}')".format(*x) for x in zip(decls, deps)] | |
| result = [] | |
| for i, decl in enumerate(new_decls): | |
| if i > 0: | |
| decl = ' ' + decl | |
| result.append(decl) | |
| return ',\n'.join(result) | |
| def iter_js_files(root='.'): | |
| for dirpath, _, filenames in os.walk('.'): | |
| for filename in filenames: | |
| if filename.endswith('.js'): | |
| yield os.path.join(dirpath, filename) | |
| def main(): | |
| for path in iter_js_files(): | |
| src = open(path).read() | |
| match = pattern.match(src) | |
| if match: | |
| try: | |
| new_src = refactor(match) | |
| except Exception, e: | |
| print 'Error processing {}: {}'.format(path, e) | |
| else: | |
| open(path, 'w').write(new_src) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment