github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/uio/progress.go (about)

     1  // Copyright 2019 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package uio
     6  
     7  import (
     8  	"io"
     9  	"strings"
    10  )
    11  
    12  // ProgressReadCloser implements io.ReadCloser and prints Symbol to W after every
    13  // Interval bytes passes through RC.
    14  type ProgressReadCloser struct {
    15  	RC io.ReadCloser
    16  
    17  	Symbol   string
    18  	Interval int
    19  	W        io.Writer
    20  
    21  	counter int
    22  	written bool
    23  }
    24  
    25  // Read implements io.Reader for ProgressReadCloser.
    26  func (rc *ProgressReadCloser) Read(p []byte) (n int, err error) {
    27  	defer func() {
    28  		numSymbols := (rc.counter%rc.Interval + n) / rc.Interval
    29  		rc.W.Write([]byte(strings.Repeat(rc.Symbol, numSymbols)))
    30  		rc.counter += n
    31  		rc.written = (rc.written || numSymbols > 0)
    32  		if err == io.EOF && rc.written {
    33  			rc.W.Write([]byte("\n"))
    34  		}
    35  	}()
    36  	return rc.RC.Read(p)
    37  }
    38  
    39  // Read implements io.Closer for ProgressReader.
    40  func (rc *ProgressReadCloser) Close() error {
    41  	return rc.RC.Close()
    42  }