github.com/ipni/storetheindex@v0.8.30/assigner/command/init.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/ipni/storetheindex/assigner/config"
     8  	sticfg "github.com/ipni/storetheindex/config"
     9  	"github.com/ipni/storetheindex/fsutil"
    10  	"github.com/urfave/cli/v2"
    11  )
    12  
    13  var InitCmd = &cli.Command{
    14  	Name:   "init",
    15  	Usage:  "Initialize or upgrade config file",
    16  	Flags:  initFlags,
    17  	Action: initAction,
    18  }
    19  
    20  var initFlags = []cli.Flag{
    21  	&cli.BoolFlag{
    22  		Name:     "no-bootstrap",
    23  		Usage:    "Do not configure bootstrap peers",
    24  		EnvVars:  []string{"NO_BOOTSTRAP"},
    25  		Required: false,
    26  	},
    27  	&cli.StringFlag{
    28  		Name:     "pubsub-topic",
    29  		Usage:    "Subscribe to this pubsub topic to receive advertisement notification",
    30  		EnvVars:  []string{"ASSIGNER_PUBSUB_TOPIC"},
    31  		Required: false,
    32  	},
    33  	&cli.BoolFlag{
    34  		Name:     "upgrade",
    35  		Usage:    "Upgrade the config file to the current version, saving the old config as config.prev, and ignoring other flags ",
    36  		Aliases:  []string{"u"},
    37  		Required: false,
    38  	},
    39  }
    40  
    41  func initAction(cctx *cli.Context) error {
    42  	// Check that the config root exists and it writable.
    43  	configRoot, err := config.PathRoot()
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	if err = fsutil.DirWritable(configRoot); err != nil {
    49  		return err
    50  	}
    51  
    52  	configFile, err := config.Path(configRoot, "")
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	if cctx.Bool("upgrade") {
    58  		cfg, err := config.Load(configFile)
    59  		if err != nil {
    60  			return err
    61  		}
    62  		prevVer := cfg.Version
    63  		err = cfg.UpgradeConfig(configFile)
    64  		if err != nil {
    65  			return fmt.Errorf("cannot upgrade: %s", err)
    66  		}
    67  		fmt.Println("Upgraded", configFile, "from version", prevVer, "to", cfg.Version)
    68  		return nil
    69  	}
    70  
    71  	fmt.Println("Initializing", progName, "at", configRoot)
    72  
    73  	if fsutil.FileExists(configFile) {
    74  		return sticfg.ErrInitialized
    75  	}
    76  
    77  	cfg, err := config.Init(os.Stderr)
    78  	if err != nil {
    79  		return err
    80  	}
    81  
    82  	noBootstrap := cctx.Bool("no-bootstrap")
    83  	if noBootstrap {
    84  		cfg.Bootstrap.Peers = []string{}
    85  		cfg.Bootstrap.MinimumPeers = 0
    86  	}
    87  
    88  	topic := cctx.String("pubsub-topic")
    89  	if topic != "" {
    90  		cfg.Assignment.PubSubTopic = topic
    91  	}
    92  
    93  	return cfg.Save(configFile)
    94  }