go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/copyright/helpers.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package copyright
     9  
    10  import (
    11  	"bytes"
    12  	"strings"
    13  	"text/template"
    14  )
    15  
    16  func mustRenderTemplate(text string, viewmodel any) string {
    17  	output, err := renderTemplate(text, viewmodel)
    18  	if err != nil {
    19  		panic(err)
    20  	}
    21  	return output
    22  }
    23  
    24  func renderTemplate(text string, viewmodel any) (string, error) {
    25  	tmpl := template.New("output")
    26  	tmpl = tmpl.Funcs(template.FuncMap{
    27  		"prefix": prefix,
    28  	})
    29  	compiled, err := tmpl.Parse(text)
    30  	if err != nil {
    31  		return "", err
    32  	}
    33  
    34  	output := new(bytes.Buffer)
    35  	if err = compiled.Execute(output, viewmodel); err != nil {
    36  		return "", err
    37  	}
    38  	return output.String(), nil
    39  }
    40  
    41  func prefix(prefix string, s string) string {
    42  	lines := strings.Split(s, "\n")
    43  	var output []string
    44  	for _, l := range lines {
    45  		output = append(output, prefix+l)
    46  	}
    47  	return strings.Join(output, "\n")
    48  }