2010-01-19 59 views
1

我需要搜索路径中的所有*.c源文件以查找对*.h标头的引用以查找未使用的C标头。我写了一个ruby脚本,但感觉非常笨拙。使用ruby搜索路径文件中的文本

我创建一个包含所有C文件和一个包含所有H文件的数组的数组。 我遍历头文件数组。对于每个标题,我打开每个C文件并查找对标题的引用。

有没有更简单或更好的方法?

require 'ftools' 
require 'find' 

# add a file search 
class File 
    def self.find(dir, filename="*.*", subdirs=true) 
    Dir[ subdirs ? File.join(dir.split(/\\/), "**", filename) : File.join(dir.split(/\\/), filename) ] 
    end 
end 

files = File.find(".", "*.c", true) 
headers = File.find(".", "*.h", true) 

headers.each do |file| 

    #puts "Searching for #{file}(#{File.basename(file)})" 
    found = 0 

    files.each do |cfile| 
    #puts "searching in #{cfile}" 
    if File.read(cfile).downcase.include?(File.basename(file).downcase) 
     found += 1 
    end 
    end 

    puts "#{file} used #{found} times" 

end 

回答

3

前面已经指出的那样,你可以使用Dir#glob来简化您的文件查找。你也可以考虑切换你的循环,这意味着打开每个C文件一次,而不是每个H文件一次。

我会考虑的东西,如以下,跑了Ruby源在3秒钟内会:

# collect the File.basename for all h files in tree 
hfile_names = Dir.glob("**/*.h").collect{|hfile| File.basename(hfile) } 

h_counts = Hash.new(0) # somewhere to store the counts 

Dir.glob("**/*.c").each do |cfile| # enumerate the C files 
    file_text = File.read(cfile) # downcase here if necessary 
    hfile_names.each do |hfile| 
    h_counts[hfile] += 1 if file_text.include?(hfile) 
    end 
end 

h_counts.each { |file, found| puts "#{file} used #{found} times" } 

编辑:这不会列出任何C文件中未引用.h文件。要确定抓那些,哈希必须明确初始化:

h_counts = {} 
hfile_names.each { |hfile| h_counts[hfile] = 0 } 
+0

+1为具有相同的想法,也为细节代码。 – YOU 2010-01-20 03:38:34

1

要搜索*.c*.h文件,你可以使用Dir.glob

irb(main):012:0> Dir.glob("*.[ch]") 
=> ["test.c", "test.h"] 

要跨任何子目录中进行搜索,您可以通过**/*

irb(main):013:0> Dir.glob("**/*.[ch]") 
=> ["src/Python-2.6.2/Demo/embed/demo.c", "src/Python-2.6.2/Demo/embed/importexc.c", 
......... 
0

Rake API中的FileList对此非常有用。请注意列表大小的增长量超过了您需要处理的内存。 :)

http://rake.rubyforge.org/