Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
Usage: fixpackages SRC_DIR [SRC_DIR ...]
Fix actionscript packages by updating the 'package <name>' statement in
applicable files and updating any import statements which reference the
old package.
To use:
- Move files to their new locations (eg, src/old/ to src/new/
- Run ./fixpackages src/ test/ will have:
package old { ... }
changed to:
package new { ... }
And test/ will have:
import old.Foo;
changed to:
import new.Foo;
from __future__ import with_statement
import os
from os import path
import sys
import re
def warn(msg):
sys.stderr.write(msg + "\n")
def log(msg):
sys.stderr.write(msg + "\n")
def fixpackage(prefix, file, dry_run=True):
fullpath = path.join(prefix, file)
with open(fullpath) as f:
data =
actual_package_match ="package +([a-zA-Z0-9_.]+)", data)
if not actual_package_match:
warn("Package not found in %r - ignoring." %(fullpath, ))
return (None, None)
actual_package =
correct_package = ".".join(file.split("/")[:-1])
if not dry_run and actual_package != correct_package:
data = re.sub(,
"package " + correct_package, data, count=1)
with open(fullpath + ".tmp", "w") as f:
os.rename(fullpath + ".tmp", fullpath)
return (actual_package, correct_package)
def fiximports(renames, file):
with open(file) as f:
data =
num_fixed = [0]
def do_sub(match):
impt =
if impt in renames:
prefix =
num_fixed[0] += 1
return prefix + renames[impt]
fixed_data = re.sub("([ \t]*import +)([a-zA-Z0-9_.]+)", do_sub, data)
if fixed_data != data:
with open(file + ".tmp", "w") as f:
os.rename(file + ".tmp", file)
return num_fixed[0]
def main():
dry_run = False
renames = {}
dirs = [ dir + (not dir.endswith("/") and "/" or "")
for dir in sys.argv[1:] ]
if len(dirs) == 0:
print __doc__
for dir in dirs:
for root, _, files in os.walk(dir):
for file in files:
if file.endswith(".as"):
file_name = file.split(".")[0]
file = path.join(root, file)
file = file[len(dir):]
(old, new) = fixpackage(dir, file, dry_run)
if old is None or old == new:
renames[old + "." + file_name] = new + "." + file_name
log("Changing package %s --> %s in %s%s"
%(old, new, dir, file))
for dir in (not dry_run and dirs or []):
for root, _, files in os.walk(dir):
for file in files:
if file.endswith(".as") or file.endswith(".mxml"):
count = fiximports(renames, path.join(root, file))
if count > 0:
log("Fixed %d imports in %s"
%(count, path.join(root, file)))
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment