Simple JavaScript dependency analysis
One of the most glorious forms of procrastination for a programmer is developing tools that automate menial and repetitive tasks. I've wasted lots of time on little Python scripts that generate Java classes, remove unused rules from CSS stylesheets, and all kinds of other unnecessary stuff.
My latest invention is a program that does a simple analysis of JavaScript files to determines the order in which they should be concatenated.
Concatenating multiple JS files is a simple optimisation that reduces the number of HTTP requests between a browser and a server. However, they need to be concatenated in the right order so that objects and functions are defined before they are referenced.
The program works by scanning JSLint /*global ...*/ declarations to determine the JavaScript variables referenced by each script. It then looks in all other scripts to figure out which one defines each variable. This results in a dependency graph that maps each file to each of its dependencies.
Once the dependencies are known, the program determines the concatenation order by inserting files into a list, one at a time. Each file is inserted after all its dependencies. If any of the previously inserted files references the newly inserted file, they are removed and reinserted in the same way.
The insertion algorithm seems very inefficient, and possibly isn't even correct! (I don't remember anything about graph theory.) But it seems to work for my Pac-Man project, which is split into 32 interdependent files.
Here's the program, and a Makefile that shows how it's used: