github.com/kubeshop/testkube@v1.17.23/cmd/kubectl-testkube/commands/common/content.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  
     8  	"github.com/spf13/cobra"
     9  )
    10  
    11  // NewDataFromFlags read input data from stdin or '--file' parameter
    12  func NewDataFromFlags(cmd *cobra.Command) (data *string, err error) {
    13  	var hasFile bool
    14  	if cmd.Flag("file").Changed {
    15  		// get file content
    16  		file := cmd.Flag("file").Value.String()
    17  		if file != "" {
    18  			fileContent, err := os.ReadFile(file)
    19  			if err != nil {
    20  				return nil, fmt.Errorf("reading file "+file+" error: %w", err)
    21  			}
    22  
    23  			content := string(fileContent)
    24  			data = &content
    25  			hasFile = true
    26  		}
    27  	}
    28  
    29  	if stat, _ := os.Stdin.Stat(); (stat.Mode()&os.ModeCharDevice) == 0 && !hasFile {
    30  		stdinContent, err := io.ReadAll(os.Stdin)
    31  		if err != nil {
    32  			return nil, fmt.Errorf("reading stdin error: %w", err)
    33  		}
    34  
    35  		if len(stdinContent) != 0 {
    36  			content := string(stdinContent)
    37  			data = &content
    38  		}
    39  	}
    40  
    41  	return data, nil
    42  }