Added mcollective 2.3.1 package
[packages/trusty/mcollective.git] / lib / mcollective / rpc / progress.rb
1 module MCollective
2   module RPC
3     # Class that shows a progress bar, currently only supports a twirling
4     # progress bar.
5     #
6     # You can specify a size for the progress bar if you want if you dont
7     # it will use the helper functions to figure out terminal dimensions
8     # and draw an appropriately sized bar
9     #
10     # p = Progress.new
11     # 100.times {|i| print p.twirl(i+1, 100) + "\r"};puts
12     #
13     #  * [ ==================================================> ] 100 / 100
14     class Progress
15       def initialize(size=nil)
16         @twirl = ['|', '/', '-', "\\", '|', '/', '-', "\\"]
17         @twirldex = 0
18
19         if size
20           @size = size
21         else
22           cols = Util.terminal_dimensions[0] - 22
23
24           # Defaults back to old behavior if it
25           # couldn't figure out the size or if
26           # its more than 60 wide
27           if cols <= 0
28             @size = 0
29           elsif cols > 60
30             @size = 60
31           else
32             @size = cols
33           end
34         end
35       end
36
37       def twirl(current, total)
38         # if the size is negative there is just not enough
39         # space on the terminal, return a simpler version
40         return "\r#{current} / #{total}" if @size == 0
41
42         if current == total
43           txt = "\r %s [ " % Util.colorize(:green, "*")
44         else
45           txt = "\r %s [ " % Util.colorize(:red, @twirl[@twirldex])
46         end
47
48         dashes = ((current.to_f / total) * @size).round
49
50         dashes.times { txt << "=" }
51         txt << ">"
52
53         (@size - dashes).times { txt << " " }
54
55         txt << " ] #{current} / #{total}"
56
57         @twirldex == 7 ? @twirldex = 0 : @twirldex += 1
58
59         return txt
60       end
61     end
62   end
63 end