github.com/windmeup/goreleaser@v1.21.95/cmd/init.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"regexp"
     7  
     8  	"github.com/caarlos0/log"
     9  	"github.com/spf13/cobra"
    10  	"github.com/windmeup/goreleaser/internal/static"
    11  )
    12  
    13  type initCmd struct {
    14  	cmd    *cobra.Command
    15  	config string
    16  }
    17  
    18  const gitignorePath = ".gitignore"
    19  
    20  func newInitCmd() *initCmd {
    21  	root := &initCmd{}
    22  	cmd := &cobra.Command{
    23  		Use:               "init",
    24  		Aliases:           []string{"i"},
    25  		Short:             "Generates a .goreleaser.yaml file",
    26  		SilenceUsage:      true,
    27  		SilenceErrors:     true,
    28  		Args:              cobra.NoArgs,
    29  		ValidArgsFunction: cobra.NoFileCompletions,
    30  		RunE: func(_ *cobra.Command, _ []string) error {
    31  			if _, err := os.Stat(root.config); err == nil {
    32  				return fmt.Errorf("%s already exists, delete it and run the command again", root.config)
    33  			}
    34  			conf, err := os.OpenFile(root.config, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|os.O_EXCL, 0o644)
    35  			if err != nil {
    36  				return err
    37  			}
    38  			defer conf.Close()
    39  
    40  			log.Infof(boldStyle.Render(fmt.Sprintf("Generating %s file", root.config)))
    41  			if _, err := conf.Write(static.ExampleConfig); err != nil {
    42  				return err
    43  			}
    44  
    45  			if !hasDistIgnored(gitignorePath) {
    46  				gitignore, err := os.OpenFile(gitignorePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)
    47  				if err != nil {
    48  					return err
    49  				}
    50  				defer gitignore.Close()
    51  				if _, err := gitignore.WriteString("\ndist/\n"); err != nil {
    52  					return err
    53  				}
    54  			}
    55  			log.WithField("file", root.config).Info("config created; please edit accordingly to your needs")
    56  			return nil
    57  		},
    58  	}
    59  
    60  	cmd.Flags().StringVarP(&root.config, "config", "f", ".goreleaser.yaml", "Load configuration from file")
    61  	_ = cmd.MarkFlagFilename("config", "yaml", "yml")
    62  
    63  	root.cmd = cmd
    64  	return root
    65  }
    66  
    67  func hasDistIgnored(path string) bool {
    68  	bts, err := os.ReadFile(path)
    69  	if err != nil {
    70  		return false
    71  	}
    72  	exp := regexp.MustCompile("(?m)^dist/$")
    73  	return exp.Match(bts)
    74  }