github.com/demonoid81/containerd@v1.3.4/pkg/progress/bar.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package progress
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  )
    23  
    24  // TODO(stevvooe): We may want to support more interesting parameterization of
    25  // the bar. For now, it is very simple.
    26  
    27  // Bar provides a very simple progress bar implementation.
    28  //
    29  // Use with fmt.Printf and "r" to format the progress bar. A "-" flag makes it
    30  // progress from right to left.
    31  type Bar float64
    32  
    33  var _ fmt.Formatter = Bar(1.0)
    34  
    35  // Format the progress bar as output
    36  func (h Bar) Format(state fmt.State, r rune) {
    37  	switch r {
    38  	case 'r':
    39  	default:
    40  		panic(fmt.Sprintf("%v: unexpected format character", float64(h)))
    41  	}
    42  
    43  	if h > 1.0 {
    44  		h = 1.0
    45  	}
    46  
    47  	if h < 0.0 {
    48  		h = 0.0
    49  	}
    50  
    51  	if state.Flag('-') {
    52  		h = 1.0 - h
    53  	}
    54  
    55  	width, ok := state.Width()
    56  	if !ok {
    57  		// default width of 40
    58  		width = 40
    59  	}
    60  
    61  	var pad int
    62  
    63  	extra := len([]byte(green)) + len([]byte(reset))
    64  
    65  	p := make([]byte, width+extra)
    66  	p[0], p[len(p)-1] = '|', '|'
    67  	pad += 2
    68  
    69  	positive := int(Bar(width-pad) * h)
    70  	negative := width - pad - positive
    71  
    72  	n := 1
    73  	n += copy(p[n:], green)
    74  	n += copy(p[n:], bytes.Repeat([]byte("+"), positive))
    75  	n += copy(p[n:], reset)
    76  
    77  	if negative > 0 {
    78  		copy(p[n:len(p)-1], bytes.Repeat([]byte("-"), negative))
    79  	}
    80  
    81  	state.Write(p)
    82  }