func processFilePath()

in pkg/template/cmdutil/values.go [100:192]


func processFilePath(currentDirectory, filePath string, result interface{}) error {
	defer func() {
		log.CheckErr("unable to reset to current working directory", os.Chdir(currentDirectory))
	}()

	// Check for type overrides
	parts := strings.Split(filePath, ":")

	filePath = parts[0]
	valuePrefix := ""
	inputType := ""

	if len(parts) > 1 {
		var err error

		// Expand if using homedir alias
		filePath, err = cmdutil.Expand(filePath)
		if err != nil {
			return fmt.Errorf("unable to expand homedir: %w", err)
		}

		// <type>:<path>
		inputType = parts[1]

		// Check prefix usage
		// <path>:<type>:<prefix>
		if len(parts) > 2 {
			valuePrefix = parts[2]
		}
	}

	// Retrieve file type from extension
	fileType := getFileType(filePath, inputType)

	// Retrieve appropriate parser
	p, err := values.GetParser(fileType)
	if err != nil {
		return fmt.Errorf("error occurred during parser instance retrieval for type '%s': %w", fileType, err)
	}

	// Drain file content
	_, err = os.Stat(filePath)
	if err != nil {
		return fmt.Errorf(
			"unable to os.Stat file name %s before attempting to build reader from current directory %s: error: %w",
			filePath,
			currentDirectory,
			err,
		)
	}

	reader, err := cmdutil.Reader(filePath)
	if err != nil {
		return fmt.Errorf("unable to build a reader from '%s' for current directory %s: %w",
			filePath,
			currentDirectory,
			err)
	}

	// Drain reader
	var contentBytes []byte
	contentBytes, err = io.ReadAll(reader)
	if err != nil {
		return fmt.Errorf("unable to drain all reader content from '%s': %w", filePath, err)
	}

	// Check prefix
	if valuePrefix != "" {
		// Parse with detected parser
		var fileContent interface{}
		if err := p.Unmarshal(contentBytes, &fileContent); err != nil {
			return fmt.Errorf("unable to unmarshal content from '%s' as '%s': %w", filePath, fileType, err)
		}

		// Re-encode JSON prepending the prefix
		var buf bytes.Buffer
		if err := json.NewEncoder(&buf).Encode(map[string]interface{}{
			valuePrefix: fileContent,
		}); err != nil {
			return fmt.Errorf("unable to re-encode as JSON with prefix '%s', content from '%s' as '%s': %w", valuePrefix, filePath, fileType, err)
		}

		// Send as result
		if err := json.NewDecoder(&buf).Decode(result); err != nil {
			return fmt.Errorf("unable to decode json content from '%s' parsed as '%s': %w", filePath, fileType, err)
		}
	} else if err := p.Unmarshal(contentBytes, result); err != nil {
		return fmt.Errorf("unable to unmarshal content from '%s' as '%s', you should use an explicit prefix: %w", filePath, fileType, err)
	}

	// No error
	return nil
}