pull/18625/head
absolutelightning 2023-08-31 14:48:54 +05:30
parent 255aa158db
commit 5e1bae5341
1 changed files with 37 additions and 5 deletions

View File

@ -6,7 +6,10 @@ package save
import ( import (
"flag" "flag"
"fmt" "fmt"
"github.com/hashicorp/consul/version"
"golang.org/x/exp/slices"
"os" "os"
"strings"
"github.com/mitchellh/cli" "github.com/mitchellh/cli"
"github.com/rboyer/safeio" "github.com/rboyer/safeio"
@ -23,10 +26,18 @@ func New(ui cli.Ui) *cmd {
} }
type cmd struct { type cmd struct {
UI cli.Ui UI cli.Ui
flags *flag.FlagSet flags *flag.FlagSet
http *flags.HTTPFlags http *flags.HTTPFlags
help string 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() { func (c *cmd) init() {
@ -34,6 +45,7 @@ func (c *cmd) init() {
c.http = &flags.HTTPFlags{} c.http = &flags.HTTPFlags{}
flags.Merge(c.flags, c.http.ClientFlags()) flags.Merge(c.flags, c.http.ClientFlags())
flags.Merge(c.flags, c.http.ServerFlags()) flags.Merge(c.flags, c.http.ServerFlags())
flags.Merge(c.flags, c.getAppendFileNameFlag())
c.help = flags.Usage(help, c.flags) c.help = flags.Usage(help, c.flags)
} }
@ -52,12 +64,32 @@ func (c *cmd) Run(args []string) int {
case 1: case 1:
file = args[0] file = args[0]
default: 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 return 1
} }
// Create and test the HTTP client // Create and test the HTTP client
client, err := c.http.APIClient() 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 { if err != nil {
c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err)) c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
return 1 return 1