当前位置: 首页 > 工具软件 > Ruby/Git > 使用案例 >

ruby脚本统计git管理的修改过的文件,得到每个author写的代码行数

逑彬炳
2023-12-01
#!/usr/bin/ruby 
#coding=utf-8
#执行脚本,输入git链接和需要统计的版本范围,就可得到此范围内每个author修改过的代码行数author_count
Encoding.default_external = 'UTF-8'


#获取当前路径并删掉换行符
path_prev = `echo %cd%`.chomp!
#puts "#{path_prev}"


#输入git clone链接
puts "input git clone url please:"
url = gets.chomp
`git clone #{url}`


#解析链接获得完整路径并修改工作目录到克隆目录
dirname = url.split('/')[-1].split('.')[0]
Dir::chdir( path_prev + "\\" + dirname)
#puts path_prev + "\\" + dirname
#输入统计范围(两个版本之间的修改条目)
range = gets.chomp
#取得指定范围内有过改动的文件名
filenames = `git diff --name-only #{range}`
#puts "#{filenames}"


chang_filenames = Array.new
#获取当前路径并删掉换行符(克隆目录)
path = `echo %cd%`.chomp!
#puts "#{path}"


#将文件名字符串推到数组里
filenames.each_line{|l| chang_filenames.push(l)}
#puts "#{chang_filenames}"


#通过字符串拼接获得完整路径
chang_filenames.map! {|item| "#{path}" + "\\" + item.chomp!}
#puts "#{chang_filenames}"


#从数组删除非源代码
chang_filenames.delete_if {|item|!((item.include?".c") || (item.include? ".cpp") || \
(item.include? ".h") || (item.include? ".js"))}
#puts "#{chang_filenames}"


#替换路径分隔符
for i in 0..chang_filenames.length-1
chang_filenames[i].gsub!('/','\\')
end
#puts "#{chang_filenames}"


blames = Array.new
authers = Array.new
j = -1;
#利用git blame得到修改过的文件的长字符串,放到数组
for i in 0..chang_filenames.length-1
blames[i] = `git blame #{chang_filenames[i]} #{range}`
blames[i].each_line{|l| if l[0,1]!='^' && (l[0,1]!='\r'||'n') then authers[j+=1]=(l.split[1].delete "(") end}
end
#删除数组中空元素
authers.delete(nil)
#puts "#{blames}"
#puts "#{authers},#{authers.length}"


basic = authers.uniq
#puts "#{basic},#{basic.length}"
#basic.each{|item| Hash[item => (item + "_num").to_i]}


#必须先初始化,双层循环里自加的时候需要
vars = Array.new(basic.length, 0)
#authers.each{|items| basic.each{|item| if item == items then vars end}}
for i in 0..basic.length-1
for j in 0..authers.length-1
if authers[j]==basic[i] then
vars[i] += 1
end
end
end
#puts "#{vars}"


k = -1;
name_count = Array.new
basic.each{|item|name_count[k+=1] = item + "_count = " + "#{vars[k]}"}
#结果
puts "#{name_count}"
 类似资料: