// makeTemplateTheOldWay is an implementation of makeTemplate that uses the
// older pre-Stringable syntax. If this file builds, then maybe we haven't broken
// backcompat.
161785
func makeTemplateTheOldWay() *cf.Template {
	t := cf.NewTemplate()
	t.Description = "example production infrastructure"
	t.Parameters["DnsName"] = &cf.Parameter{
		Description: "The top level DNS name for the infrastructure",
		Type:        "String",
		Default:     "preview.example.io",
	}

	t.AddResource("ServerLoadBalancer", cf.ElasticLoadBalancingLoadBalancer{
		ConnectionDrainingPolicy: &cf.ElasticLoadBalancingConnectionDrainingPolicy{
			Enabled: cf.Bool(true),
			Timeout: cf.Integer(30),
		},
		CrossZone: cf.Bool(true),
		HealthCheck: &cf.ElasticLoadBalancingHealthCheck{
			HealthyThreshold:   cf.String("2"),
			Interval:           cf.String("60"),
			Target:             cf.String("HTTP:80/"),
			Timeout:            cf.String("5"),
			UnhealthyThreshold: cf.String("2"),
		},
		Listeners: &cf.ElasticLoadBalancingListenerList{
			cf.ElasticLoadBalancingListener{
				InstancePort:     cf.String("8000"),
				InstanceProtocol: cf.String("TCP"),
				LoadBalancerPort: cf.String("443"),
				Protocol:         cf.String("SSL"),
				SSLCertificateId: cf.Join("",
					*cf.String("arn:aws:iam::"),
					*cf.Ref("AWS::AccountID").String(),
					*cf.String(":server-certificate/"),
					*cf.Ref("DnsName").String()).String(),
			},
		},
		Policies: &cf.ElasticLoadBalancingPolicyList{
			cf.ElasticLoadBalancingPolicy{
				PolicyName: cf.String("EnableProxyProtocol"),
				PolicyType: cf.String("ProxyProtocolPolicyType"),
				Attributes: []map[string]interface{}{
					map[string]interface{}{
						"Name":  "ProxyProtocol",
						"Value": "true",
					},
				},
				InstancePorts: []int{8000},
			},
		},
		Subnets: cf.StringList(
			*cf.Ref("VpcSubnetA").String(),
			*cf.Ref("VpcSubnetB").String(),
			*cf.Ref("VpcSubnetC").String(),
		),
		SecurityGroups: cf.StringList(*cf.Ref("LoadBalancerSecurityGroup").String()),
	})

	return t
}
23614
func RenderTemplate(destPath, srcPath string, data interface{}) (err error) {
	tmpl, err := template.ParseFiles(srcPath)
	if err != nil {
		return NewBuildIfError(err, "Failed to parse template "+srcPath)
	}

	f, err := os.Create(destPath)
	if err != nil {
		return NewBuildIfError(err, "Failed to create  ", "path", destPath)
	}

	err = tmpl.Execute(f, data)
	if err != nil {
		return NewBuildIfError(err, "Failed to Render template "+srcPath)
	}

	err = f.Close()
	if err != nil {
		return NewBuildIfError(err, "Failed to close file stream "+destPath)
	}
	return
}
858962
func (c *Client) CopyTemplate(p *CopyTemplateParameter) (*Template, error) {
	obj, err := c.Request("copyTemplate", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Template), err
}
963625
func (c *AppConfig) buildTemplates(components app.ComponentReferences, parameters app.Environment, environment app.Environment, buildEnvironment app.Environment, templateProcessor templateclientv1.TemplateProcessorInterface) (string, []runtime.Object, error) {
	objects := []runtime.Object{}
	name := ""
	for _, ref := range components {
		tpl := ref.Input().ResolvedMatch.Template

		klog.V(4).Infof("processing template %s/%s", c.OriginNamespace, tpl.Name)
		if len(c.ContextDir) > 0 {
			return "", nil, fmt.Errorf("--context-dir is not supported when using a template")
		}
		result, err := TransformTemplate(tpl, templateProcessor, c.OriginNamespace, parameters, c.IgnoreUnknownParameters)
		if err != nil {
			return name, nil, err
		}
		if len(name) == 0 {
			name = tpl.Name
		}
		resultObjects, err := templateObjectsToAppObjects(result.Objects)
		if err != nil {
			return "", nil, err
		}

		objects = append(objects, resultObjects...)
		if len(resultObjects) > 0 {
			// if environment variables were passed in, let's apply the environment variables
			// to every pod template object
			for _, obj := range resultObjects {
				if bc, ok := obj.(*buildv1.BuildConfig); ok {
					buildEnv := getBuildConfigEnv(bc)
					buildEnv = app.JoinEnvironment(buildEnv, buildEnvironment.List())
					setBuildConfigEnv(bc, buildEnv)
				}
				podSpec, _, err := ometa.GetPodSpecV1(obj)
				if err == nil {
					for ii := range podSpec.Containers {
						if podSpec.Containers[ii].Env != nil {
							podSpec.Containers[ii].Env = app.JoinEnvironment(environment.List(), podSpec.Containers[ii].Env)
						} else {
							podSpec.Containers[ii].Env = environment.List()
						}
					}
				}
			}
		}

		DescribeGeneratedTemplate(c.Out, ref.Input().String(), result, c.OriginNamespace)
	}
	return name, objects, nil
}
1158822
func createPipelineTemplateCommand() *cli.Command {
	return &cli.Command{
		Name:     CreatePipelineTemplateCommandName,
		Usage:    CreatePipelineTemplateCommandUsage,
		Action:   ActionWrapper(createPipelineTemplateAction),
		Category: "Pipeline Templates",
		Flags: []cli.Flag{
			cli.StringFlag{Name: "template-name", Usage: "Pipeline Template name."},
			cli.StringSliceFlag{Name: "stage", Usage: "JSON encoded stage object."},
		},
	}
}
406719
func (t *templateHandler) NewTextTemplate() tpl.TemplateParseFinder {
	t.mu.Lock()
	defer t.mu.Unlock()

	tt := &textTemplate{t: texttemplate.New("")}
	t.extTextTemplates = append(t.extTextTemplates, tt)

	return struct {
		tpl.TemplateParser
		tpl.TemplateLookup
		tpl.TemplateLookupVariant
	}{
		tt,
		tt,
		new(nopLookupVariant),
	}

}
1026563
func (f *Fpdf) CreateTemplateCustom(corner PointType, size SizeType, fn func(*Tpl)) Template {
	return newTpl(corner, size, f.defOrientation, f.unitStr, f.fontDirStr, fn, f)
}
419388
func SetTemplatesFromOrigin(desc *zoekt.Repository, u *url.URL) error {
	desc.Name = filepath.Join(u.Host, strings.TrimSuffix(u.Path, ".git"))

	if strings.HasSuffix(u.Host, ".googlesource.com") {
		return setTemplates(desc, u, "gitiles")
	} else if u.Host == "github.com" {
		u.Path = strings.TrimSuffix(u.Path, ".git")
		return setTemplates(desc, u, "github")
	} else {
		return fmt.Errorf("unknown git hosting site %q", u)
	}
}
1322408
func (loader *TemplateLoader) Template(name string) (tmpl Template, err error) {
	runtimeLoader := loader.runtimeLoader.Load().(*templateRuntime)
	return runtimeLoader.TemplateLang(name, "")
}
789639
func prepareTemplates(templatesPath string) *templates.Bundle {
	return &templates.Bundle{
		Loader:          templates.FileSystemLoader(templatesPath),
		DebugMode:       info.IsDevAppServer,
		DefaultTemplate: "base",
		FuncMap: template.FuncMap{
			// Count returns sequential integers in range [0, n] (inclusive).
			"Count": func(n int) []int {
				out := make([]int, n+1)
				for i := range out {
					out[i] = i
				}
				return out
			},
			// Pair combines two args into one map with keys "First" and "Second", to
			// pass pairs to templates (that in golang can accept only one argument).
			"Pair": func(a1, a2 interface{}) map[string]interface{} {
				return map[string]interface{}{
					"First":  a1,
					"Second": a2,
				}
			},
		},
		DefaultArgs: func(c context.Context, e *templates.Extra) (templates.Args, error) {
			loginURL, err := auth.LoginURL(c, e.Request.URL.RequestURI())
			if err != nil {
				return nil, err
			}
			logoutURL, err := auth.LogoutURL(c, e.Request.URL.RequestURI())
			if err != nil {
				return nil, err
			}
			token, err := xsrf.Token(c)
			if err != nil {
				return nil, err
			}
			return templates.Args{
				"AppVersion":  strings.Split(info.VersionID(c), ".")[0],
				"IsAnonymous": auth.CurrentIdentity(c) == "anonymous:anonymous",
				"User":        auth.CurrentUser(c),
				"LoginURL":    loginURL,
				"LogoutURL":   logoutURL,
				"XsrfToken":   token,
				"HandlerDuration": func() time.Duration {
					return clock.Now(c).Sub(startTime(c))
				},
			}, nil
		},
	}
}
1317423
func (q TemplateQuery) Template(name string) TemplateQuery {
	q.template = name
	return q
}
1116940
func (p *Plugin) templateToProcess(tmp *process.Template) (*Process, error) {
	if tmp.Name == "" {
		return nil, errors.Errorf("cannot create process from template, missing name")
	}
	if tmp.Cmd == "" {
		return nil, errors.Errorf("cannot create process from template, missing command")
	}

	pOptions := &POptions{}
	if tmp.POptions != nil {
		pOptions.args = tmp.POptions.Args
		pOptions.outWriter = func(isSet bool) io.Writer {
			if isSet {
				return os.Stdout
			}
			return nil
		}(tmp.POptions.OutWriter)
		pOptions.errWriter = func(isSet bool) io.Writer {
			if isSet {
				return os.Stderr
			}
			return nil
		}(tmp.POptions.ErrWriter)
		pOptions.detach = tmp.POptions.Detach
		pOptions.restart = tmp.POptions.Restart
		pOptions.runOnStartup = tmp.POptions.RunOnStartup
		pOptions.notifyChan = func(notify bool) chan status.ProcessStatus {
			if notify {
				return make(chan status.ProcessStatus)
			}
			return nil
		}(tmp.POptions.Notify)
		pOptions.autoTerm = tmp.POptions.AutoTerminate
	}

	return &Process{
		log:     p.Log,
		name:    tmp.Name,
		cmd:     tmp.Cmd,
		options: pOptions,
		sh:      &status.Reader{Log: p.Log},
		status: &status.File{
			State: status.Initial,
		},
		cancelChan: make(chan struct{}),
	}, nil
}
1083363
func buildURLTemplate(path string) string {
	template, start, end := "", -1, -1
	for i := 0; i < len(path); i++ {
		if path[i] == '<' && start < 0 {
			start = i
		} else if path[i] == '>' && start >= 0 {
			name := path[start+1 : i]
			for j := start + 1; j < i; j++ {
				if path[j] == ':' {
					name = path[start+1 : j]
					break
				}
			}
			template += path[end+1:start] + "<" + name + ">"
			end = i
			start = -1
		}
	}
	if end < 0 {
		template = path
	} else if end < len(path)-1 {
		template += path[end+1:]
	}
	return template
}
1140150
func ProcessTemplate(t T, templateContent string, value interface{}) string {
	tmp, err := template.New("temporary").Parse(templateContent)
	if err != nil {
		logfatal(t, sfatalf("failed to parse:%v", err))
		return ""
	}
	var buf bytes.Buffer
	err = tmp.Execute(&buf, value)
	if err != nil {
		logfatal(t, sfatalf("failed to execute template:%v", err))
		return ""
	}
	return buf.String()
}
1344590
func (g *Generator) ProcessTemplate(tmplName, tmpl string, data interface{}) error {
	vars := []string{}
	for varName, varValue := range g.vars {
		vars = append(vars, fmt.Sprintf("{{ $%s := %q }}", varName, varValue))
	}

	if len(vars) > 0 {
		tmpl = strings.Join(vars, "\n") + "\n" + tmpl
	}

	t, err := template.New(tmplName).Funcs(g.templateFuncs).Parse(tmpl)
	if err != nil {
		return fmt.Errorf("failed to parse template: %v\n%s", err, tmpl)
	}

	if err := t.Execute(g.body, data); err != nil {
		return fmt.Errorf("failed to execute template: %v", err)
	}

	return nil
}
239424
func RunTemplate(tmpl *template.Template, data interface{}) string {
	var b bytes.Buffer
	err := tmpl.Execute(&b, data)
	if err != nil {
		panic(err) // should never happen, bug if it does.
	}
	return b.String()
}
246243
func expandTemplate(tmpl string) (pkg string, err error) {
	pkg, err = template.DefaultExpander().Expand(tmpl)
	if err != nil {
		err = commandLineError{err}
	}
	return
}