Created
May 21, 2012 21:12
-
-
Save nwwells/2764762 to your computer and use it in GitHub Desktop.
A progress bar for Groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def progressBar = { max, closure -> | |
def template = "\r[%s] %s" | |
def progress = 0 | |
def percent = 0 | |
def barLength = 100 | |
def progressRatio = barLength / 100 | |
while (progress < max) { | |
def progressBuffer = new StringBuilder(); | |
def step = closure() | |
if (!step) step = 1 // default to stepping 1 | |
if (step < 0) continue // no progress | |
// else step is the amount of progress | |
progress = Math.min(max, progress + step) | |
percent = (int) ((progress / max) * 100) | |
progressLength = (int) ((progress / max) * (100 * progressRatio)) | |
progressBuffer.append('=' * progressLength) | |
progressBuffer.append(' ' * (barLength - progressLength)) | |
print String.format(template, progressBuffer, "${percent}%") | |
} | |
println '' | |
} | |
progressBar 10, { | |
sleep(500) | |
//randomly return -1, 0, or 1 | |
def result = new Random().nextInt(3) - 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't handle if the system terminal width is less than 100 (barLength). Unfortunately, such a luxury would require work that has already been done with the JCurses library.