github.com/openshift/installer@v1.4.17/pkg/explain/cmd.go (about)

     1  package explain
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/pkg/errors"
     9  	"github.com/spf13/cobra"
    10  
    11  	"github.com/openshift/installer/data"
    12  )
    13  
    14  // NewCmd returns a subcommand for explain
    15  func NewCmd() *cobra.Command {
    16  	cmd := &cobra.Command{
    17  		Use:   "explain",
    18  		Short: "List the fields for supported InstallConfig versions",
    19  		Long: `This command describes the fields associated with each supported InstallConfig API. Fields are identified via a simple
    20  JSONPath identifier:
    21  		
    22  installconfig.<fieldName>[.<fieldName>]
    23  `,
    24  		Example: `
    25  # Get the documentation of the resource and its fields
    26  openshift-install explain installconfig
    27  
    28  # Get the documentation of a AWS platform
    29  openshift-install explain installconfig.platform.aws`,
    30  		RunE: runCmd,
    31  	}
    32  
    33  	return cmd
    34  }
    35  
    36  func runCmd(cmd *cobra.Command, args []string) error {
    37  	if len(args) == 0 {
    38  		return errors.Errorf("You must specify the type of resource to explain\n")
    39  	}
    40  	if len(args) > 1 {
    41  		return errors.Errorf("We accept only this format: explain RESOURCE\n")
    42  	}
    43  
    44  	file, err := data.Assets.Open(installConfigCRDFileName)
    45  	if err != nil {
    46  		return errors.Wrap(err, "failed to load InstallConfig CRD")
    47  	}
    48  	defer file.Close()
    49  
    50  	raw, err := io.ReadAll(file)
    51  	if err != nil {
    52  		return errors.Wrap(err, "failed to read InstallConfig CRD")
    53  	}
    54  
    55  	resource, path := splitDotNotation(args[0])
    56  	if resource != "installconfig" {
    57  		return errors.Errorf("only installconfig resource is supported")
    58  	}
    59  
    60  	schema, err := loadSchema(raw)
    61  	if err != nil {
    62  		return errors.Wrap(err, "failed to load schema")
    63  	}
    64  
    65  	fschema, err := lookup(schema, path)
    66  	if err != nil {
    67  		return errors.Wrapf(err, "failed to load schema for the field %s", strings.Join(path, "."))
    68  	}
    69  
    70  	p := printer{Writer: os.Stdout}
    71  	p.PrintKindAndVersion()
    72  	p.PrintResource(fschema)
    73  	p.PrintFields(fschema)
    74  	return nil
    75  }
    76  
    77  func splitDotNotation(model string) (string, []string) {
    78  	var fieldsPath []string
    79  
    80  	// ignore trailing period
    81  	model = strings.TrimSuffix(model, ".")
    82  
    83  	dotModel := strings.Split(model, ".")
    84  	if len(dotModel) >= 1 {
    85  		fieldsPath = dotModel[1:]
    86  	}
    87  	return dotModel[0], fieldsPath
    88  }