From 3db07ca2d44407cc3fc9d3b1366a16101e3b06f2 Mon Sep 17 00:00:00 2001 From: Pasha Sviderski Date: Tue, 16 Sep 2025 10:17:44 +1000 Subject: [PATCH] feat: allow setting config and connection with UNCLOUD_CONFIG and UNCLOUD_CONNECT env vars --- cmd/uncloud/main.go | 10 ++++++---- internal/cli/flags.go | 13 +++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/cmd/uncloud/main.go b/cmd/uncloud/main.go index d1bb64ba..1eb723a1 100644 --- a/cmd/uncloud/main.go +++ b/cmd/uncloud/main.go @@ -28,11 +28,14 @@ func main() { opts := globalOptions{} cmd := &cobra.Command{ Use: "uc", - Short: "A CLI tool for managing Uncloud resources such as clusters, machines, and services.", + Short: "A CLI tool for managing Uncloud resources such as machines, services, and volumes.", Version: version.String(), SilenceUsage: true, SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + cli.BindEnvToFlag(cmd, "connect", "UNCLOUD_CONNECT") + cli.BindEnvToFlag(cmd, "uncloud-config", "UNCLOUD_CONFIG") + var conn *config.MachineConnection if opts.connect != "" { if strings.HasPrefix(opts.connect, "tcp://") { @@ -65,11 +68,10 @@ func main() { } cmd.PersistentFlags().StringVar(&opts.connect, "connect", "", - "Connect to a remote cluster machine without using the Uncloud configuration file.\n"+ + "Connect to a remote cluster machine without using the Uncloud configuration file. [$UNCLOUD_CONNECT]\n"+ "Format: [ssh://]user@host[:port] or tcp://host:port") - // TODO: allow to override using UNCLOUD_CONFIG env var. cmd.PersistentFlags().StringVar(&opts.configPath, "uncloud-config", "~/.config/uncloud/config.yaml", - "Path to the Uncloud configuration file.") + "Path to the Uncloud configuration file. [$UNCLOUD_CONFIG]") _ = cmd.MarkPersistentFlagFilename("uncloud-config", "yaml", "yml") // TODO: make --context a global flag and pass it as a value of the command context. diff --git a/internal/cli/flags.go b/internal/cli/flags.go index 289bfa73..23434739 100644 --- a/internal/cli/flags.go +++ b/internal/cli/flags.go @@ -1,7 +1,11 @@ package cli import ( + "log" + "os" "strings" + + "github.com/spf13/cobra" ) // ExpandCommaSeparatedValues takes a slice of strings and expands any comma-separated values into individual elements. @@ -21,3 +25,12 @@ func ExpandCommaSeparatedValues(values []string) []string { return expanded } + +// BindEnvToFlag assigns the value of an environment variable to the given command flag if the flag has not been set. +func BindEnvToFlag(cmd *cobra.Command, flagName, envVar string) { + if value := os.Getenv(envVar); value != "" && !cmd.Flags().Changed(flagName) { + if err := cmd.Flags().Set(flagName, value); err != nil { + log.Fatalf("Failed to bind environment variable '%s' to flag '%s': %v", envVar, flagName, err) + } + } +}