get.porter.sh/porter@v1.3.0/pkg/printer/printer.go (about)

     1  package printer
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  type Format string
     9  
    10  const (
    11  	FormatJson      Format = "json"
    12  	FormatYaml      Format = "yaml"
    13  	FormatPlaintext Format = "plaintext"
    14  )
    15  
    16  type Formats []Format
    17  
    18  func (f Formats) String() string {
    19  	var buf strings.Builder
    20  	for i, format := range f {
    21  		buf.WriteString(string(format))
    22  		if i < len(f)-1 {
    23  			buf.WriteString(", ")
    24  		}
    25  	}
    26  	return buf.String()
    27  }
    28  
    29  func (p *PrintOptions) ParseFormat() error {
    30  	format := Format(p.RawFormat)
    31  	switch format {
    32  	case FormatJson, FormatYaml, FormatPlaintext:
    33  		p.Format = format
    34  		return nil
    35  	case "":
    36  		// This helps us out in our unit tests, defaulting the output to plaintext
    37  		p.Format = FormatPlaintext
    38  		return nil
    39  	default:
    40  		return fmt.Errorf("invalid format: %s", p.RawFormat)
    41  	}
    42  }
    43  
    44  func (p *PrintOptions) Validate(defaultFormat Format, allowedFormats []Format) error {
    45  	// Default unspecified format
    46  	if p.RawFormat == "" {
    47  		p.RawFormat = string(defaultFormat)
    48  	}
    49  
    50  	format := Format(p.RawFormat)
    51  	for _, f := range allowedFormats {
    52  		if f == format {
    53  			p.Format = format
    54  			return nil
    55  		}
    56  	}
    57  	return fmt.Errorf("invalid format: %s", p.RawFormat)
    58  }
    59  
    60  type PrintOptions struct {
    61  	RawFormat string
    62  	Format
    63  }