File: progressbar.rb

package info (click to toggle)
libprogressbar-ruby 0.2-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 40 kB
  • ctags: 17
  • sloc: ruby: 112; makefile: 44
file content (114 lines) | stat: -rw-r--r-- 2,298 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#
# Ruby/ProgressBar - a text progress bar library
#
# Copyright (C) 2001 Satoru Takabayashi <satoru@namazu.org>
#     All rights reserved.
#     This is free software with ABSOLUTELY NO WARRANTY.
#
# You can redistribute it and/or modify it under the terms
# of Ruby's licence.
#

class ProgressBar
  VERSION = "0.2"

  def initialize (title, total, out = STDERR)
    @title = title
    @total = total
    @out = out
    @current = 0
    @previous = 0
    @is_finished = false
    @start_time = Time.now
    @bar = "oooooooooooooooooooooooooooooooooooooooo"
    show_progress
  end

  def inspect
    "(ProgressBar: #{@current}/#{@total})"
  end

  def format_time (t)
    t = t.to_i
    sec = t % 60
    min  = (t / 60) % 60
    hour = t / 3600
    sprintf("%02d:%02d:%02d", hour, min, sec);
  end

  # ETA stands for Estimated Time of Arrival.
  def eta
    if @current == 0
      "ETA:  --:--:--"
    else
      elapsed = Time.now - @start_time
      eta = elapsed * @total / @current - elapsed;
      sprintf("ETA:  %s", format_time(eta))
    end
  end

  def elapsed
    elapsed = Time.now - @start_time
    sprintf("Time: %s", format_time(elapsed))
  end
  
  def time
    if @is_finished then elapsed else eta end
  end

  def eol
    if @is_finished then "\n" else "\r" end
  end

  def bar (percentage)
    len = percentage * @bar.length / 100
    sprintf("|%.*s%*s|", len, @bar, @bar.length - len, "")
  end

  def show (percentage)
    @out.printf("%-14s %3d%% %s %s%s", 
		@title + ":", 
		percentage, 
		bar(percentage),
		time,
		eol)
  end

  def show_progress
    if @total.zero?
      cur_percentage = 100
      prev_percentage = 0
    else
      cur_percentage  = (@current  * 100 / @total).to_i
      prev_percentage = (@previous * 100 / @total).to_i
    end

    if cur_percentage > prev_percentage || @is_finished
      show(cur_percentage)
    end
  end

  public
  def finish
    @current = @total
    @is_finished = true
    show_progress
  end

  def set (count)
    if count < 0 || count > @total
      raise "invalid count: #{count} (total: #{total})"
    end
    @current = count
    show_progress
    @previous = @current
  end

  def inc (step = 1)
    @current += step
    @current = @total if @current > @total
    show_progress
    @previous = @current
  end
end