From f46bf475799a90c9afcb9df4ec5f541dcf73eb8a Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sun, 11 Aug 2013 23:12:20 -0700 Subject: [PATCH] parse --machine-readable and set it --- packer.go | 29 ++++++++++++++++++++++++++++- packer_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/packer.go b/packer.go index e1049b231..aa53fe57d 100644 --- a/packer.go +++ b/packer.go @@ -76,8 +76,13 @@ func main() { log.Printf("Setting cache directory: %s", cacheDir) cache := &packer.FileCache{CacheDir: cacheDir} + // Determine if we're in machine-readable mode by mucking around with + // the arguments... + args, machineReadable := extractMachineReadable(os.Args[1:]) + defer plugin.CleanupClients() + // Create the environment configuration envConfig := packer.DefaultEnvironmentConfig() envConfig.Cache = cache envConfig.Commands = config.CommandNames() @@ -86,6 +91,11 @@ func main() { envConfig.Components.Hook = config.LoadHook envConfig.Components.PostProcessor = config.LoadPostProcessor envConfig.Components.Provisioner = config.LoadProvisioner + if machineReadable { + envConfig.Ui = &packer.MachineReadableUi{ + Writer: os.Stdout, + } + } env, err := packer.NewEnvironment(envConfig) if err != nil { @@ -96,7 +106,7 @@ func main() { setupSignalHandlers(env) - exitCode, err := env.Cli(os.Args[1:]) + exitCode, err := env.Cli(args) if err != nil { fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err.Error()) plugin.CleanupClients() @@ -107,6 +117,23 @@ func main() { os.Exit(exitCode) } +// extractMachineReadable checks the args for the machine readable +// flag and returns whether or not it is on. It modifies the args +// to remove this flag. +func extractMachineReadable(args []string) ([]string, bool) { + for i, arg := range args { + if arg == "--machine-readable" { + // We found it. Slice it out. + result := make([]string, len(args)-1) + copy(result, args[:i]) + copy(result[i:], args[i+1:]) + return result, true + } + } + + return args, false +} + func loadConfig() (*config, error) { var config config if err := decodeConfig(bytes.NewBufferString(defaultConfig), &config); err != nil { diff --git a/packer_test.go b/packer_test.go index 06ab7d0f9..5a08f8431 100644 --- a/packer_test.go +++ b/packer_test.go @@ -1 +1,35 @@ package main + +import ( + "reflect" + "testing" +) + +func TestExtractMachineReadable(t *testing.T) { + var args, expected, result []string + var mr bool + + // Not + args = []string{"foo", "bar", "baz"} + result, mr = extractMachineReadable(args) + expected = []string{"foo", "bar", "baz"} + if !reflect.DeepEqual(result, expected) { + t.Fatalf("bad: %#v", result) + } + + if mr { + t.Fatal("should not be mr") + } + + // Yes + args = []string{"foo", "--machine-readable", "baz"} + result, mr = extractMachineReadable(args) + expected = []string{"foo", "baz"} + if !reflect.DeepEqual(result, expected) { + t.Fatalf("bad: %#v", result) + } + + if !mr { + t.Fatal("should be mr") + } +}