After your Flex project gets a bit large you’re inevitably going to start forgetting to remove old, unused code.. Included in the Flex 4 SDK is an updated version of the SWF Tool’s swfdump application. It’s a swf disassembler that can help you in some fun ways. One of which is finding orphaned classes in your application. Here’s a little script to help you do this:
If you haven’t already, as a flex developer you should already have the FLEX_HOME environment variable defined in your bash profile. For an example on a mac see http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x
Create a directory to play in
mkdir MyProjectTemp
cd MyProjectTemp
Get a fresh copy of your application (skip this and the next step if you just want to use a swf you already have)
svn checkout https://path-to-your project/
Compile it (hopefully you’re using a tool like Maven or Ant)
mvn clean install OR ant ./build/build.xml
Execute swfdump from its home in the FlexSDK folder defined by FLEX_HOME.
Note: the “-abc” is important here (stands for Actionscript Byte Code). You need this level of detail to search for class names in the following steps.
java -ea -Dapplication.home="$FLEX_HOME" -Xms32m -Xmx384m -jar "$FLEX_HOME/lib/swfdump.jar" -abc ./buildOutpuTarget/MyProject.swf > MyProjectSwfDump
Now we use some bash trickery to output the filenames of all the Actionscript and MXML files in our project for ONLY classes meant to be compiled. This should EXCLUDE test cases (usually under /src/test/…). Those are not typically included in your build and will just make noise in our search.
NOTE: the different “>” and “>>” are important so you don’t overwrite your find output every time.
find ./MyCommonLibraryProject/src/main/flex -name "*.as" -exec basename {} .as \; > classes
find ./MyCommonLibraryProject/src/main/flex -name "*.mxml" -exec basename {} .mxml \; >> classes
find ./MyMainProject/src/main/flex -name "*.as" -exec basename {} .as \; >> classes
find ./MyMainProject/src/main/flex -name "*.mxml" -exec basename {} .mxml \; >> classes
Now we have a file called “classes” that is a list of all the filenames (without extensions) in our projects. So now some more bash fun to compare the swf dump with our file list.
for class in $(<classes) ; do grep -q $class MyProjectSwfDump || echo $class >> UnusedClassNames ; done
Now you have a file called UnusedClassNames that is a list of all class names that could not be found in your compiled application.
Happy Garbage Hunting!