github.com/tcnksm/gcli@v0.2.4-0.20170129033839-7eb950507e5a/command/validate.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/BurntSushi/toml"
     9  	"github.com/tcnksm/gcli/skeleton"
    10  )
    11  
    12  // ValidateCommand is a Command that validate template file
    13  type ValidateCommand struct {
    14  	Meta
    15  }
    16  
    17  // Run validates template file
    18  func (c *ValidateCommand) Run(args []string) int {
    19  
    20  	uflag := c.Meta.NewFlagSet("validate", c.Help())
    21  	if err := uflag.Parse(args); err != nil {
    22  		return 1
    23  	}
    24  
    25  	parsedArgs := uflag.Args()
    26  	if len(parsedArgs) != 1 {
    27  		c.UI.Error("Invalid argument")
    28  		c.UI.Error(c.Help())
    29  		return 1
    30  	}
    31  
    32  	designFile := parsedArgs[0]
    33  
    34  	// Check file is exist or not
    35  	if _, err := os.Stat(designFile); os.IsNotExist(err) {
    36  		c.UI.Error(fmt.Sprintf(
    37  			"Design file %q does not exsit: %s", designFile, err))
    38  		return 1
    39  	}
    40  
    41  	// Decode design file as skeleton.Executable
    42  	executable := skeleton.NewExecutable()
    43  	if _, err := toml.DecodeFile(designFile, executable); err != nil {
    44  		c.UI.Error(fmt.Sprintf(
    45  			"Failed to decode design file %q: %s", designFile, err))
    46  		return 1
    47  	}
    48  
    49  	errs := executable.Validate()
    50  	if len(errs) != 0 {
    51  		c.UI.Error(fmt.Sprintf(
    52  			"%q is not valid template file. It has %d errors:", designFile, len(errs)))
    53  		for _, err := range errs {
    54  			c.UI.Error(fmt.Sprintf(
    55  				"  * %s", err.Error()))
    56  		}
    57  		return ExitCodeFailed
    58  	}
    59  
    60  	c.UI.Info(fmt.Sprintf(
    61  		"%q is valid template file.\n"+
    62  			"You can generate cli project based on this file via `gcli apply` command", designFile))
    63  
    64  	return ExitCodeOK
    65  
    66  }
    67  
    68  // Synopsis is a one-line, short synopsis of the command.
    69  func (c *ValidateCommand) Synopsis() string {
    70  	return "Validate design template file"
    71  }
    72  
    73  // Help is a long-form help text that includes the command-line
    74  // usage, a brief few sentences explaining the function of the command,
    75  // and the complete list of flags the command accepts.
    76  func (c *ValidateCommand) Help() string {
    77  	helpText := `
    78  Validate design template file which has required filed. If not it returns
    79  error and non zero value. 
    80  
    81  Usage:
    82  
    83    gcli validate FILE
    84  
    85  `
    86  	return strings.TrimSpace(helpText)
    87  }