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

     1  // Package checksums provides a Pipe that creates .checksums files for
     2  // each artifact.
     3  package checksums
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"path/filepath"
     9  
    10  	"github.com/apex/log"
    11  
    12  	"github.com/goreleaser/goreleaser/internal/artifact"
    13  	"github.com/goreleaser/goreleaser/internal/semerrgroup"
    14  	"github.com/goreleaser/goreleaser/internal/tmpl"
    15  	"github.com/goreleaser/goreleaser/pkg/context"
    16  )
    17  
    18  // Pipe for checksums
    19  type Pipe struct{}
    20  
    21  func (Pipe) String() string {
    22  	return "calculating checksums"
    23  }
    24  
    25  // Default sets the pipe defaults
    26  func (Pipe) Default(ctx *context.Context) error {
    27  	if ctx.Config.Checksum.NameTemplate == "" {
    28  		ctx.Config.Checksum.NameTemplate = "{{ .ProjectName }}_{{ .Version }}_checksums.txt"
    29  	}
    30  	return nil
    31  }
    32  
    33  // Run the pipe
    34  func (Pipe) Run(ctx *context.Context) (err error) {
    35  	filename, err := tmpl.New(ctx).Apply(ctx.Config.Checksum.NameTemplate)
    36  	if err != nil {
    37  		return err
    38  	}
    39  	file, err := os.OpenFile(
    40  		filepath.Join(ctx.Config.Dist, filename),
    41  		os.O_APPEND|os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
    42  		0444,
    43  	)
    44  	if err != nil {
    45  		return err
    46  	}
    47  	defer file.Close() // nolint: errcheck
    48  
    49  	var g = semerrgroup.New(ctx.Parallelism)
    50  	for _, artifact := range ctx.Artifacts.Filter(
    51  		artifact.Or(
    52  			artifact.ByType(artifact.UploadableArchive),
    53  			artifact.ByType(artifact.UploadableBinary),
    54  			artifact.ByType(artifact.LinuxPackage),
    55  		),
    56  	).List() {
    57  		artifact := artifact
    58  		g.Go(func() error {
    59  			return checksums(file, artifact)
    60  		})
    61  	}
    62  	ctx.Artifacts.Add(artifact.Artifact{
    63  		Type: artifact.Checksum,
    64  		Path: file.Name(),
    65  		Name: filename,
    66  	})
    67  	return g.Wait()
    68  }
    69  
    70  func checksums(file *os.File, artifact artifact.Artifact) error {
    71  	log.WithField("file", artifact.Name).Info("checksumming")
    72  	sha, err := artifact.Checksum()
    73  	if err != nil {
    74  		return err
    75  	}
    76  	_, err = file.WriteString(fmt.Sprintf("%v  %v\n", sha, artifact.Name))
    77  	return err
    78  }