* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / sample / coverage.rb
blob3f45e9fc980e419caaaf123d081a90550b64217e
1 require "coverage.so"
3 Coverage.start
5 ext = ENV["COVERUBY_EXT"] || ".cov"
6 accum = ENV["COVERUBY_ACCUM"]
7 accum = !accum || accum == "" || !(%w(f n 0).include?(accum[0]))
8 pwd = Dir.pwd
10 at_exit do
11   Dir.chdir(pwd) do
12     Coverage.result.each do |sfile, covs|
13       cfile = sfile + ext
15       writable = proc do |f|
16         File.writable?(f) || File.writable?(File.dirname(f))
17       end
18       unless writable[cfile]
19         cfile = cfile.gsub(File.PATH_SEPARATOR, "#")
20         next unless writable[cfile]
21       end
23       readlines = proc do |f|
24         File.read(f).force_encoding("ASCII-8BIT").lines.to_a
25       end
27       sources = (readlines[sfile] rescue [])
29       pcovs = []
30       if accum
31         pcovs = (readlines[cfile] rescue []).map.with_index do |line, idx|
32           if line[/^\s*(?:(#####)|(\d+)|-):\s*\d+:(.*)$/n]
33             cov, line = $1 ? 0 : ($2 ? $2.to_i : nil), $3
34             if !sources[idx] || sources[idx].chomp != line.chomp
35               warn("source file changed, ignoring: `#{ cfile }'")
36               break []
37             end
38             cov
39           else
40             p line
41             warn("coverage file corrupted, ignoring: #{ cfile }")
42             break []
43           end
44         end
45         unless pcovs.empty? || pcovs.size == covs.size
46           warn("coverage file changed, ignoring: `#{ cfile }'")
47           pcovs = []
48         end
49       end
51       open(cfile, "w") do |out|
52         covs.zip(sources, pcovs).each_with_index do |(cov, line, pcov), idx|
53           cov += pcov || 0 if cov
54           cov = (cov ? (cov == 0 ? "#####" : cov.to_s) : "-").rjust(9)
55           out.puts("%s:% 5d:%s" % [cov, idx + 1, line])
56         end
57       end
58     end
59   end
60 end