github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/test/testdata/govet_custom_formatter/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "fmt" 6 "os" 7 ) 8 9 const ( 10 escape = "\x1b" 11 reset = escape + "[0m" 12 green = escape + "[32m" 13 14 minValue = 0.0 15 maxValue = 1.0 16 ) 17 18 // Bar is a progress bar. 19 type Bar float64 20 21 var _ fmt.Formatter = Bar(maxValue) 22 23 // Format the progress bar as output 24 func (h Bar) Format(state fmt.State, r rune) { 25 switch r { 26 case 'r': 27 default: 28 panic(fmt.Sprintf("%v: unexpected format character", float64(h))) 29 } 30 31 if h > maxValue { 32 h = maxValue 33 } 34 35 if h < minValue { 36 h = minValue 37 } 38 39 if state.Flag('-') { 40 h = maxValue - h 41 } 42 43 width, ok := state.Width() 44 if !ok { 45 // default width of 40 46 width = 40 47 } 48 49 var pad int 50 51 extra := len([]byte(green)) + len([]byte(reset)) 52 53 p := make([]byte, width+extra) 54 p[0], p[len(p)-1] = '|', '|' 55 pad += 2 56 57 positive := int(Bar(width-pad) * h) 58 negative := width - pad - positive 59 60 n := 1 61 n += copy(p[n:], green) 62 n += copy(p[n:], bytes.Repeat([]byte("+"), positive)) 63 n += copy(p[n:], reset) 64 65 if negative > 0 { 66 copy(p[n:len(p)-1], bytes.Repeat([]byte("-"), negative)) 67 } 68 69 _, _ = state.Write(p) 70 } 71 72 func main() { 73 var b Bar = 0.9 74 _, _ = fmt.Fprintf(os.Stdout, "%r", b) 75 }