當前位置: 首頁>>代碼示例>>Golang>>正文


Golang template.ParseFile函數代碼示例

本文整理匯總了Golang中github.com/mitchellh/packer/template.ParseFile函數的典型用法代碼示例。如果您正苦於以下問題:Golang ParseFile函數的具體用法?Golang ParseFile怎麽用?Golang ParseFile使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ParseFile函數的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestCore_pushInterpolate

func TestCore_pushInterpolate(t *testing.T) {
	cases := []struct {
		File   string
		Vars   map[string]string
		Result template.Push
	}{
		{
			"push-vars.json",
			map[string]string{"foo": "bar"},
			template.Push{Name: "bar"},
		},
	}

	for _, tc := range cases {
		tpl, err := template.ParseFile(fixtureDir(tc.File))
		if err != nil {
			t.Fatalf("err: %s\n\n%s", tc.File, err)
		}

		core, err := NewCore(&CoreConfig{
			Template:  tpl,
			Variables: tc.Vars,
		})
		if err != nil {
			t.Fatalf("err: %s\n\n%s", tc.File, err)
		}

		expected := core.Template.Push
		if !reflect.DeepEqual(expected, tc.Result) {
			t.Fatalf("err: %s\n\n%#v", tc.File, expected)
		}
	}
}
開發者ID:cewood,項目名稱:packer,代碼行數:33,代碼來源:core_test.go

示例2: testCoreTemplate

func testCoreTemplate(t *testing.T, c *CoreConfig, p string) {
	tpl, err := template.ParseFile(p)
	if err != nil {
		t.Fatalf("err: %s\n\n%s", p, err)
	}

	c.Template = tpl
}
開發者ID:cewood,項目名稱:packer,代碼行數:8,代碼來源:core_test.go

示例3: TestCoreBuildNames

func TestCoreBuildNames(t *testing.T) {
	cases := []struct {
		File   string
		Vars   map[string]string
		Result []string
	}{
		{
			"build-names-basic.json",
			nil,
			[]string{"something"},
		},

		{
			"build-names-func.json",
			nil,
			[]string{"TUBES"},
		},
	}

	for _, tc := range cases {
		tpl, err := template.ParseFile(fixtureDir(tc.File))
		if err != nil {
			t.Fatalf("err: %s\n\n%s", tc.File, err)
		}

		core, err := NewCore(&CoreConfig{
			Template:  tpl,
			Variables: tc.Vars,
		})
		if err != nil {
			t.Fatalf("err: %s\n\n%s", tc.File, err)
		}

		names := core.BuildNames()
		if !reflect.DeepEqual(names, tc.Result) {
			t.Fatalf("err: %s\n\n%#v", tc.File, names)
		}
	}
}
開發者ID:cewood,項目名稱:packer,代碼行數:39,代碼來源:core_test.go

示例4: Run

func (c BuildCommand) Run(args []string) int {
	var cfgColor, cfgDebug, cfgForce, cfgParallel bool
	var cfgOnError string
	flags := c.Meta.FlagSet("build", FlagSetBuildFilter|FlagSetVars)
	flags.Usage = func() { c.Ui.Say(c.Help()) }
	flags.BoolVar(&cfgColor, "color", true, "")
	flags.BoolVar(&cfgDebug, "debug", false, "")
	flags.BoolVar(&cfgForce, "force", false, "")
	flagOnError := enumflag.New(&cfgOnError, "cleanup", "abort", "ask")
	flags.Var(flagOnError, "on-error", "")
	flags.BoolVar(&cfgParallel, "parallel", true, "")
	if err := flags.Parse(args); err != nil {
		return 1
	}

	args = flags.Args()
	if len(args) != 1 {
		flags.Usage()
		return 1
	}

	// Parse the template
	var tpl *template.Template
	var err error
	tpl, err = template.ParseFile(args[0])
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to parse template: %s", err))
		return 1
	}

	// Get the core
	core, err := c.Meta.Core(tpl)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	// Get the builds we care about
	buildNames := c.Meta.BuildNames(core)
	builds := make([]packer.Build, 0, len(buildNames))
	for _, n := range buildNames {
		b, err := core.Build(n)
		if err != nil {
			c.Ui.Error(fmt.Sprintf(
				"Failed to initialize build '%s': %s",
				n, err))
			continue
		}

		builds = append(builds, b)
	}

	if cfgDebug {
		c.Ui.Say("Debug mode enabled. Builds will not be parallelized.")
	}

	// Compile all the UIs for the builds
	colors := [5]packer.UiColor{
		packer.UiColorGreen,
		packer.UiColorCyan,
		packer.UiColorMagenta,
		packer.UiColorYellow,
		packer.UiColorBlue,
	}
	buildUis := make(map[string]packer.Ui)
	for i, b := range buildNames {
		var ui packer.Ui
		ui = c.Ui
		if cfgColor {
			ui = &packer.ColoredUi{
				Color: colors[i%len(colors)],
				Ui:    ui,
			}
		}

		buildUis[b] = ui
		ui.Say(fmt.Sprintf("%s output will be in this color.", b))
	}

	// Add a newline between the color output and the actual output
	c.Ui.Say("")

	log.Printf("Build debug mode: %v", cfgDebug)
	log.Printf("Force build: %v", cfgForce)
	log.Printf("On error: %v", cfgOnError)

	// Set the debug and force mode and prepare all the builds
	for _, b := range builds {
		log.Printf("Preparing build: %s", b.Name())
		b.SetDebug(cfgDebug)
		b.SetForce(cfgForce)
		b.SetOnError(cfgOnError)

		warnings, err := b.Prepare()
		if err != nil {
			c.Ui.Error(err.Error())
			return 1
		}
		if len(warnings) > 0 {
			ui := buildUis[b.Name()]
//.........這裏部分代碼省略.........
開發者ID:rnaveiras,項目名稱:packer,代碼行數:101,代碼來源:build.go

示例5: Run

func (c *InspectCommand) Run(args []string) int {
	flags := c.Meta.FlagSet("inspect", FlagSetNone)
	flags.Usage = func() { c.Ui.Say(c.Help()) }
	if err := flags.Parse(args); err != nil {
		return 1
	}

	args = flags.Args()
	if len(args) != 1 {
		flags.Usage()
		return 1
	}

	// Parse the template
	tpl, err := template.ParseFile(args[0])
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to parse template: %s", err))
		return 1
	}

	// Convenience...
	ui := c.Ui

	// Description
	if tpl.Description != "" {
		ui.Say("Description:\n")
		ui.Say(tpl.Description + "\n")
	}

	// Variables
	if len(tpl.Variables) == 0 {
		ui.Say("Variables:\n")
		ui.Say("  <No variables>")
	} else {
		requiredHeader := false
		for k, v := range tpl.Variables {
			if v.Required {
				if !requiredHeader {
					requiredHeader = true
					ui.Say("Required variables:\n")
				}

				ui.Machine("template-variable", k, v.Default, "1")
				ui.Say("  " + k)
			}
		}

		if requiredHeader {
			ui.Say("")
		}

		ui.Say("Optional variables and their defaults:\n")
		keys := make([]string, 0, len(tpl.Variables))
		max := 0
		for k := range tpl.Variables {
			keys = append(keys, k)
			if len(k) > max {
				max = len(k)
			}
		}

		sort.Strings(keys)

		for _, k := range keys {
			v := tpl.Variables[k]
			if v.Required {
				continue
			}

			padding := strings.Repeat(" ", max-len(k))
			output := fmt.Sprintf("  %s%s = %s", k, padding, v.Default)

			ui.Machine("template-variable", k, v.Default, "0")
			ui.Say(output)
		}
	}

	ui.Say("")

	// Builders
	ui.Say("Builders:\n")
	if len(tpl.Builders) == 0 {
		ui.Say("  <No builders>")
	} else {
		keys := make([]string, 0, len(tpl.Builders))
		max := 0
		for k := range tpl.Builders {
			keys = append(keys, k)
			if len(k) > max {
				max = len(k)
			}
		}

		sort.Strings(keys)

		for _, k := range keys {
			v := tpl.Builders[k]
			padding := strings.Repeat(" ", max-len(k))
			output := fmt.Sprintf("  %s%s", k, padding)
			if v.Name != v.Type {
//.........這裏部分代碼省略.........
開發者ID:rnaveiras,項目名稱:packer,代碼行數:101,代碼來源:inspect.go

示例6: Run

func (c *PushCommand) Run(args []string) int {
	var token string
	var message string
	var name string
	var create bool

	f := c.Meta.FlagSet("push", FlagSetVars)
	f.Usage = func() { c.Ui.Error(c.Help()) }
	f.StringVar(&token, "token", "", "token")
	f.StringVar(&message, "m", "", "message")
	f.StringVar(&message, "message", "", "message")
	f.StringVar(&name, "name", "", "name")
	f.BoolVar(&create, "create", false, "create (deprecated)")
	if err := f.Parse(args); err != nil {
		return 1
	}

	if message != "" {
		c.Ui.Say("[DEPRECATED] -m/-message is deprecated and will be removed in a future Packer release")
	}

	args = f.Args()
	if len(args) != 1 {
		f.Usage()
		return 1
	}

	// Print deprecations
	if create {
		c.Ui.Error(fmt.Sprintf("The '-create' option is now the default and is\n" +
			"longer used. It will be removed in the next version."))
	}

	// Parse the template
	tpl, err := template.ParseFile(args[0])
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to parse template: %s", err))
		return 1
	}

	// Get the core
	core, err := c.Meta.Core(tpl)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}
	push := core.Template.Push

	// If we didn't pass name from the CLI, use the template
	if name == "" {
		name = push.Name
	}

	// Validate some things
	if name == "" {
		c.Ui.Error(fmt.Sprintf(
			"The 'push' section must be specified in the template with\n" +
				"at least the 'name' option set. Alternatively, you can pass the\n" +
				"name parameter from the CLI."))
		return 1
	}

	if !reName.MatchString(name) {
		c.Ui.Error(errInvalidName.Error())
		return 1
	}

	// Determine our token
	if token == "" {
		token = push.Token
	}

	// Build our client
	defer func() { c.client = nil }()
	c.client = atlas.DefaultClient()
	if push.Address != "" {
		c.client, err = atlas.NewClient(push.Address)
		if err != nil {
			c.Ui.Error(fmt.Sprintf(
				"Error setting up API client: %s", err))
			return 1
		}
	}
	if token != "" {
		c.client.Token = token
	}

	// Build the archiving options
	var opts archive.ArchiveOpts
	opts.Include = push.Include
	opts.Exclude = push.Exclude
	opts.VCS = push.VCS
	opts.Extra = map[string]string{
		archiveTemplateEntry: args[0],
	}

	// Determine the path we're archiving. This logic is a bit complicated
	// as there are three possibilities:
	//
	//   1.) BaseDir is an absolute path, just use that.
//.........這裏部分代碼省略.........
開發者ID:boumenot,項目名稱:packer,代碼行數:101,代碼來源:push.go

示例7: Run

func (c *ValidateCommand) Run(args []string) int {
	var cfgSyntaxOnly bool
	flags := c.Meta.FlagSet("validate", FlagSetBuildFilter|FlagSetVars)
	flags.Usage = func() { c.Ui.Say(c.Help()) }
	flags.BoolVar(&cfgSyntaxOnly, "syntax-only", false, "check syntax only")
	if err := flags.Parse(args); err != nil {
		return 1
	}

	args = flags.Args()
	if len(args) != 1 {
		flags.Usage()
		return 1
	}

	// Parse the template
	tpl, err := template.ParseFile(args[0])
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to parse template: %s", err))
		return 1
	}

	// If we're only checking syntax, then we're done already
	if cfgSyntaxOnly {
		c.Ui.Say("Syntax-only check passed. Everything looks okay.")
		return 0
	}

	// Get the core
	core, err := c.Meta.Core(tpl)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	errs := make([]error, 0)
	warnings := make(map[string][]string)

	// Get the builds we care about
	buildNames := c.Meta.BuildNames(core)
	builds := make([]packer.Build, 0, len(buildNames))
	for _, n := range buildNames {
		b, err := core.Build(n)
		if err != nil {
			c.Ui.Error(fmt.Sprintf(
				"Failed to initialize build '%s': %s",
				n, err))
			return 1
		}

		builds = append(builds, b)
	}

	// Check the configuration of all builds
	for _, b := range builds {
		log.Printf("Preparing build: %s", b.Name())
		warns, err := b.Prepare()
		if len(warns) > 0 {
			warnings[b.Name()] = warns
		}
		if err != nil {
			errs = append(errs, fmt.Errorf("Errors validating build '%s'. %s", b.Name(), err))
		}
	}

	if len(errs) > 0 {
		c.Ui.Error("Template validation failed. Errors are shown below.\n")
		for i, err := range errs {
			c.Ui.Error(err.Error())

			if (i + 1) < len(errs) {
				c.Ui.Error("")
			}
		}

		return 1
	}

	if len(warnings) > 0 {
		c.Ui.Say("Template validation succeeded, but there were some warnings.")
		c.Ui.Say("These are ONLY WARNINGS, and Packer will attempt to build the")
		c.Ui.Say("template despite them, but they should be paid attention to.\n")

		for build, warns := range warnings {
			c.Ui.Say(fmt.Sprintf("Warnings for build '%s':\n", build))
			for _, warning := range warns {
				c.Ui.Say(fmt.Sprintf("* %s", warning))
			}
		}

		return 0
	}

	c.Ui.Say("Template validated successfully.")
	return 0
}
開發者ID:c12simple,項目名稱:packer,代碼行數:96,代碼來源:validate.go


注:本文中的github.com/mitchellh/packer/template.ParseFile函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。