knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/upgrade/shell/prefixer.go (about)

     1  /*
     2  Copyright 2020 The Knative 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 shell
    18  
    19  import (
    20  	"bytes"
    21  	"io"
    22  )
    23  
    24  // NewPrefixer creates a new prefixer that forwards all calls to Write() to
    25  // writer.Write() with all lines prefixed with the value of prefix. Having a
    26  // function instead of a static prefix allows to print timestamps or other
    27  // changing information.
    28  func NewPrefixer(writer io.Writer, prefix func() string) io.Writer {
    29  	return &prefixer{prefix: prefix, writer: writer, trailingNewline: true}
    30  }
    31  
    32  type prefixer struct {
    33  	prefix          func() string
    34  	writer          io.Writer
    35  	trailingNewline bool
    36  	buf             bytes.Buffer // reuse buffer to save allocations
    37  }
    38  
    39  func (pf *prefixer) Write(payload []byte) (int, error) {
    40  	pf.buf.Reset() // clear the buffer
    41  
    42  	for _, b := range payload {
    43  		if pf.trailingNewline {
    44  			pf.buf.WriteString(pf.prefix())
    45  			pf.trailingNewline = false
    46  		}
    47  
    48  		pf.buf.WriteByte(b)
    49  
    50  		if b == '\n' {
    51  			// do not print the prefix right after the newline character as this might
    52  			// be the very last character of the stream and we want to avoid a trailing prefix.
    53  			pf.trailingNewline = true
    54  		}
    55  	}
    56  
    57  	n, err := pf.writer.Write(pf.buf.Bytes())
    58  	if err != nil {
    59  		// never return more than original length to satisfy io.Writer interface
    60  		if n > len(payload) {
    61  			n = len(payload)
    62  		}
    63  		return n, err
    64  	}
    65  
    66  	// return original length to satisfy io.Writer interface
    67  	return len(payload), nil
    68  }