Wednesday, October 1st, 2008

Finding those trailing commas

Category: Tip, Utility

Dan Fabulich got bitten by the “trailing comma” issue one too many times, so he created a script to solve his problem:

“How many thousands of developer hours have been lost to random IE bugs like this?” I asked myself. I decided that there had to be a good way to detect this problem in an automated way, without firing up a copy of IE and running a full test suite.

It turns out that these and other syntax errors can be detected automatically from the Windows command line, using the Windows Scripting Host (WSH). On Windows XP and higher, the command-line tool “cscript.exe” can be used to run JavaScript (ahem, JScript) headlessly (outside of any browser).

Just create a file called “wsh-parser.js” like this:

javascript

  1. var fso = new ActiveXObject( "Scripting.FileSystemObject" );
  2.  
  3. function parse(fname) {
  4.     var file = fso.OpenTextFile( fname, 1 );
  5.     ret = file.ReadAll();
  6.     file.Close();
  7.     try {
  8.         eval("(function(){\n"+ret+"\n});");
  9.     } catch (e) {
  10.         WScript.Echo("Syntax error parsing " + fname);
  11.         WScript.Echo("  " + e.message);
  12.     }
  13. }
  14.  
  15. function findJavaScript(folder) {
  16.     for (var fc = new Enumerator(folder.files); !fc.atEnd(); fc.moveNext()) {
  17.         var file=fc.item();
  18.         if (/.js$/.test(file.Name)) {
  19.             parse(file);
  20.         }
  21.     }
  22.     for (var fc = new Enumerator(folder.subfolders); !fc.atEnd(); fc.moveNext()) {
  23.         var subfolder = fc.item();
  24.         if (subfolder.Name == ".svn") continue; // ignore .svn folders
  25.         findJavaScript(subfolder);
  26.     }
  27. }
  28.  
  29. var rootPath = "src/main/javascript";
  30. var rootFolder = fso.GetFolder(rootPath);
  31.  
  32. findJavaScript(rootFolder);

Other tools will help you hunt this down too, and I am sure some of you have Perl/Ruby/Python one liners to do the same ;)

Posted by Dion Almaer at 5:37 am
Comment here

+++--
3.3 rating from 8 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.