Refactor Actionscript package names (move refactoring)

Comprehensive refactoring is missing in Flex Builder: currently you can only rename local variables and class members, but not package names.  So if you move a folder, you have to manually edit all the package names.  Lame.

This python script fixes all package names in a root source folder.  It assumes the folders are the correct package names.

! /usr/bin/env python

""" Repairs actionscript package names, since Flex Builder is too crummy to do this simple task. """ import os.path, string, sys, glob, re

pattern = re.compile('^\spackage .')

if len(sys.argv) == 1: print "Usage: fixAS3PackageNames.py [src folder]" print "Repairs actionscript source package names" sys.exit(0)

path = sys.argv[1]

path = os.path.join(path, "")

def packageFromFileName (fileName): tokens = fileName.strip().split("/")[0:-1] return string.join(tokens, ".")

fileSet = set()

for root, dirs, files in os.walk(path): for fileName in files: if fileName.endswith(".as"): fileSet.add( os.path.join( root[len(path):], fileName ))

for fileName in fileSet: correctedFileName = os.path.join(path, fileName) f = open(correctedFileName, 'r') lines = f.readlines() f.close()

write = False
for i in range(len(lines)):
    line = lines[i]
    if pattern.match(line):
        packageString = line.split("package")[-1].strip()
        filePackage = packageFromFileName(fileName)

        if packageString != filePackage:
            write = True
            lines[i] = "package " + filePackage

            if line.find("{") >= 0:
                lines[i] = lines[i] + "{"
            if line[-1] == "\n":
                lines[i] = lines[i] + "\n"
                print fileName +": " + packageString + " -> " + filePackage
        break
if write:
    f = open(correctedFileName, 'w')
    for line in lines:
        f.write(line)
    f.close()

This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Refactor Actionscript package names (move refactoring)

  1. Mike G. says:

    This is just what I’m looking for, but for someone not familiar with python or how to even run python script, would you be so kind as to explain how you go about using this fantastic piece of usefulness?

    It’d be greatly appreciated!

  2. Dion says:

    1) Install Python.
    2) Copy the code above to a file called fixPackages.py
    3) In a terminal (or dos prompt, for Windows run cmd.exe), go to the directory where you saved fixPackages.py, and type fixPackages.py .

    Replace with the actionscript source directory.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>