代码行数统计工具(Ruby)

#保存扫描结果
class Result
def initialize
self.name = ''
self.count = 0
self.subResult = Array.new
end
attr_reader :name, :count, :subResult
attr_writer :name, :count, :subResult
end

#函数统计类
class LinesCounter
#dir 目标目录名
#fileFilter 文件过滤器,返回false表示过滤掉。
#lineFilter 行过滤器,返回alse表示过滤掉。
def initialize(dir, fileFilter, lineFilter)
raise "#{dir} 不是目录" unless File.directory?(dir)
@dir = dir
@fileFilter, @lineFilter = fileFilter, lineFilter
end

def count
r = Result.new
r.name = @dir
countDir("", @dir, r)
return r
end
private
def getPath(prefix, name)
prefix=='' ? name : prefix + File::SEPARATOR + name
end
def countDir(prefix, dirName, collect)
path = getPath(prefix, dirName)
c = 0
Dir.foreach(path) do
|x|
next if x =~/^(/.|/./.)$/
r = Result.new
r.name = x
subpath = getPath(path, x)
if File.directory?(subpath)
c += countDir(path, x, r)
else
next unless @fileFilter.call(x)
c += countFile(path, x, r)
end
collect.subResult.push(r)
end
collect.count = c
end
def countFile(prefix, fileName, collect)
path = getPath(prefix, fileName)
c = 0
File.foreach(path) do
|x|
next unless @lineFilter.call(x)
c = c + 1
end
collect.count = c
end
end

#打印结果
def printResult(r)
def printR(r, deep)
puts "#{"/t" * deep}#{r.name}(#{r.count})"
r.subResult.each do
|x|
printR(x, deep+1)
end
end
printR(r, 0)
end

lc = LinesCounter.new(ARGV[0],/
proc {|x| x =~ /^.*/.rb$/} , #只统计*.rb文件/
proc {|x| x !~ /^/s*(#|/s*$)/ }) #忽略注释和空行
#这里可以根据自己情况修改
#java可以这样写:
#lc = LinesCounter.new(ARGV[0],/
#proc {|x| x =~ /^.*/.java$/} ,/
#proc {|x| x !~ /^/s*(|/s*$)/ })
printResult(lc.count)

使用方法和运行结果:

D:/ruby>ruby lines.rb D:/ruby
D:/ruby(241)
a.rb(5)
exp.rb(130)
hello(1)
hello.rb(1)
lines.rb(69)
other(20)
pipe.rb(16)
scan.rb(4)
pipe.rb(16)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值