update fix command with new synthax

This commit is contained in:
Adrien Delorme 2020-05-12 11:33:44 +02:00
parent 14f18f4236
commit 49c2a8cb17
1 changed files with 43 additions and 24 deletions

View File

@ -2,6 +2,7 @@ package command
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
@ -19,22 +20,38 @@ type FixCommand struct {
} }
func (c *FixCommand) Run(args []string) int { func (c *FixCommand) Run(args []string) int {
var flagValidate bool ctx, cleanup := handleTermInterrupt(c.Ui)
defer cleanup()
cfg, ret := c.ParseArgs(args)
if ret != 0 {
return ret
}
return c.RunContext(ctx, cfg)
}
func (c *FixCommand) ParseArgs(args []string) (*FixArgs, int) {
var cfg FixArgs
flags := c.Meta.FlagSet("fix", FlagSetNone) flags := c.Meta.FlagSet("fix", FlagSetNone)
flags.BoolVar(&flagValidate, "validate", true, "")
flags.Usage = func() { c.Ui.Say(c.Help()) } flags.Usage = func() { c.Ui.Say(c.Help()) }
cfg.AddFlagSets(flags)
if err := flags.Parse(args); err != nil { if err := flags.Parse(args); err != nil {
return 1 return &cfg, 1
} }
args = flags.Args() args = flags.Args()
if len(args) != 1 { if len(args) != 1 {
flags.Usage() flags.Usage()
return 1 return &cfg, 1
} }
cfg.Path = args[0]
return &cfg, 0
}
func (c *FixCommand) RunContext(ctx context.Context, cla *FixArgs) int {
// Read the file for decoding // Read the file for decoding
tplF, err := os.Open(args[0]) tplF, err := os.Open(cla.Path)
if err != nil { if err != nil {
c.Ui.Error(fmt.Sprintf("Error opening template: %s", err)) c.Ui.Error(fmt.Sprintf("Error opening template: %s", err))
return 1 return 1
@ -86,25 +103,27 @@ func (c *FixCommand) Run(args []string) int {
result = strings.Replace(result, `\u003e`, ">", -1) result = strings.Replace(result, `\u003e`, ">", -1)
c.Ui.Say(result) c.Ui.Say(result)
if flagValidate { if cla.Validate == false {
// Attempt to parse and validate the template return 0
tpl, err := template.Parse(strings.NewReader(result)) }
if err != nil {
c.Ui.Error(fmt.Sprintf( // Attempt to parse and validate the template
"Error! Fixed template fails to parse: %s\n\n"+ tpl, err := template.Parse(strings.NewReader(result))
"This is usually caused by an error in the input template.\n"+ if err != nil {
"Please fix the error and try again.", c.Ui.Error(fmt.Sprintf(
err)) "Error! Fixed template fails to parse: %s\n\n"+
return 1 "This is usually caused by an error in the input template.\n"+
} "Please fix the error and try again.",
if err := tpl.Validate(); err != nil { err))
c.Ui.Error(fmt.Sprintf( return 1
"Error! Fixed template failed to validate: %s\n\n"+ }
"This is usually caused by an error in the input template.\n"+ if err := tpl.Validate(); err != nil {
"Please fix the error and try again.", c.Ui.Error(fmt.Sprintf(
err)) "Error! Fixed template failed to validate: %s\n\n"+
return 1 "This is usually caused by an error in the input template.\n"+
} "Please fix the error and try again.",
err))
return 1
} }
return 0 return 0