github.com/be-b10g/golangci-lint@v1.17.2/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  
    15  // Bar is a progress bar.
    16  type Bar float64
    17  
    18  var _ fmt.Formatter = Bar(1.0)
    19  
    20  // Format the progress bar as output
    21  func (h Bar) Format(state fmt.State, r rune) {
    22  	switch r {
    23  	case 'r':
    24  	default:
    25  		panic(fmt.Sprintf("%v: unexpected format character", float64(h)))
    26  	}
    27  
    28  	if h > 1.0 {
    29  		h = 1.0
    30  	}
    31  
    32  	if h < 0.0 {
    33  		h = 0.0
    34  	}
    35  
    36  	if state.Flag('-') {
    37  		h = 1.0 - h
    38  	}
    39  
    40  	width, ok := state.Width()
    41  	if !ok {
    42  		// default width of 40
    43  		width = 40
    44  	}
    45  
    46  	var pad int
    47  
    48  	extra := len([]byte(green)) + len([]byte(reset))
    49  
    50  	p := make([]byte, width+extra)
    51  	p[0], p[len(p)-1] = '|', '|'
    52  	pad += 2
    53  
    54  	positive := int(Bar(width-pad) * h)
    55  	negative := width - pad - positive
    56  
    57  	n := 1
    58  	n += copy(p[n:], green)
    59  	n += copy(p[n:], bytes.Repeat([]byte("+"), positive))
    60  	n += copy(p[n:], reset)
    61  
    62  	if negative > 0 {
    63  		copy(p[n:len(p)-1], bytes.Repeat([]byte("-"), negative))
    64  	}
    65  
    66  	_, _ = state.Write(p)
    67  }
    68  
    69  func main() {
    70  	var b Bar = 0.9
    71  	_, _ = fmt.Fprintf(os.Stdout, "%r", b)
    72  }