github.com/kubeshop/testkube@v1.17.23/cmd/tcl/testworkflow-init/utils/outputProcessor.go (about)

     1  // Copyright 2024 Testkube.
     2  //
     3  //Licensed as a Testkube Pro file under the Testkube Community
     4  // License (the "License"); you may not use this file except in compliance with
     5  // the License. You may obtain a copy of the License at
     6  //
     7  //	https://github.com/kubeshop/testkube/blob/main/licenses/TCL.txt
     8  
     9  package utils
    10  
    11  import (
    12  	"bytes"
    13  	"errors"
    14  	"io"
    15  
    16  	"github.com/kubeshop/testkube/cmd/tcl/testworkflow-init/data"
    17  )
    18  
    19  type outputProcessor struct {
    20  	writer   io.Writer
    21  	ref      string
    22  	closed   bool
    23  	lastLine []byte
    24  }
    25  
    26  func NewOutputProcessor(ref string, writer io.Writer) io.WriteCloser {
    27  	return &outputProcessor{
    28  		writer: writer,
    29  		ref:    ref,
    30  	}
    31  }
    32  
    33  func (o *outputProcessor) Write(p []byte) (int, error) {
    34  	if o.closed {
    35  		return 0, errors.New("stream is already closed")
    36  	}
    37  
    38  	// Process to search for output
    39  	lines := bytes.Split(append(o.lastLine, p...), []byte("\n"))
    40  	o.lastLine = nil
    41  	for i := range lines {
    42  		instruction, _, _ := data.DetectInstruction(lines[i])
    43  		if instruction == nil && i == len(lines)-1 {
    44  			o.lastLine = lines[i]
    45  		}
    46  		if instruction != nil && instruction.Value != nil {
    47  			data.State.SetOutput(instruction.Ref, instruction.Name, instruction.Value)
    48  		}
    49  	}
    50  
    51  	// Pass the output down
    52  	return o.writer.Write(p)
    53  }
    54  
    55  func (o *outputProcessor) Close() error {
    56  	o.closed = true
    57  	return nil
    58  }