1
1
package getaccesstoken
2
2
3
3
import (
4
+ "encoding/json"
5
+ "fmt"
6
+
7
+ "github.com/goccy/go-yaml"
4
8
"github.com/spf13/cobra"
5
9
"github.com/stackitcloud/stackit-cli/internal/cmd/params"
6
10
"github.com/stackitcloud/stackit-cli/internal/pkg/args"
7
11
"github.com/stackitcloud/stackit-cli/internal/pkg/auth"
8
12
cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors"
9
13
"github.com/stackitcloud/stackit-cli/internal/pkg/examples"
14
+ "github.com/stackitcloud/stackit-cli/internal/pkg/globalflags"
15
+ "github.com/stackitcloud/stackit-cli/internal/pkg/print"
10
16
)
11
17
18
+ type inputModel struct {
19
+ * globalflags.GlobalFlagModel
20
+ }
21
+
12
22
func NewCmd (params * params.CmdParams ) * cobra.Command {
13
23
cmd := & cobra.Command {
14
24
Use : "get-access-token" ,
@@ -20,7 +30,12 @@ func NewCmd(params *params.CmdParams) *cobra.Command {
20
30
`Print a short-lived access token` ,
21
31
"$ stackit auth get-access-token" ),
22
32
),
23
- RunE : func (_ * cobra.Command , _ []string ) error {
33
+ RunE : func (cmd * cobra.Command , _ []string ) error {
34
+ model , err := parseInput (params .Printer , cmd )
35
+ if err != nil {
36
+ return err
37
+ }
38
+
24
39
userSessionExpired , err := auth .UserSessionExpired ()
25
40
if err != nil {
26
41
return err
@@ -35,9 +50,52 @@ func NewCmd(params *params.CmdParams) *cobra.Command {
35
50
return err
36
51
}
37
52
38
- params .Printer .Outputf ("%s\n " , accessToken )
39
- return nil
53
+ switch model .OutputFormat {
54
+ case print .JSONOutputFormat :
55
+ details , err := json .MarshalIndent (map [string ]string {
56
+ "access_token" : accessToken ,
57
+ }, "" , " " )
58
+ if err != nil {
59
+ return fmt .Errorf ("marshal image list: %w" , err )
60
+ }
61
+ params .Printer .Outputln (string (details ))
62
+
63
+ return nil
64
+ case print .YAMLOutputFormat :
65
+ details , err := yaml .MarshalWithOptions (map [string ]string {
66
+ "access_token" : accessToken ,
67
+ }, yaml .IndentSequence (true ), yaml .UseJSONMarshaler ())
68
+ if err != nil {
69
+ return fmt .Errorf ("marshal image list: %w" , err )
70
+ }
71
+ params .Printer .Outputln (string (details ))
72
+
73
+ return nil
74
+ default :
75
+ params .Printer .Outputln (accessToken )
76
+
77
+ return nil
78
+ }
40
79
},
41
80
}
42
81
return cmd
43
82
}
83
+
84
+ func parseInput (p * print.Printer , cmd * cobra.Command ) (* inputModel , error ) {
85
+ globalFlags := globalflags .Parse (p , cmd )
86
+
87
+ model := inputModel {
88
+ GlobalFlagModel : globalFlags ,
89
+ }
90
+
91
+ if p .IsVerbosityDebug () {
92
+ modelStr , err := print .BuildDebugStrFromInputModel (model )
93
+ if err != nil {
94
+ p .Debug (print .ErrorLevel , "convert model to string for debugging: %v" , err )
95
+ } else {
96
+ p .Debug (print .DebugLevel , "parsed input values: %s" , modelStr )
97
+ }
98
+ }
99
+
100
+ return & model , nil
101
+ }
0 commit comments