cuke: make File.tail utility more robust
This commit is contained in:
parent
3726706608
commit
21c4691d40
@ -18,8 +18,15 @@ class OSRMError < StandardError
|
||||
private
|
||||
|
||||
def log_tail path, n
|
||||
File.open(path) do |f|
|
||||
return f.tail(n).map { |line| " > #{line}" }.join "\n"
|
||||
Dir.chdir TEST_FOLDER do
|
||||
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
|
||||
|
@ -1,24 +1,34 @@
|
||||
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)
|
||||
return [] if size==0
|
||||
buffer = 1024
|
||||
idx = (size - buffer).abs
|
||||
chunks = []
|
||||
lines = 0
|
||||
str = nil
|
||||
|
||||
begin
|
||||
seek(idx)
|
||||
chunk = read(buffer)
|
||||
lines += chunk.count("\n")
|
||||
chunks.unshift chunk
|
||||
idx -= buffer
|
||||
end while lines < ( n + 1 ) && pos != 0
|
||||
if size>buffer
|
||||
chunks = []
|
||||
lines = 0
|
||||
idx = size
|
||||
begin
|
||||
idx -= buffer # rewind
|
||||
if idx<0
|
||||
buffer += idx # adjust last read to avoid negative index
|
||||
idx = 0
|
||||
end
|
||||
seek(idx)
|
||||
chunk = read(buffer)
|
||||
chunk.gsub!(/\n+\Z/,"") if chunks.empty? # strip newlines from end of file (first chunk)
|
||||
lines += chunk.count("\n") # update total lines found
|
||||
chunks.unshift chunk # prepend
|
||||
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('')
|
||||
ary = tail_of_file.split(/\n/)
|
||||
lines_to_return = ary[ ary.size - n, ary.size - 1 ]
|
||||
rescue
|
||||
["Cannot read log file!"]
|
||||
# return last n lines of str
|
||||
lines = str.split("\n")
|
||||
lines.size>=n ? lines[-n,n] : lines
|
||||
end
|
||||
end
|
Loading…
Reference in New Issue
Block a user