github.com/thanhphan1147/cloudfoundry-cli@v7.1.0+incompatible/cf/terminal/tee_printer.go (about)

     1  package terminal
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"io/ioutil"
     7  )
     8  
     9  type TeePrinter struct {
    10  	disableTerminalOutput bool
    11  	outputBucket          io.Writer
    12  	stdout                io.Writer
    13  }
    14  
    15  func NewTeePrinter(w io.Writer) *TeePrinter {
    16  	return &TeePrinter{
    17  		outputBucket: ioutil.Discard,
    18  		stdout:       w,
    19  	}
    20  }
    21  
    22  func (t *TeePrinter) SetOutputBucket(bucket io.Writer) {
    23  	if bucket == nil {
    24  		bucket = ioutil.Discard
    25  	}
    26  
    27  	t.outputBucket = bucket
    28  }
    29  
    30  func (t *TeePrinter) Print(values ...interface{}) (int, error) {
    31  	str := fmt.Sprint(values...)
    32  	t.saveOutputToBucket(str)
    33  	if !t.disableTerminalOutput {
    34  		return fmt.Fprint(t.stdout, str)
    35  	}
    36  	return 0, nil
    37  }
    38  
    39  func (t *TeePrinter) Printf(format string, a ...interface{}) (int, error) {
    40  	str := fmt.Sprintf(format, a...)
    41  	t.saveOutputToBucket(str)
    42  	if !t.disableTerminalOutput {
    43  		return fmt.Fprint(t.stdout, str)
    44  	}
    45  	return 0, nil
    46  }
    47  
    48  func (t *TeePrinter) Println(values ...interface{}) (int, error) {
    49  	str := fmt.Sprint(values...)
    50  	t.saveOutputToBucket(str)
    51  	if !t.disableTerminalOutput {
    52  		return fmt.Fprintln(t.stdout, str)
    53  	}
    54  	return 0, nil
    55  }
    56  
    57  func (t *TeePrinter) DisableTerminalOutput(disable bool) {
    58  	t.disableTerminalOutput = disable
    59  }
    60  
    61  func (t *TeePrinter) saveOutputToBucket(output string) {
    62  	_, _ = t.outputBucket.Write([]byte(Decolorize(output)))
    63  }