github.com/kaixiang/packer@v0.5.2-0.20140114230416-1f5786b0d7f1/command/fix/command.go (about)

     1  package fix
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"flag"
     7  	"fmt"
     8  	"github.com/mitchellh/packer/packer"
     9  	"log"
    10  	"os"
    11  	"strings"
    12  )
    13  
    14  type Command byte
    15  
    16  func (Command) Help() string {
    17  	return strings.TrimSpace(helpString)
    18  }
    19  
    20  func (c Command) Run(env packer.Environment, args []string) int {
    21  	cmdFlags := flag.NewFlagSet("fix", flag.ContinueOnError)
    22  	cmdFlags.Usage = func() { env.Ui().Say(c.Help()) }
    23  	if err := cmdFlags.Parse(args); err != nil {
    24  		return 1
    25  	}
    26  
    27  	args = cmdFlags.Args()
    28  	if len(args) != 1 {
    29  		cmdFlags.Usage()
    30  		return 1
    31  	}
    32  
    33  	// Read the file for decoding
    34  	tplF, err := os.Open(args[0])
    35  	if err != nil {
    36  		env.Ui().Error(fmt.Sprintf("Error opening template: %s", err))
    37  		return 1
    38  	}
    39  	defer tplF.Close()
    40  
    41  	// Decode the JSON into a generic map structure
    42  	var templateData map[string]interface{}
    43  	decoder := json.NewDecoder(tplF)
    44  	if err := decoder.Decode(&templateData); err != nil {
    45  		env.Ui().Error(fmt.Sprintf("Error parsing template: %s", err))
    46  		return 1
    47  	}
    48  
    49  	// Close the file since we're done with that
    50  	tplF.Close()
    51  
    52  	input := templateData
    53  	for _, name := range FixerOrder {
    54  		var err error
    55  		fixer, ok := Fixers[name]
    56  		if !ok {
    57  			panic("fixer not found: " + name)
    58  		}
    59  
    60  		log.Printf("Running fixer: %s", name)
    61  		input, err = fixer.Fix(input)
    62  		if err != nil {
    63  			env.Ui().Error(fmt.Sprintf("Error fixing: %s", err))
    64  			return 1
    65  		}
    66  	}
    67  
    68  	var output bytes.Buffer
    69  	encoder := json.NewEncoder(&output)
    70  	if err := encoder.Encode(input); err != nil {
    71  		env.Ui().Error(fmt.Sprintf("Error encoding: %s", err))
    72  		return 1
    73  	}
    74  
    75  	var indented bytes.Buffer
    76  	if err := json.Indent(&indented, output.Bytes(), "", "  "); err != nil {
    77  		env.Ui().Error(fmt.Sprintf("Error encoding: %s", err))
    78  		return 1
    79  	}
    80  
    81  	result := indented.String()
    82  	result = strings.Replace(result, `\u003c`, "<", -1)
    83  	result = strings.Replace(result, `\u003e`, ">", -1)
    84  	env.Ui().Say(result)
    85  	return 0
    86  }
    87  
    88  func (c Command) Synopsis() string {
    89  	return "fixes templates from old versions of packer"
    90  }