用ruby写的一个统计源代码行数的小程序,能够支持c,cc,cpp,h,hh,hpp,js,xsl,java.
注释只处理了 // 和 /* */ 其中/* */只考虑了嵌套2套的情况。可能还有些问题,以后有空再改。
用法
ruby count.rb xxx
xxx是源代码所在的目录名。结果是以.csv的形式输出,可以重定向到一个csv文件然后用excel打开。
如
ruby count.rb mydir > result.csv
#file name count.rb
def count(file)
blankLine = 0;
commentLine = 0;
codeLine = 0;
commentFlag = false;
oFile = File.open(file, "r")
oFile.each_line do |line|
line = line.strip
if commentFlag then
if(line.size == 0) then
blankLine += 1;
else
newline = line.gsub!(/\/\*.*\*\//, "")
if(newline) then
line = newline;
end
inx = line.index("*/");
if(inx == nil) then
commentLine += 1;
elsif(inx >= 0) then
commentFlag = false;
line = line[inx+2..line.size-1];
inx = line.index("/*");
if(inx == nil) then
codeLine += 1;$totalLine +=1;
elsif(inx == 0) then
commentFlag = true;
commentLine += 1;
elsif(inx > 0) then
commentFlag = true;
commentLine += 1;
code = line[0..inx -1].strip;
if(code.size > 0) then
codeLine += 1;$totalLine +=1;
end
end
end
end
else
if(line.index("//") == 0) then
commentLine += 1
else
newline = line.gsub!(/\/\*.*\*\//, "")
if(newline) then
commentLine += 1
line = newline.strip
if (line.size > 0) then
inx = line.index("/*");
if(inx == nil) then
codeLine += 1;$totalLine +=1;
elsif(inx == 0) then
commentFlag = true;
elsif(inx > 0) then
commentFlag = true;
code = line[0..inx -1].strip;
if(code.size > 0) then
codeLine += 1;$totalLine +=1;
end
end
end
else
if(line.size == 0) then
blankLine += 1
else
inx = line.index("/*");
if(inx == nil) then
codeLine += 1;$totalLine +=1;
elsif(inx == 0) then
commentFlag = true;
commentLine += 1;
elsif(inx > 0) then
commentFlag = true;
commentLine += 1;
code = line[0..inx -1].strip;
if(code.size > 0) then
codeLine += 1;$totalLine +=1;
end
end
end
end
end
end
end
oFile.close
printf("\"#{file}\",\"%d\",\"%d\",\"%d\"\n", blankLine, commentLine, codeLine);
end
if($*.size < 1) then
puts "ERROR: You need specify the source code dir"
puts "ruby codecout.rb {sourcedir}"
exit(-1);
end
$totalLine = 0
curDir = Dir.getwd
printf("\"FILE\",\"BLANK\",\"COMMENT\",\"CODE\"\n")
Dir.chdir($*[0])
Dir.glob(File.join("**","*.{c,cc,cpp,h,hh,hpp,js,xsl,java}")) {
|file| count(file)}
Dir.chdir(curDir)
#puts "total line is :", $totalLine
阅读(2042) | 评论(0) | 转发(0) |