github.com/mutagen-io/mutagen@v0.18.0-rc1/cmd/mutagen/common/templating/flags.go (about)

     1  package templating
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"text/template"
     8  	"unicode/utf8"
     9  
    10  	"github.com/spf13/pflag"
    11  )
    12  
    13  // TemplateFlags stores command line formatting flags and provides for their
    14  // registration and handling.
    15  type TemplateFlags struct {
    16  	// template stores the value of the --template flag.
    17  	template string
    18  	// templateFile stores the value of the --template-file flag.
    19  	templateFile string
    20  }
    21  
    22  // Register registers the flags into the specified flag set.
    23  func (f *TemplateFlags) Register(flags *pflag.FlagSet) {
    24  	flags.StringVar(&f.template, "template", "", "Specify an output template")
    25  	flags.StringVar(&f.templateFile, "template-file", "", "Specify a file containing an output template")
    26  }
    27  
    28  // LoadTemplate loads the template specified by the flags. If no template has
    29  // been specified, then it returns nil with no error. Template literals
    30  // specified via the command line will have a trailing newline added.
    31  func (f *TemplateFlags) LoadTemplate() (*template.Template, error) {
    32  	// Figure out if there's a template to be processed. If not, then no valid
    33  	// template has been specified and we can just return. If a template literal
    34  	// was provided directly on the command line, then add a trailing newline to
    35  	// make typical command line usage more friendly.
    36  	var literal string
    37  	if f.template != "" {
    38  		literal = f.template + "\n"
    39  	} else if f.templateFile != "" {
    40  		if l, err := os.ReadFile(f.templateFile); err != nil {
    41  			return nil, fmt.Errorf("unable to load template: %w", err)
    42  		} else if !utf8.Valid(l) {
    43  			return nil, errors.New("template file is not UTF-8 encoded")
    44  		} else {
    45  			literal = string(l)
    46  		}
    47  	} else {
    48  		return nil, nil
    49  	}
    50  
    51  	// Create the template and register built-in functions.
    52  	result := template.New("")
    53  	result.Funcs(builtins)
    54  
    55  	// Parse the template literal.
    56  	return result.Parse(literal)
    57  }