// runToolBoxTemplate is the action for the command
337119
func runToolBoxTemplate(f *util.Factory, out io.Writer, options *toolboxTemplateOption) error {
	// @step: read in the configuration if any
	context, err := newTemplateContext(options.configPath, options.values, options.stringValues)
	if err != nil {
		return err
	}
	context["clusterName"] = options.clusterName

	// @check if we are just rendering the config value
	if options.configValue != "" {
		v, found := context[options.configValue]
		switch found {
		case true:
			fmt.Fprintf(out, "%v\n", v)
		default:
			fmt.Fprintf(out, "null\n")
		}
		return nil
	}

	// @step: expand the list of templates into a list of files to render
	var templates []string
	for _, x := range options.templatePath {
		list, err := expandFiles(utils.ExpandPath(x))
		if err != nil {
			return fmt.Errorf("unable to expand the template: %s, error: %s", x, err)
		}
		templates = append(templates, list...)
	}

	snippets := make(map[string]string, 0)
	for _, x := range options.snippetsPath {
		list, err := expandFiles(utils.ExpandPath(x))
		if err != nil {
			return fmt.Errorf("unable to expand the snippets: %s, error: %s", x, err)
		}

		for _, j := range list {
			content, err := ioutil.ReadFile(j)
			if err != nil {
				return fmt.Errorf("unable to read snippet: %s, error: %s", j, err)
			}
			snippets[path.Base(j)] = string(content)
		}
	}

	// @step: render each of the templates, splitting on the documents
	r := templater.NewTemplater()
	var documents []string
	for _, x := range templates {
		content, err := ioutil.ReadFile(x)
		if err != nil {
			return fmt.Errorf("unable to read template: %s, error: %s", x, err)
		}

		rendered, err := r.Render(string(content), context, snippets, options.failOnMissing)
		if err != nil {
			return fmt.Errorf("unable to render template: %s, error: %s", x, err)
		}
		// @check if the content is zero ignore it
		if len(rendered) <= 0 {
			continue
		}

		if !options.formatYAML {
			documents = append(documents, strings.Split(rendered, "---\n")...)
			continue
		}

		for _, x := range strings.Split(rendered, "---\n") {
			var data map[string]interface{}
			if err := yaml.Unmarshal([]byte(x), &data); err != nil {
				return fmt.Errorf("unable to unmarshall content from template: %s, error: %s", x, err)
			}
			if len(data) <= 0 {
				continue
			}
			formatted, err := yaml.Marshal(&data)
			if err != nil {
				return fmt.Errorf("unable to marhshal formatted content to yaml: %s", err)
			}
			documents = append(documents, string(formatted))
		}
	}
	// join in harmony all the YAML documents back together
	content := strings.Join(documents, "---\n")

	iowriter := out
	// @check if we are writing to a file rather than stdout
	if options.outputPath != "" {
		w, err := os.OpenFile(utils.ExpandPath(options.outputPath), os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0660)
		if err != nil {
			return fmt.Errorf("unable to open file: %s, error: %v", options.outputPath, err)
		}
		defer try.CloseFile(w)
		iowriter = w
	}

	if _, err := iowriter.Write([]byte(content)); err != nil {
		return fmt.Errorf("unable to write template: %s", err)
	}

	return nil
}
235670
func (o *ProcessOptions) RunProcess() error {
	duplicatedKeys := sets.NewString()
	params, paramErr := app.ParseAndCombineEnvironment(o.templateParams, o.paramFile, o.In, func(key, file string) error {
		if file == "" {
			duplicatedKeys.Insert(key)
		} else {
			fmt.Fprintf(o.ErrOut, "warning: Template parameter %q already defined, ignoring value from file %q\n", key, file)
		}
		return nil
	})
	if len(duplicatedKeys) != 0 {
		return o.usageErrorFn(fmt.Sprintf("The following parameters were provided more than once: %s", strings.Join(duplicatedKeys.List(), ", ")))
	}

	if len(o.templateName) == 0 && len(o.filename) == 0 {
		return o.usageErrorFn("Must pass a filename or name of stored template")
	}

	var infos []*resource.Info

	// When templateName is not empty, then we fetch the template from the
	// server, otherwise we require to set the `-f` parameter.
	if len(o.templateName) > 0 && !o.local {
		if o.templateClient == nil {
			return fmt.Errorf("attempt to fetch template from server with nil template client")
		}

		var (
			storedTemplate, rs string
			sourceNamespace    string
			ok                 bool
		)
		sourceNamespace, rs, storedTemplate, ok = parseNamespaceResourceName(o.templateName, o.namespace)
		if !ok {
			return fmt.Errorf("invalid argument %q", o.templateName)
		}
		if len(rs) > 0 && (rs != "template" && rs != "templates") {
			return fmt.Errorf("unable to process invalid resource %q", rs)
		}
		if len(storedTemplate) == 0 {
			return fmt.Errorf("invalid value syntax %q", o.templateName)
		}

		templateObj, err := o.templateClient.Templates(sourceNamespace).Get(storedTemplate, metav1.GetOptions{})
		if err != nil {
			if errors.IsNotFound(err) {
				return fmt.Errorf("template %q could not be found", storedTemplate)
			}
			return err
		}
		templateObj.CreationTimestamp = metav1.Now()
		infos = append(infos, &resource.Info{Object: templateObj})
	} else {
		var err error
		infos, err = o.builderFn().
			WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
			LocalParam(o.local).
			FilenameParam(o.explicitNamespace, &resource.FilenameOptions{Recursive: false, Filenames: []string{o.filename}}).
			Do().
			Infos()
		if err != nil {
			return fmt.Errorf("failed to read input object (not a Template?): %v", err)
		}
	}

	if len(infos) > 1 {
		// in order to run validation on the input given to us by a user, we only support the processing
		// of one template in a list. For instance, we want to be able to fail when a user does not give
		// a parameter that the template wants or when they give a parameter the template doesn't need,
		// as this may indicate that they have mis-used `oc process`. This is much less complicated when
		// we process at most one template.
		fmt.Fprintf(o.Out, "%d input templates found, but only the first will be processed\n", len(infos))
	}

	obj, ok := infos[0].Object.(*templatev1.Template)
	if !ok {
		sourceName := o.filename
		if len(o.templateName) > 0 {
			sourceName = o.namespace + "/" + o.templateName
		}
		return fmt.Errorf("unable to parse %q, not a valid Template but %s\n", sourceName, reflect.TypeOf(infos[0].Object))
	}

	// If 'parameters' flag is set it does not do processing but only print
	// the template parameters to console for inspection.
	if o.parameters {
		// TODO(juanvallejo): remove once we have external describers
		internalTemplate := &templateapi.Template{}
		if err := templateapiv1.Convert_v1_Template_To_template_Template(obj, internalTemplate, nil); err != nil {
			return err
		}
		return describe.PrintTemplateParameters(internalTemplate.Parameters, o.Out)
	}

	if label := o.labels; len(label) > 0 {
		lbl, err := generate.ParseLabels(label)
		if err != nil {
			return fmt.Errorf("error parsing labels: %v\n", err)
		}
		if obj.ObjectLabels == nil {
			obj.ObjectLabels = make(map[string]string)
		}
		for key, value := range lbl {
			obj.ObjectLabels[key] = value
		}
	}

	// Raise parameter parsing errors here after we had chance to return UsageErrors first
	if paramErr != nil {
		return paramErr
	}
	if errs := injectUserVars(params, obj, o.ignoreUnknownParams); errs != nil {
		return kerrors.NewAggregate(errs)
	}

	resultObj := obj
	resultObj, err := o.templateProcessor(obj)
	if err != nil {
		return err
	}

	if o.outputFormat == "describe" {
		return o.Printer.PrintObj(resultObj, o.Out)
	}

	// attempt to convert our resulting object to external
	var externalResultObj templatev1.Template
	if err := legacyscheme.Scheme.Convert(resultObj, &externalResultObj, nil); err != nil {
		return fmt.Errorf("unable to convert template to external template object: %v", err)
	}

	// the name printer does not accept object lists, so re-use
	// the print loop used for --raw printing instead.
	if o.outputFormat == "name" || o.raw {
		for _, obj := range externalResultObj.Objects {
			objToPrint := obj.Object

			if objToPrint == nil {
				converted, err := runtime.Decode(unstructured.UnstructuredJSONScheme, obj.Raw)
				if err != nil {
					return err
				}

				objToPrint = converted
			}

			if err := o.Printer.PrintObj(objToPrint, o.Out); err != nil {
				return err
			}
		}

		return nil
	}

	return o.Printer.PrintObj(&corev1.List{
		ListMeta: metav1.ListMeta{},
		Items:    externalResultObj.Objects,
	}, o.Out)
}
433294
func ValidateTemplate(template *templateapi.Template) (allErrs field.ErrorList) {
	allErrs = validation.ValidateObjectMeta(&template.ObjectMeta, true, ValidateTemplateName, field.NewPath("metadata"))
	allErrs = append(allErrs, validateTemplateBody(template)...)
	return
}
822224
func templateRunner(config *TaskTemplateManagerConfig) (
	*manager.Runner, map[string][]*structs.Template, error) {

	if len(config.Templates) == 0 {
		return nil, nil, nil
	}

	// Parse the templates
	ctmplMapping, err := parseTemplateConfigs(config)
	if err != nil {
		return nil, nil, err
	}

	// Create the runner configuration.
	runnerConfig, err := newRunnerConfig(config, ctmplMapping)
	if err != nil {
		return nil, nil, err
	}

	runner, err := manager.NewRunner(runnerConfig, false, false)
	if err != nil {
		return nil, nil, err
	}

	// Set Nomad's environment variables
	runner.Env = config.EnvBuilder.Build().All()

	// Build the lookup
	idMap := runner.TemplateConfigMapping()
	lookup := make(map[string][]*structs.Template, len(idMap))
	for id, ctmpls := range idMap {
		for _, ctmpl := range ctmpls {
			templates := lookup[id]
			templates = append(templates, ctmplMapping[ctmpl])
			lookup[id] = templates
		}
	}

	return runner, lookup, nil
}
841929
func (s *TemplateService) UpdateTemplate(p *UpdateTemplateParams) (*UpdateTemplateResponse, error) {
	resp, err := s.cs.newRequest("updateTemplate", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r UpdateTemplateResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
1336180
func GenerateTemplate(filename, templateSource string, args map[string]interface{}) (err error) {
	tmpl := template.Must(template.New("").Parse(templateSource))

	var b bytes.Buffer
	if err = tmpl.Execute(&b, args); err != nil {
		return NewBuildIfError(err, "ExecuteTemplate: Execute failed")
	}
	sourceCode := b.String()
	filePath := filepath.Dir(filename)
	if !DirExists(filePath) {
		err = os.MkdirAll(filePath, 0777)
		if err != nil && !os.IsExist(err) {
			return NewBuildIfError(err, "Failed to make directory", "dir", filePath)
		}
	}

	// Create the file
	file, err := os.Create(filename)
	if err != nil {
		Logger.Fatal("Failed to create file", "error", err)
		return
	}
	defer func() {
		_ = file.Close()
	}()

	if _, err = file.WriteString(sourceCode); err != nil {
		Logger.Fatal("Failed to write to file: ", "error", err)
	}

	return
}
404208
func NewButtonsTemplate(thumbnailImageURL, title, text string, actions ...TemplateAction) *ButtonsTemplate {
	return &ButtonsTemplate{
		ThumbnailImageURL: thumbnailImageURL,
		Title:             title,
		Text:              text,
		Actions:           actions,
	}
}
468345
func (mg *MailgunImpl) UpdateTemplate(ctx context.Context, template *Template) error {
	if template.Name == "" {
		return errors.New("UpdateTemplate() Template.Name cannot be empty")
	}

	r := newHTTPRequest(generateApiUrl(mg, templatesEndpoint) + "/" + template.Name)
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.APIKey())
	p := newUrlEncodedPayload()

	if template.Name != "" {
		p.addValue("name", template.Name)
	}
	if template.Description != "" {
		p.addValue("description", template.Description)
	}

	var resp templateResp
	err := putResponseFromJSON(ctx, r, p, &resp)
	if err != nil {
		return err
	}
	*template = resp.Item
	return nil
}
623915
func (c *Client) ExtractTemplate(p *ExtractTemplateParameter) (*Template, error) {
	obj, err := c.Request("extractTemplate", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Template), err
}
378808
func (c *Controller) RenderTemplate(templatePath string) Result {
	c.setStatusIfNil(http.StatusOK)

	// Get the Template.
	lang, _ := c.ViewArgs[CurrentLocaleViewArg].(string)
	template, err := MainTemplateLoader.TemplateLang(templatePath, lang)
	if err != nil {
		return c.RenderError(err)
	}

	return &RenderTemplateResult{
		Template: template,
		ViewArgs: c.ViewArgs,
	}
}
761160
func RunTemplates(o *Config) error {
	Metrics = newMetrics()
	defer runCleanupHooks()
	// make sure config is sane
	o.defaults()
	ds := append(o.DataSources, o.Contexts...)
	d, err := data.NewData(ds, o.DataSourceHeaders)
	if err != nil {
		return err
	}
	addCleanupHook(d.Cleanup)
	nested, err := parseTemplateArgs(o.Templates)
	if err != nil {
		return err
	}
	c, err := createContext(o.Contexts, d)
	if err != nil {
		return err
	}
	g := newGomplate(d, o.LDelim, o.RDelim, nested, c)

	return g.runTemplates(o)
}
246243
func expandTemplate(tmpl string) (pkg string, err error) {
	pkg, err = template.DefaultExpander().Expand(tmpl)
	if err != nil {
		err = commandLineError{err}
	}
	return
}
450591
func (c *Client) CreateTemplate(p *CreateTemplateParameter) (*Template, error) {
	obj, err := c.Request("createTemplate", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Template), err
}
1230289
func ExecuteTemplate(w io.Writer, templateText string, data interface{}) error {
	t := template.New("top")
	t.Funcs(template.FuncMap{
		"trim": strings.TrimSpace,
		"wrap": wrap,
	})
	template.Must(t.Parse(templateText))
	return t.Execute(w, data)
}
731545
func mkCommandsTemplate(genTemplate func(commandDoc) string) string {
	template := "{{if false}}"
	for _, command := range append(commands) {
		template = template + fmt.Sprintf("{{else if (eq .Name %q)}}%s", command.Name, genTemplate(commandDocs[command.Name]))
	}
	return template + "{{end}}"
}
1019841
func (f *SourceFile) ExecuteTemplate(name, source string, funcMap template.FuncMap, data interface{}) error {
	tmpl, err := template.New(name).Funcs(DefaultFuncMap).Funcs(funcMap).Parse(source)
	if err != nil {
		panic(err) // bug
	}
	return tmpl.Execute(f, data)
}
731379
func (loader *FileSystemLoader) LoadTemplate(name string) (string, error) {
	f, err := os.Open(path.Join(loader.BaseDir, name))
	if err != nil {
		return "", err
	}
	b, err := ioutil.ReadAll(f)
	return string(b), err
}