Javascript Code Beautifier Written by Min
As part of my work, I must inspect some javascript code in the released live.com platform. Maybe for bandwidth concern, the code is reformatted so as not easy to read and understand. All lines are joined into one single line. It will be a nightmare if the file is rather long. The visual studio doesn't provide a format function for javascript file.
Min is very warm-hearted on that. She made a tool in perl within quite short time. It performs perfect.
The source code is posted below.
我的工作会涉及到读取live.com上面的javascript源文件。而这些发布版本的文件格式非常难读,所有的内容都写进了一行中。我需要一个工具来进行重新格式化。敏帮我写了一个小工具,很好用。在处理一些复杂的与语法相关的格式时(例如字符串中包含了大括号)会出一些问题,不过,要解决这样的问题则需要花一些功夫了。根据目前的使用,我还是非常满意的。谢谢敏。^^
##
# Author: ZHANG Min
# Description: format javascript
# Copyright: (C) 2007 ZHANG Min
##
use strict;
undef $/;
# input file name, output file name
my $inname = "input.js";
my $outname = $inname.".out";
open IN, "<$inname" or die "cannot open file $inname";
my $lines;
$lines = <IN>;
close IN;
my $outlines;
my $tabnum = 0;
my $i;
$lines =~ s!\n!!g;
$lines =~ s!;!;\n!g;
$lines =~ s!\{!\n\{\n!g;
$lines =~ s!\}!\n\}\n!g;
$lines =~ s!\n\n\}!\n\}!g;
$lines =~ s!\}\n;\n!\};\n!g;
$lines =~ s!return \n\{\n(.*?)\n\}!return \{$1\}!g;
$lines =~ s!(for .*?;)\n(.*?;)\n!$1$2!sg;
$lines =~ s!(for\(.+?;)\n(.+?;)\n!$1$2!sg;
$lines =~ s!(case.*?);\nbreak;\n!$1;break;\n!sg; #print $lines;
my @array = split ('\n',$lines);
for (my $i = 0; $i <@array; $i++)
{
my $theline = $array[$i];
if (($theline =~ m!\}!) && !($theline =~ m!\{!))
{
$tabnum --;
}
for (my $j = 0; $j < $tabnum; $j++)
{
$outlines .="\t";
}
$outlines .=$theline."\n";
if (($theline =~ m!\}!) && ($theline =~ m!\{!))
{
$tabnum --;
}
if ($theline =~ m!\{!)
{
$tabnum ++;
}
}
open OUT, ">$outname" or die "cannot open output $outname";
print OUT $outlines;
close OUT;
print "finished. press any key to exit.\n";
getc();





0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home