cuke: make File.tail utility more robust

This commit is contained in:
Emil Tin 2014-06-08 12:06:34 +02:00
parent 3726706608
commit 21c4691d40
2 changed files with 35 additions and 18 deletions

View File

@ -18,8 +18,15 @@ class OSRMError < StandardError
private private
def log_tail path, n def log_tail path, n
File.open(path) do |f| Dir.chdir TEST_FOLDER do
return f.tail(n).map { |line| " > #{line}" }.join "\n" expanded = File.expand_path path
if File.exists? expanded
File.open(expanded) do |f|
return f.tail(n).map { |line| " #{line}" }.join "\n"
end
else
return "File '#{expanded} does not exist!"
end
end end
end end
end end

View File

@ -1,24 +1,34 @@
class File class File
#read last n lines of a file. useful for getting last part of a big log file. # read last n lines of a file (trailing newlines are ignored)
def tail(n) def tail(n)
return [] if size==0
buffer = 1024 buffer = 1024
idx = (size - buffer).abs str = nil
if size>buffer
chunks = [] chunks = []
lines = 0 lines = 0
idx = size
begin begin
idx -= buffer # rewind
if idx<0
buffer += idx # adjust last read to avoid negative index
idx = 0
end
seek(idx) seek(idx)
chunk = read(buffer) chunk = read(buffer)
lines += chunk.count("\n") chunk.gsub!(/\n+\Z/,"") if chunks.empty? # strip newlines from end of file (first chunk)
chunks.unshift chunk lines += chunk.count("\n") # update total lines found
idx -= buffer chunks.unshift chunk # prepend
end while lines < ( n + 1 ) && pos != 0 end while lines<(n) && idx>0 # stop when enough lines found or no more to read
str = chunks.join('')
else
str = read(buffer)
end
tail_of_file = chunks.join('') # return last n lines of str
ary = tail_of_file.split(/\n/) lines = str.split("\n")
lines_to_return = ary[ ary.size - n, ary.size - 1 ] lines.size>=n ? lines[-n,n] : lines
rescue
["Cannot read log file!"]
end end
end end