Skip to content

Commit d667a32

Browse files
committed
Merge: console: add simple progress bar that refreshes itself
Example: ~~~nit import console var pb = new TermProgress(10, 0) for i in [1..10] do pb.update(i) end ~~~ Will display something like: ~~~sh 20% [==========================> ] ~~~ See documentation for more info about the progress bar. Signed-off-by: Alexandre Terrasa <alexandre@moz-code.org> Pull-Request: #1859 Reviewed-by: Jean Privat <jean@pryen.org>
2 parents a1f906a + 0d8f541 commit d667a32

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

lib/console.nit

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,3 +337,75 @@ redef class String
337337
# WARNING: SEE: `TermCharFormat`
338338
fun underline: String do return apply_format(normal.underline)
339339
end
340+
341+
# A dynamic progressbar displayable in console.
342+
#
343+
# Example:
344+
# ~~~nitish
345+
# var max = 10
346+
# var current = 0
347+
# var pb = new TermProgress(max, current)
348+
#
349+
# pb.display
350+
# for i in [current + 1 .. max] do
351+
# nanosleep(1, 0)
352+
# pb.update(i)
353+
# end
354+
#
355+
# print "\ndone"
356+
# ~~~
357+
#
358+
# Progressbar can accept metadata to display a small amount of data.
359+
#
360+
# Example with metadata:
361+
# ~~~nitish
362+
# var pb = new TermProgress(10, 0)
363+
# for i in [0..10] do
364+
# pb.update(i, "Step {i}")
365+
# end
366+
# ~~~
367+
class TermProgress
368+
369+
# Max value of the progress bar (business value).
370+
var max_value: Int
371+
372+
# Current value of the progress bar (business value).
373+
var current_value: Int
374+
375+
# Number of columns used to display the progress bar.
376+
var max_columns = 70 is writable
377+
378+
# Get the current percent value.
379+
fun current_percentage: Int do
380+
return current_value * 100 / max_value
381+
end
382+
383+
# Display the progress bar.
384+
#
385+
# `metadata` can be used to pass a small amount of data to display after
386+
# the progressbar.
387+
fun display(metadata: nullable String) do
388+
var percent = current_percentage
389+
var p = current_value * max_columns / max_value
390+
printn "\r{percent}% ["
391+
for i in [1..max_columns] do
392+
if i < p then
393+
printn "="
394+
else if i == p then
395+
printn ">"
396+
else
397+
printn " "
398+
end
399+
end
400+
printn "]"
401+
if metadata != null then printn " ({metadata})"
402+
end
403+
404+
# Update and display the progresssbar.
405+
#
406+
# See `display`.
407+
fun update(new_current: Int, metadata: nullable String) do
408+
current_value = new_current
409+
display(metadata)
410+
end
411+
end

0 commit comments

Comments
 (0)