// Checks to see if template exists in templatePaths, if so it is skipped (templates are imported in order
// reads the template file into memory, replaces namespace keys with module (if found
436099
func (runtimeLoader *templateRuntime) findAndAddTemplate(path, fullSrcDir, basePath string) (fileBytes []byte, err error) {
	templateName := filepath.ToSlash(path[len(fullSrcDir)+1:])
	// Convert template names to use forward slashes, even on Windows.
	if os.PathSeparator == '\\' {
		templateName = strings.Replace(templateName, `\`, `/`, -1) // `
	}

	// Check to see if template was found
	if place, found := runtimeLoader.TemplatePaths[templateName]; found {
		templateLog.Debug("findAndAddTemplate: Not Loading, template is already exists: ", "name", templateName, "old",
			place, "new", path)
		return
	}

	fileBytes, err = ioutil.ReadFile(path)
	if err != nil {
		templateLog.Error("findAndAddTemplate: Failed reading file:", "path", path, "error", err)
		return
	}
	// Parse template file and replace the "_LOCAL_|" in the template with the module name
	// allow for namespaces to be renamed "_LOCAL_(.*?)|"
	if module := ModuleFromPath(path, false); module != nil {
		fileBytes = namespaceReplace(fileBytes, module)
	}

	// if we have an engine picked for this template process it now
	baseTemplate := NewBaseTemplate(templateName, path, basePath, fileBytes)

	// Try to find a default engine for the file
	for _, engine := range runtimeLoader.templatesAndEngineList {
		if engine.Handles(baseTemplate) {
			_, err = runtimeLoader.loadIntoEngine(engine, baseTemplate)
			return
		}
	}

	// Try all engines available
	var defaultError error
	for _, engine := range runtimeLoader.templatesAndEngineList {
		if loaded, loaderr := runtimeLoader.loadIntoEngine(engine, baseTemplate); loaded {
			return
		} else {
			templateLog.Debugf("findAndAddTemplate: Engine '%s' unable to compile %s %s", engine.Name(), path, loaderr.Error())
			if defaultError == nil {
				defaultError = loaderr
			}
		}
	}

	// Assign the error from the first parser
	err = defaultError

	// No engines could be found return the err
	if err == nil {
		err = fmt.Errorf("Failed to parse template file using engines %s", path)
	}

	return
}
502245
func (p *Plugin) GetTemplate(name string) (*process.Template, error) {
	if p.tReader == nil {
		return nil, errors.Errorf("cannot read process template %s: reader is nil (no path was defined)", name)
	}
	templates, err := p.tReader.GetAllTemplates()
	if err != nil {
		return nil, err
	}
	for _, tmp := range templates {
		if tmp.Name == name {
			return tmp, nil
		}
	}
	return nil, nil
}
1117695
func (t *Template) Templates() []*Template {
	if t.common == nil {
		return nil
	}
	// Return a slice so we don't expose the map.
	m := make([]*Template, 0, len(t.tmpl))
	for _, v := range t.tmpl {
		m = append(m, v)
	}
	return m
}
107554
func (engine *GoEngine) Lookup(templateName string) Template {
	// Case-insensitive matching of template file name
	if tpl, found := engine.templatesByName[engine.ConvertPath(templateName)]; found {
		return tpl
	}
	return nil
}
1255640
func (c *templateInstances) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *template.TemplateInstance, err error) {
	result = &template.TemplateInstance{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("templateinstances").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return
}
669638
func completeTemplate(source io.Reader) (io.Reader, error) {
	template := make(map[string]interface{})
	err := json.NewDecoder(source).Decode(&template)
	if err != nil {
		return nil, err
	}
	if typesVal, ok := template["types"]; ok {
		types, ok := typesVal.(map[string]interface{})
		if !ok {
			return nil, errors.New("bad template, expected types as object")
		}
		mappings, ok := template["mappings"]
		if ok {
			replaceTypes(types, types)
			replaceTypes(mappings, types)
		}
		delete(template, "types")
	}
	b, err := json.MarshalIndent(template, "", "  ")
	if err != nil {
		return nil, err
	}
	return bytes.NewReader(b), nil
}
740593
func (a *ArgType) TemplateSet() *TemplateSet {
	if a.templateSet == nil {
		a.templateSet = &TemplateSet{
			funcs: a.NewTemplateFuncs(),
			l:     a.TemplateLoader,
			tpls:  map[string]*template.Template{},
		}
	}

	return a.templateSet
}
459223
func LoadTemplate(path string) (*wfv1.Template, error) {
	var tmpl wfv1.Template
	err := unmarshalAnnotationField(path, common.AnnotationKeyTemplate, &tmpl)
	if err != nil {
		return nil, err
	}
	return &tmpl, nil
}
647824
func (loader *TemplateLoader) Load(fs filesystem.Filespace, subPath string) error {
	bytes, err := fs.ReadFile(subPath)
	if err != nil {
		return err
	}
	loader.muTemplate.Lock()
	defer loader.muTemplate.Unlock()
	if len(bytes) == 0 {
		return fmt.Errorf("empty file")
	}
	if _, err := loader.template.Parse(string(bytes)); err != nil {
		return fmt.Errorf("%v: %v", subPath, err)
	}
	return nil
}
829870
func ParseTemplateError(err error) (templateName string, line int, description string) {
	if e, ok := err.(*Error); ok {
		return "", e.Line, e.Description
	}

	description = err.Error()
	i := regexp.MustCompile(`:\d+:`).FindStringIndex(description)
	if i != nil {
		line, err = strconv.Atoi(description[i[0]+1 : i[1]-1])
		if err != nil {
			templateLog.Error("ParseTemplateError: Failed to parse line number from error message:", "error", err)
		}
		templateName = description[:i[0]]
		if colon := strings.Index(templateName, ":"); colon != -1 {
			templateName = templateName[colon+1:]
		}
		templateName = strings.TrimSpace(templateName)
		description = description[i[1]+1:]
	}
	return templateName, line, description
}
793145
func (tm *TaskTemplateManager) allTemplatesNoop() bool {
	for _, tmpl := range tm.config.Templates {
		if tmpl.ChangeMode != structs.TemplateChangeModeNoop {
			return false
		}
	}

	return true
}
1205654
func NewTemplateReader(path string, log logging.Logger) (*Reader, error) {
	reader := &Reader{
		log:  log,
		path: path,
	}

	if _, err := os.Stat(path); os.IsNotExist(err) {
		if err := os.MkdirAll(path, DefaultMode); err != nil {
			return nil, errors.Errorf("cannot initialize template reader: path processing error: %v", err)
		}
	}
	return reader, nil
}
1295341
func ParseFile(path string) (*Template, error) {
	var f *os.File
	var err error
	if path == "-" {
		// Create a temp file for stdin in case of errors
		f, err = tmp.File("parse")
		if err != nil {
			return nil, err
		}
		defer os.Remove(f.Name())
		defer f.Close()
		io.Copy(f, os.Stdin)
		f.Seek(0, os.SEEK_SET)
	} else {
		f, err = os.Open(path)
		if err != nil {
			return nil, err
		}
		defer f.Close()
	}
	tpl, err := Parse(f)
	if err != nil {
		syntaxErr, ok := err.(*json.SyntaxError)
		if !ok {
			return nil, err
		}
		// Rewind the file and get a better error
		f.Seek(0, os.SEEK_SET)
		// Grab the error location, and return a string to point to offending syntax error
		line, col, highlight := highlightPosition(f, syntaxErr.Offset)
		err = fmt.Errorf("Error parsing JSON: %s\nAt line %d, column %d (offset %d):\n%s", err, line, col, syntaxErr.Offset, highlight)
		return nil, err
	}

	if !filepath.IsAbs(path) {
		path, err = filepath.Abs(path)
		if err != nil {
			return nil, err
		}
	}

	tpl.Path = path
	return tpl, nil
}
579746
func ValidateTemplateInstance(templateInstance *templateapi.TemplateInstance) (allErrs field.ErrorList) {
	allErrs = validation.ValidateObjectMeta(&templateInstance.ObjectMeta, true, ValidateTemplateInstanceName, field.NewPath("metadata"))

	// Allow the nested template name and namespace to be empty.  If not empty,
	// the fields should pass validation.
	templateCopy := templateInstance.Spec.Template.DeepCopy()
	if templateCopy.Name == "" {
		templateCopy.Name = "dummy"
	}
	if templateCopy.Namespace == "" {
		templateCopy.Namespace = "dummy"
	}
	for _, err := range ValidateTemplate(templateCopy) {
		err.Field = "spec.template." + err.Field
		allErrs = append(allErrs, err)
	}
	if templateInstance.Spec.Secret != nil {
		if templateInstance.Spec.Secret.Name != "" {
			for _, msg := range validation.ValidateSecretName(templateInstance.Spec.Secret.Name, false) {
				allErrs = append(allErrs, field.Invalid(field.NewPath("spec.secret.name"), templateInstance.Spec.Secret.Name, msg))
			}
		} else {
			allErrs = append(allErrs, field.Required(field.NewPath("spec.secret.name"), ""))
		}
	}
	if templateInstance.Spec.Requester == nil {
		allErrs = append(allErrs, field.Required(field.NewPath("spec.requester"), ""))
	} else if templateInstance.Spec.Requester.Username == "" {
		allErrs = append(allErrs, field.Required(field.NewPath("spec.requester.username"), ""))
	}
	return
}
1368964
func Convert_v1_TemplateInstanceSpec_To_template_TemplateInstanceSpec(in *v1.TemplateInstanceSpec, out *template.TemplateInstanceSpec, s conversion.Scope) error {
	return autoConvert_v1_TemplateInstanceSpec_To_template_TemplateInstanceSpec(in, out, s)
}
1190328
func (f ES6Formatter) Template(name string) (string, string) {
	return ES6Identifier(name), "export function " + ES6Identifier(name)
}
684564
func (r *Reader) GetAllTemplates() ([]*process.Template, error) {
	var templates []*process.Template
	entries, err := ioutil.ReadDir(r.path)
	if err != nil {
		return templates, errors.Errorf("failed to open process template path %s: %v", r.path, err)
	}
	// From this point, log all errors bot continue reading
	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}
		if filepath.Ext(entry.Name()) != JSONExt {
			continue
		}
		filePath := filepath.Join(r.path, entry.Name())
		file, err := ioutil.ReadFile(filePath)
		if err != nil {
			r.log.Errorf("failed to read file %s: %v", filePath, err)
			continue
		}
		template := &process.Template{}
		if err := json.Unmarshal(file, template); err != nil {
			r.log.Errorf("failed to unmarshal file %s: %v", filePath, err)
			continue
		}

		templates = append(templates, template)
	}

	r.log.Debugf("read %d process template(s)", len(templates))

	return templates, nil
}