Created
November 15, 2011 12:38
-
-
Save jasonmadigan/1366987 to your computer and use it in GitHub Desktop.
Fix trailing JavaScript commas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use Getopt::Long; | |
my $verbose; | |
my $overwrite; | |
my $renamenew; | |
my $append; | |
my $help; | |
GetOptions( | |
'verbose' => \$verbose, | |
'overwrite' => \$overwrite, | |
'renamenew' => \$renamenew, | |
'appendstring:s' => \$append, | |
'help' => \$help | |
); | |
if($help) { | |
print <<ENDHELP; | |
Syntax: fix_trailing_comma.pl [options] [files] | |
Files may be specified on the command-line or piped in: | |
find . -name *.js | fix_trailing_comma | |
fix_trailing_comma < ./list_of_files.txt | |
Command-line options: | |
--verbose, -v Reports the number of problems corrected in each file | |
--overwrite, -o Does not make a backup copy of the file before changing | |
--renamenew, -r Renames the new file rather than the old file | |
Ignored if --overwrite is set | |
--appendstring, -a Changes the string appended to backup/new filenames | |
Ignored if --overwrite is set | |
--help, -h Shows this help information | |
ENDHELP | |
exit(0); | |
} | |
if($append eq '') { | |
if($renamenew) { $append = "FIXED"; } | |
else { $append = "OLD"; } | |
} | |
@filelist = ($#ARGV >= 0) ? @ARGV : <>; | |
foreach $file (@filelist) { | |
chomp $file; | |
my $oldfile = $file; | |
my $newfile = $file; | |
if(!$overwrite && $renamenew) { | |
if($newfile =~ /\.js$/) { $newfile =~ s/(.*)\.js/\1_$append.js/; } | |
else { $newfile = $newfile . "_$append"; } | |
} else { | |
if($oldfile =~ /\.js$/) { $oldfile =~ s/(.*)\.js/\1_$append.js/; } | |
else { $oldfile = $oldfile . "_$append"; } | |
} | |
unless(open(FILE, "<", $file)){ | |
warn "Unable to read $file: $!\n"; | |
next; | |
} | |
my $jsfile; | |
{ | |
local $/; | |
$jsfile = <FILE>; | |
} | |
close(FILE); | |
my $originalfile = $jsfile unless $overwrite; | |
my $count = $jsfile =~ s#^((?:[^/\n]|/(?!/))*),((?:\s*|//.*$|/\*(?:[^*]|\*(?!/))*\*/)*\s*[}\]])#$1$2#mg; | |
if(!$count) { $count = 0; } | |
if(!$overwrite) { | |
open(OLDFILE, ">", $oldfile) or die "Unable to open $oldfile for writing: $!\n"; | |
print OLDFILE $originalfile; | |
close OLDFILE; | |
} | |
open(NEWFILE, ">", $newfile) or die "Unable to open $newfile for writing: $!\n"; | |
print NEWFILE $jsfile; | |
close NEWFILE; | |
print "[*] $count total problems fixed in $file\n" if $verbose; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment