github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/testhelpers/outputhelper/outputhelper.go (about)

     1  package outputhelper
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"github.com/ActiveState/cli/internal/output"
     8  )
     9  
    10  type Catcher struct {
    11  	output.Outputer
    12  	cfg       *output.Config
    13  	outWriter *bytes.Buffer
    14  	errWriter *bytes.Buffer
    15  }
    16  
    17  func NewCatcher() *Catcher {
    18  	return NewCatcherByFormat(output.PlainFormatName, false)
    19  }
    20  
    21  func NewCatcherByFormat(format output.Format, interactive bool) *Catcher {
    22  	catch := &Catcher{}
    23  
    24  	catch.cfg = &output.Config{
    25  		Colored:     false,
    26  		Interactive: interactive,
    27  	}
    28  
    29  	catch.outWriter = &bytes.Buffer{}
    30  	catch.errWriter = &bytes.Buffer{}
    31  
    32  	outputer, err := output.New(string(format), &output.Config{
    33  		OutWriter:   catch.outWriter,
    34  		ErrWriter:   catch.errWriter,
    35  		Colored:     false,
    36  		Interactive: false,
    37  	})
    38  
    39  	if err != nil {
    40  		panic(fmt.Sprintf("Could not create plain outputer: %s", err.Error()))
    41  	}
    42  
    43  	catch.Outputer = outputer
    44  
    45  	return catch
    46  }
    47  
    48  func (c *Catcher) Output() string {
    49  	return c.outWriter.String()
    50  }
    51  
    52  func (c *Catcher) ErrorOutput() string {
    53  	return c.errWriter.String()
    54  }
    55  
    56  func (c *Catcher) CombinedOutput() string {
    57  	return c.Output() + "\n" + c.ErrorOutput()
    58  }
    59  
    60  type TypedCatcher struct {
    61  	Prints  []interface{}
    62  	Errors  []interface{}
    63  	Notices []interface{}
    64  }
    65  
    66  func (t *TypedCatcher) Type() output.Format {
    67  	return ""
    68  }
    69  
    70  func (t *TypedCatcher) Print(value interface{}) {
    71  	t.Prints = append(t.Prints, value)
    72  }
    73  
    74  func (t *TypedCatcher) Error(value interface{}) {
    75  	t.Errors = append(t.Errors, value)
    76  }
    77  
    78  func (t *TypedCatcher) Notice(value interface{}) {
    79  	t.Notices = append(t.Notices, value)
    80  }
    81  
    82  func (t *TypedCatcher) Config() *output.Config {
    83  	return &output.Config{}
    84  }