From bb2ca482000f5c780545edb9a03aa9f6bf93d906 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20T=C3=B6lle?= Date: Fri, 10 May 2024 18:06:38 +0200 Subject: [PATCH] fix(cli): completion requires HCLOUD_TOKEN (#19) The current setup of the CLI requires the user to set HCLOUD_TOKEN for every single invocation of the binary. Even if we just want to autocomplete some arguments or even generate the completion scripts in CI. This fixes the bug by only initializing the hcloud-go client in the "cleanup" and "upload" subcommands. --- cmd/cleanup.go | 4 ++++ cmd/root.go | 15 ++++++++++----- cmd/upload.go | 2 ++ go.mod | 2 +- 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/cmd/cleanup.go b/cmd/cleanup.go index c726267..78486b7 100644 --- a/cmd/cleanup.go +++ b/cmd/cleanup.go @@ -23,7 +23,11 @@ $ hcloud ssh-key list -l apricote.de/created-by=hcloud-upload-image This command does not handle any parallel executions of hcloud-upload-image and will remove in-use resources if called at the same time.`, + GroupID: "primary", + + PreRun: initClient, + RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() logger := contextlogger.From(ctx) diff --git a/cmd/root.go b/cmd/root.go index 3d0b247..1d735d4 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "log/slog" "os" "time" @@ -46,8 +45,6 @@ var rootCmd = &cobra.Command{ logger := slog.Default() ctx = contextlogger.New(ctx, logger) cmd.SetContext(ctx) - - client = newClient(ctx) }, } @@ -71,7 +68,15 @@ func initLogger() *slog.Logger { } -func newClient(ctx context.Context) *hcloudimages.Client { +func initClient(cmd *cobra.Command, _ []string) { + if client != nil { + // Only init if not set. + // Theoretically this is not safe against data races and should use [sync.Once], but :shrug: + return + } + + ctx := cmd.Context() + logger := contextlogger.From(ctx) // Build hcloud-go client if os.Getenv("HCLOUD_TOKEN") == "" { @@ -89,7 +94,7 @@ func newClient(ctx context.Context) *hcloudimages.Client { opts = append(opts, hcloud.WithDebugWriter(os.Stderr)) } - return hcloudimages.NewClient(hcloud.NewClient(opts...)) + client = hcloudimages.NewClient(hcloud.NewClient(opts...)) } func Execute() { diff --git a/cmd/upload.go b/cmd/upload.go index 843791a..abc15c7 100644 --- a/cmd/upload.go +++ b/cmd/upload.go @@ -33,6 +33,8 @@ This does cost a bit of money for the server.`, GroupID: "primary", + PreRun: initClient, + RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() logger := contextlogger.From(ctx) diff --git a/go.mod b/go.mod index d00ea5c..6b250ae 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/apricote/hcloud-upload-image go 1.22.2 require ( - github.com/apricote/hcloud-upload-image/hcloudimages v0.0.0 + github.com/apricote/hcloud-upload-image/hcloudimages v0.2.0 github.com/hetznercloud/hcloud-go/v2 v2.8.0 github.com/spf13/cobra v1.8.0 )