Skip to content

Instantly share code, notes, and snippets.

@nwwells
Created May 21, 2012 21:12
Show Gist options
  • Save nwwells/2764762 to your computer and use it in GitHub Desktop.
Save nwwells/2764762 to your computer and use it in GitHub Desktop.
A progress bar for Groovy
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
}
@nwwells
Copy link
Author

nwwells commented May 22, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment