| 53 | } |
| 54 | |
| 55 | func (c *FixCommand) RunContext(ctx context.Context, cla *FixArgs) int { |
| 56 | if hcl2, _ := isHCLLoaded(cla.Path); hcl2 { |
| 57 | c.Ui.Error("packer fix only works with JSON files for now.") |
| 58 | return 1 |
| 59 | } |
| 60 | // Read the file for decoding |
| 61 | tplF, err := os.Open(cla.Path) |
| 62 | if err != nil { |
| 63 | c.Ui.Error(fmt.Sprintf("Error opening template: %s", err)) |
| 64 | return 1 |
| 65 | } |
| 66 | defer tplF.Close() |
| 67 | |
| 68 | // Decode the JSON into a generic map structure |
| 69 | var templateData map[string]interface{} |
| 70 | decoder := json.NewDecoder(tplF) |
| 71 | if err := decoder.Decode(&templateData); err != nil { |
| 72 | c.Ui.Error(fmt.Sprintf("Error parsing template: %s", err)) |
| 73 | return 1 |
| 74 | } |
| 75 | |
| 76 | // Close the file since we're done with that |
| 77 | tplF.Close() |
| 78 | |
| 79 | input := templateData |
| 80 | for _, name := range fix.FixerOrder { |
| 81 | var err error |
| 82 | fixer, ok := fix.Fixers[name] |
| 83 | if !ok { |
| 84 | panic("fixer not found: " + name) |
| 85 | } |
| 86 | |
| 87 | log.Printf("Running fixer: %s", name) |
| 88 | input, err = fixer.Fix(input) |
| 89 | if err != nil { |
| 90 | c.Ui.Error(fmt.Sprintf("Error fixing: %s", err)) |
| 91 | return 1 |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | var output bytes.Buffer |
| 96 | encoder := json.NewEncoder(&output) |
| 97 | if err := encoder.Encode(input); err != nil { |
| 98 | c.Ui.Error(fmt.Sprintf("Error encoding: %s", err)) |
| 99 | return 1 |
| 100 | } |
| 101 | |
| 102 | var indented bytes.Buffer |
| 103 | if err := json.Indent(&indented, output.Bytes(), "", " "); err != nil { |
| 104 | c.Ui.Error(fmt.Sprintf("Error encoding: %s", err)) |
| 105 | return 1 |
| 106 | } |
| 107 | |
| 108 | result := indented.String() |
| 109 | result = strings.Replace(result, `\u003c`, "<", -1) |
| 110 | result = strings.Replace(result, `\u003e`, ">", -1) |
| 111 | c.Ui.Say(result) |
| 112 | |