From a354376373cf92a0a544f6c3953f6295eb0995ce Mon Sep 17 00:00:00 2001 From: Martin Anker Have Date: Tue, 2 Jan 2024 13:18:31 +0100 Subject: [PATCH] Print helpful text to know how to login (#514) --- .github/workflows/build.yml | 2 +- cmd/hamctl/main.go | 11 +++++++++++ internal/http/authenticator.go | 7 ++++++- internal/http/client.go | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7274fe80..92fe31d3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,7 +17,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v5 with: - go-version: 1.19.0 + go-version: 1.21.4 - name: Cache Go modules uses: actions/cache@v3 with: diff --git a/cmd/hamctl/main.go b/cmd/hamctl/main.go index d3b066a5..41fdf94a 100644 --- a/cmd/hamctl/main.go +++ b/cmd/hamctl/main.go @@ -1,10 +1,12 @@ package main import ( + "errors" "fmt" "os" "github.com/lunarway/release-manager/cmd/hamctl/command" + "github.com/lunarway/release-manager/internal/http" ) var ( @@ -17,8 +19,17 @@ func main() { fmt.Printf("Error: %v\n", err) os.Exit(1) } + c.SilenceUsage = true + c.SilenceErrors = true + err = c.Execute() if err != nil { + if errors.Is(err, http.ErrLoginRequired) { + fmt.Printf("You are not logged in. To log in, please run the following command:\n 'hamctl login'\n") + } else { + fmt.Printf("Error: %v\n", err) + } + os.Exit(1) } } diff --git a/internal/http/authenticator.go b/internal/http/authenticator.go index 68c6d084..e0b8be74 100644 --- a/internal/http/authenticator.go +++ b/internal/http/authenticator.go @@ -3,6 +3,7 @@ package http import ( "context" "encoding/json" + "errors" "fmt" "net/http" "os" @@ -13,6 +14,10 @@ import ( "golang.org/x/oauth2/clientcredentials" ) +var ( + ErrLoginRequired = errors.New("login required") +) + type UserAuthenticator struct { conf *oauth2.Config } @@ -52,7 +57,7 @@ func (g *UserAuthenticator) Login(ctx context.Context) error { func (g *UserAuthenticator) Access(ctx context.Context) (*http.Client, error) { token, err := readAccessToken() if err != nil { - return nil, err + return nil, fmt.Errorf("%w: %w", ErrLoginRequired, err) } return g.conf.Client(ctx, token), nil } diff --git a/internal/http/client.go b/internal/http/client.go index 7bed0d90..675ebbe5 100644 --- a/internal/http/client.go +++ b/internal/http/client.go @@ -59,7 +59,7 @@ func (c *Client) Do(method string, path string, requestBody, responseBody interf ctx := context.Background() client, err := c.Auth.Access(ctx) if err != nil { - return errors.Wrap(err, "please log in again to refresh the token") + return err } client.Timeout = c.Timeout