gitee.com/mirrors_opencollective/goreleaser@v0.45.0/pipeline/checksums/checksums.go (about)

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