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.
This commit is contained in:
Julian Tölle 2024-05-10 18:06:38 +02:00 committed by GitHub
parent f7dc501b2f
commit bb2ca48200
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 17 additions and 6 deletions

View file

@ -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() {