github.phpd.cn/goreleaser/goreleaser@v0.92.0/internal/pipe/env/env.go (about)

     1  // Package env implements the Pipe interface providing validation of
     2  // missing environment variables needed by the release process.
     3  package env
     4  
     5  import (
     6  	"bufio"
     7  	"os"
     8  
     9  	"github.com/goreleaser/goreleaser/internal/pipe"
    10  	"github.com/goreleaser/goreleaser/pkg/context"
    11  	homedir "github.com/mitchellh/go-homedir"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  // ErrMissingToken indicates an error when GITHUB_TOKEN is missing in the environment
    16  var ErrMissingToken = errors.New("missing GITHUB_TOKEN")
    17  
    18  // Pipe for env
    19  type Pipe struct{}
    20  
    21  func (Pipe) String() string {
    22  	return "loading environment variables"
    23  }
    24  
    25  // Default sets the pipe defaults
    26  func (Pipe) Default(ctx *context.Context) error {
    27  	var env = &ctx.Config.EnvFiles
    28  	if env.GitHubToken == "" {
    29  		env.GitHubToken = "~/.config/goreleaser/github_token"
    30  	}
    31  	return nil
    32  }
    33  
    34  // Run the pipe
    35  func (Pipe) Run(ctx *context.Context) error {
    36  	token, err := loadEnv("GITHUB_TOKEN", ctx.Config.EnvFiles.GitHubToken)
    37  	ctx.Token = token
    38  	if ctx.SkipPublish {
    39  		return pipe.ErrSkipPublishEnabled
    40  	}
    41  	if ctx.Config.Release.Disable {
    42  		return pipe.Skip("release pipe is disabled")
    43  	}
    44  	if ctx.Token == "" && err == nil {
    45  		return ErrMissingToken
    46  	}
    47  	return errors.Wrap(err, "failed to load github token")
    48  }
    49  
    50  func loadEnv(env, path string) (string, error) {
    51  	val := os.Getenv(env)
    52  	if val != "" {
    53  		return val, nil
    54  	}
    55  	path, err := homedir.Expand(path)
    56  	if err != nil {
    57  		return "", err
    58  	}
    59  	f, err := os.Open(path) // #nosec
    60  	if os.IsNotExist(err) {
    61  		return "", nil
    62  	}
    63  	if err != nil {
    64  		return "", err
    65  	}
    66  	bts, _, err := bufio.NewReader(f).ReadLine()
    67  	return string(bts), err
    68  }