github.com/adevinta/lava@v0.7.2/cmd/lava/internal/initialize/initialize.go (about)

     1  // Copyright 2023 Adevinta
     2  
     3  // Package initialize implements the init command.
     4  package initialize
     5  
     6  import (
     7  	_ "embed"
     8  	"errors"
     9  	"fmt"
    10  	"io/fs"
    11  	"os"
    12  
    13  	"github.com/adevinta/lava/cmd/lava/internal/base"
    14  )
    15  
    16  // CmdInit represents the init command.
    17  var CmdInit = &base.Command{
    18  	UsageLine: "init [flags]",
    19  	Short:     "init Lava project",
    20  	Long: `
    21  Initializes a Lava project.
    22  
    23  This command creates a default Lava configuration file.
    24  
    25  The -c flag allows to specify the name of the configuration file. By
    26  default, a file with the name "lava.yaml" is created in the current
    27  directory.
    28  
    29  The -f flag allows to overwrite the output configuration file if it
    30  exists.
    31  	`,
    32  }
    33  
    34  // Command-line flags.
    35  var (
    36  	initC string // -c flag
    37  	initF bool   // -f flag
    38  )
    39  
    40  //go:embed default.yaml
    41  var defaultConfig []byte
    42  
    43  func init() {
    44  	CmdInit.Run = runInit // Break initialization cycle.
    45  	CmdInit.Flag.StringVar(&initC, "c", "lava.yaml", "config file")
    46  	CmdInit.Flag.BoolVar(&initF, "f", false, "overwrite config file")
    47  }
    48  
    49  // runInit is the entry point of the init command.
    50  func runInit(args []string) error {
    51  	if len(args) > 0 {
    52  		return errors.New("too many arguments")
    53  	}
    54  
    55  	if !initF {
    56  		_, err := os.Stat(initC)
    57  		if err == nil {
    58  			return fs.ErrExist
    59  		}
    60  		if !errors.Is(err, fs.ErrNotExist) {
    61  			return fmt.Errorf("stat: %w", err)
    62  		}
    63  	}
    64  
    65  	if err := os.WriteFile(initC, defaultConfig, 0644); err != nil {
    66  		return fmt.Errorf("write file: %w", err)
    67  	}
    68  
    69  	return nil
    70  }