Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compatibility with non-tty devices #10

Merged
merged 2 commits into from Dec 16, 2011
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 34 additions & 2 deletions lib/progressbar.rb
Expand Up @@ -37,7 +37,6 @@ def initialize (title, total, out = STDERR)

private
def fmt_bar
bar_width = do_percentage * @terminal_width / 100
sprintf("|%s%s|",
@bar_mark * bar_width,
" " * (@terminal_width - bar_width))
Expand All @@ -63,6 +62,10 @@ def fmt_title
@title[0,(@title_width - 1)] + ":"
end

def bar_width
do_percentage * @terminal_width / 100
end

def convert_bytes (bytes)
if bytes < 1024
sprintf("%6dB", bytes)
Expand Down Expand Up @@ -138,6 +141,12 @@ def get_width
end

def show
tty? ? show_tty : show_no_tty
@previous_time = time_now
end

# Print output to a tty device.
def show_tty
arguments = @format_arguments.map {|method|
method = sprintf("fmt_%s", method)
send(method)
Expand All @@ -155,7 +164,25 @@ def show
@terminal_width += width - line.length + 1
show
end
@previous_time = time_now
end

# Print output to a non-terminal device, such as a log file.
# The terminal width is set to 80 columns.
def show_no_tty
@out.print("| " + elapsed + eol) and return if finished?

# Draw title the first time
if @last_bar_width.nil?
@last_bar_width = 0
@terminal_width = @terminal_width - fmt_title.size - elapsed.size - 4
@out.print(fmt_title + " |")
else
bar_width_change = bar_width - @last_bar_width
if bar_width_change > 0
@out.print(@bar_mark * bar_width_change)
@last_bar_width = bar_width
end
end
end

def show_if_needed
Expand Down Expand Up @@ -186,8 +213,13 @@ def time_now
end
end

def tty?
@out.tty?
end

public
def clear
return unless tty?
@out.print "\r"
@out.print(" " * (get_width - 1))
@out.print "\r"
Expand Down
16 changes: 15 additions & 1 deletion test.rb
@@ -1,5 +1,5 @@
require 'test/unit'
require 'lib/progressbar'
require File.expand_path('../lib/progressbar', __FILE__)

class ProgressBarTest < Test::Unit::TestCase
SleepUnit = 0.01
Expand Down Expand Up @@ -138,6 +138,20 @@ def test_delorean
}
pbar.halt
end

class StubbedTtyProgressBar < ProgressBar
def tty?; false; end
end

def test_non_tty
total = 1024 * 1024
pbar = StubbedTtyProgressBar.new("non-tty compatible", total)
0.step(total, 2**14) {|x|
pbar.set(x)
sleep(SleepUnit)
}
pbar.finish
end
end

class ReversedProgressBarTest < ProgressBarTest
Expand Down