Class: CLI::UI::Progress

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/cli/ui/progress.rb

Constant Summary collapse

FILLED_BAR =

A Cyan filled block

"\e[46m"
UNFILLED_BAR =

A bright white block

"\e[1;47m"

Class Method Summary collapse

Instance Method Summary collapse

Methods included from T::Sig

sig

Constructor Details

#initialize(title = nil, width: Terminal.width, reporter: nil) ⇒ Progress

Returns a new instance of Progress.



79
80
81
82
83
84
# File 'lib/cli/ui/progress.rb', line 79

def initialize(title = nil, width: Terminal.width, reporter: nil)
  @percent_done = T.let(0, Numeric)
  @title = title
  @max_width = width
  @reporter = reporter
end

Class Method Details

.progress(title = nil, width: Terminal.width, &block) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/cli/ui/progress.rb', line 54

def progress(title = nil, width: Terminal.width, &block)
  bar = T.let(nil, T.nilable(Progress))
  CLI::UI::ProgressReporter.with_progress(mode: :progress) do |reporter|
    bar = Progress.new(title, width: width, reporter: reporter)
    print(CLI::UI::ANSI.hide_cursor)
    yield(bar)
  end
ensure
  puts(bar) if bar

  CLI::UI.raw do
    print(ANSI.show_cursor)
  end
end

Instance Method Details

#tick(percent: nil, set_percent: nil) ⇒ Object

Raises:

  • (ArgumentError)


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/cli/ui/progress.rb', line 97

def tick(percent: nil, set_percent: nil)
  raise ArgumentError, 'percent and set_percent cannot both be specified' if percent && set_percent

  @percent_done += percent || 0.01
  @percent_done = set_percent if set_percent
  @percent_done = [@percent_done, 1.0].min # Make sure we can't go above 1.0

  # Update terminal progress reporter with current percentage
  @reporter&.set_progress((@percent_done * 100).floor)

  print(self)

  printed_lines = @title ? 2 : 1
  print(CLI::UI::ANSI.previous_lines(printed_lines) + "\n")
end

#to_sObject



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/cli/ui/progress.rb', line 127

def to_s
  suffix = " #{(@percent_done * 100).floor}%".ljust(5)
  workable_width = @max_width - Frame.prefix_width - suffix.size
  filled = [(@percent_done * workable_width.to_f).ceil, 0].max
  unfilled = [workable_width - filled, 0].max

  title = CLI::UI.resolve_text(@title, truncate_to: @max_width - Frame.prefix_width) if @title
  bar = CLI::UI.resolve_text([
    FILLED_BAR + ' ' * filled,
    UNFILLED_BAR + ' ' * unfilled,
    CLI::UI::Color::RESET.code + suffix,
  ].join)

  [title, bar].compact.join("\n")
end

#update_title(new_title) ⇒ Object



120
121
122
# File 'lib/cli/ui/progress.rb', line 120

def update_title(new_title)
  @title = new_title
end