github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/cmd/roachprod/ui/writer.go (about)

     1  // Copyright 2018 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package ui
    12  
    13  import (
    14  	"bytes"
    15  	"fmt"
    16  	"io"
    17  	"strings"
    18  )
    19  
    20  // Writer TODO(peter): document
    21  type Writer struct {
    22  	buf       bytes.Buffer
    23  	lineCount int
    24  }
    25  
    26  // Flush TODO(peter): document
    27  func (w *Writer) Flush(out io.Writer) error {
    28  	if len(w.buf.Bytes()) == 0 {
    29  		return nil
    30  	}
    31  	w.clearLines(out)
    32  
    33  	for _, b := range w.buf.Bytes() {
    34  		if b == '\n' {
    35  			w.lineCount++
    36  		}
    37  	}
    38  	_, err := out.Write(w.buf.Bytes())
    39  	w.buf.Reset()
    40  	return err
    41  }
    42  
    43  func (w *Writer) Write(b []byte) (n int, err error) {
    44  	return w.buf.Write(b)
    45  }
    46  
    47  func (w *Writer) clearLines(out io.Writer) {
    48  	fmt.Fprint(out, strings.Repeat("\033[1A\033[2K\r", w.lineCount))
    49  	w.lineCount = 0
    50  }