Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
absolutelightning committed Aug 31, 2023
1 parent 255aa15 commit 5e1bae5
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions command/snapshot/save/snapshot_save.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ package save
import (
"flag"
"fmt"
"github.com/hashicorp/consul/version"
"golang.org/x/exp/slices"
"os"
"strings"

"github.com/mitchellh/cli"
"github.com/rboyer/safeio"
Expand All @@ -23,17 +26,26 @@ func New(ui cli.Ui) *cmd {
}

type cmd struct {
UI cli.Ui
flags *flag.FlagSet
http *flags.HTTPFlags
help string
UI cli.Ui
flags *flag.FlagSet
http *flags.HTTPFlags
help string
appendFileName flags.StringValue
}

func (c *cmd) getAppendFileNameFlag() *flag.FlagSet {
fs := flag.NewFlagSet("", flag.ContinueOnError)
fs.Var(&c.appendFileName, "append-filename", "Append filename flag takes two possible values. "+
"1. version, 2. dc. It appends consul version and datacenter to filename given in command")
return fs
}

func (c *cmd) init() {
c.flags = flag.NewFlagSet("", flag.ContinueOnError)
c.http = &flags.HTTPFlags{}
flags.Merge(c.flags, c.http.ClientFlags())
flags.Merge(c.flags, c.http.ServerFlags())
flags.Merge(c.flags, c.getAppendFileNameFlag())
c.help = flags.Usage(help, c.flags)
}

Expand All @@ -52,12 +64,32 @@ func (c *cmd) Run(args []string) int {
case 1:
file = args[0]
default:
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args)))
c.UI.Error(fmt.Sprintf("Too many arguments (expected 1 or 3, got %d)", len(args)))
return 1
}

// Create and test the HTTP client
client, err := c.http.APIClient()

appendFileNameFlags := strings.Split(c.appendFileName.String(), ",")

if slices.Contains(appendFileNameFlags, "version") {
file = file + "-" + version.GetHumanVersion()
}

if slices.Contains(appendFileNameFlags, "dc") {
agentSelfResponse, err := client.Agent().Self()
if err != nil {
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent and fetching datacenter: %s", err))
return 1
}
if config, ok := agentSelfResponse["Config"]; ok {
if datacenter, ok := config["Datacenter"]; ok {
file = file + "-" + datacenter.(string)
}
}
}

if err != nil {
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1
Expand Down

0 comments on commit 5e1bae5

Please sign in to comment.