github.com/marianogappa/goreleaser@v0.26.2-0.20170715090149-96acd0a9fc46/internal/name/name.go (about)

     1  // Package name provides name template logic for the final archive, formulae,
     2  // etc.
     3  package name
     4  
     5  import (
     6  	"bytes"
     7  	"text/template"
     8  
     9  	"github.com/goreleaser/goreleaser/config"
    10  	"github.com/goreleaser/goreleaser/context"
    11  	"github.com/goreleaser/goreleaser/internal/buildtarget"
    12  )
    13  
    14  type nameData struct {
    15  	Os          string
    16  	Arch        string
    17  	Arm         string
    18  	Version     string
    19  	Tag         string
    20  	Binary      string // deprecated
    21  	ProjectName string
    22  }
    23  
    24  // ForBuild return the name for the given context, goos, goarch, goarm and
    25  // build, using the build.Binary property instead of project_name.
    26  func ForBuild(ctx *context.Context, build config.Build, target buildtarget.Target) (string, error) {
    27  	return apply(
    28  		nameData{
    29  			Os:          replace(ctx.Config.Archive.Replacements, target.OS),
    30  			Arch:        replace(ctx.Config.Archive.Replacements, target.Arch),
    31  			Arm:         replace(ctx.Config.Archive.Replacements, target.Arm),
    32  			Version:     ctx.Version,
    33  			Tag:         ctx.Git.CurrentTag,
    34  			Binary:      build.Binary,
    35  			ProjectName: build.Binary,
    36  		},
    37  		ctx.Config.Archive.NameTemplate,
    38  	)
    39  }
    40  
    41  // For returns the name for the given context, goos, goarch and goarm.
    42  func For(ctx *context.Context, target buildtarget.Target) (string, error) {
    43  	return apply(
    44  		nameData{
    45  			Os:          replace(ctx.Config.Archive.Replacements, target.OS),
    46  			Arch:        replace(ctx.Config.Archive.Replacements, target.Arch),
    47  			Arm:         replace(ctx.Config.Archive.Replacements, target.Arm),
    48  			Version:     ctx.Version,
    49  			Tag:         ctx.Git.CurrentTag,
    50  			Binary:      ctx.Config.ProjectName,
    51  			ProjectName: ctx.Config.ProjectName,
    52  		},
    53  		ctx.Config.Archive.NameTemplate,
    54  	)
    55  }
    56  
    57  func apply(data nameData, templateStr string) (string, error) {
    58  	var out bytes.Buffer
    59  	t, err := template.New(data.ProjectName).Parse(templateStr)
    60  	if err != nil {
    61  		return "", err
    62  	}
    63  	err = t.Execute(&out, data)
    64  	return out.String(), err
    65  }
    66  
    67  func replace(replacements map[string]string, original string) string {
    68  	result := replacements[original]
    69  	if result == "" {
    70  		return original
    71  	}
    72  	return result
    73  }