github.com/tahsinrahman/goreleaser@v0.79.1/internal/filenametemplate/template.go (about)

     1  // Package filenametemplate contains the code used to template names of
     2  // goreleaser's  packages and archives.
     3  package filenametemplate
     4  
     5  import (
     6  	"bytes"
     7  	"text/template"
     8  
     9  	"github.com/goreleaser/goreleaser/context"
    10  	"github.com/goreleaser/goreleaser/internal/artifact"
    11  )
    12  
    13  // Fields contains all accepted fields in the template string
    14  type Fields struct {
    15  	Version     string
    16  	Tag         string
    17  	ProjectName string
    18  	Env         map[string]string
    19  	Os          string
    20  	Arch        string
    21  	Arm         string
    22  	Binary      string
    23  }
    24  
    25  // NewFields returns a Fields instances filled with the data provided
    26  func NewFields(ctx *context.Context, replacements map[string]string, artifacts ...artifact.Artifact) Fields {
    27  	// This will fail if artifacts is empty - should never be though...
    28  	var binary = artifacts[0].Extra["Binary"]
    29  	if len(artifacts) > 1 {
    30  		binary = ctx.Config.ProjectName
    31  	}
    32  	return Fields{
    33  		Env:         ctx.Env,
    34  		Version:     ctx.Version,
    35  		Tag:         ctx.Git.CurrentTag,
    36  		ProjectName: ctx.Config.ProjectName,
    37  		Os:          replace(replacements, artifacts[0].Goos),
    38  		Arch:        replace(replacements, artifacts[0].Goarch),
    39  		Arm:         replace(replacements, artifacts[0].Goarm),
    40  		Binary:      binary,
    41  	}
    42  }
    43  
    44  // Apply applies the given fields to the given template and returns the
    45  // evaluation and any error that might occur.
    46  func Apply(tmpl string, fields Fields) (string, error) {
    47  	t, err := template.New(tmpl).Option("missingkey=error").Parse(tmpl)
    48  	if err != nil {
    49  		return "", err
    50  	}
    51  	var out bytes.Buffer
    52  	err = t.Execute(&out, fields)
    53  	return out.String(), err
    54  }
    55  
    56  func replace(replacements map[string]string, original string) string {
    57  	result := replacements[original]
    58  	if result == "" {
    59  		return original
    60  	}
    61  	return result
    62  }