Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 84 lines (74 sloc) 1.765 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
// Stepper package provides super simple steps handler and
// formatter.
//
// Copyright (C) 2011 by Krzysztof Kowalik <chris@nu7hat.ch>
package stepper

import (
"fmt"
"os"
)

// Possible steps
const (
done = iota
busy
fail
)

// Stepper contains information about current step's
// state and provides functions to operate on it.
type Stepper struct {
step string
}

// doStep performs transition to desired step.
func (s *Stepper) doStep(status int) {
var sstr string
switch status {
case done:
sstr = "\033[32mdone\033[0m"
case busy:
sstr = "\033[34mbusy\033[0m"
case fail:
sstr = "\033[31mfail\033[0m"
}
fmt.Fprintf(os.Stderr, "\r%s... %s", s.step, sstr)
}

// Fail terminates currently performed step (if any) with
// a failure notification. If second param is true, then
// it exits the program as well.
func (s *Stepper) Fail(msg string, exit bool) {
if s.step != "" {
s.doStep(fail)
fmt.Fprintf(os.Stderr, "\n\033[31m!!! %s\033[0m\n", msg)
if exit {
os.Exit(1)
}
}
}

// Ok terminates currently performed step (if any) with
// a success notification.
func (s *Stepper) Ok() {
if s.step != "" {
s.doStep(done)
s.step = ""
println()
}
}

// do setups step for specified message, executes passed operation
// and displays appropriate results.
func (s *Stepper) do(msg string, exit bool, fn func()(error)) {
s.step = msg
s.doStep(busy)
        if err := fn(); err != nil {
s.Fail(err.Error(), exit)
return
}
s.Ok()
}

// MustDo executes operation and exists when error occurs.
func (s *Stepper) MustDo(msg string, fn func()(error)) {
s.do(msg, true, fn)
}

// Do executes operation and lets program to keep going when
// error occurs.
func (s *Stepper) Do(msg string, fn func()(error)) {
s.do(msg, false, fn)
}
Something went wrong with that request. Please try again.