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