Skip to content

Commit 3f79b37

Browse files
authored
Merge pull request #730 from iotaledger/feat/RunE
Refactor cobra commands to return errors
2 parents 7831b0b + 300cfcd commit 3f79b37

26 files changed

+484
-307
lines changed

tools/cluster/tests/wasp-cli_test.go

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func TestWaspAuth(t *testing.T) {
3939

4040
t.Run("table format output", func(t *testing.T) {
4141
// t.Skip()
42-
out := w.MustRun("auth", "login", "--node=0", "-u=wasp", "-p=wasp")
42+
out := w.MustRun("auth", "login", "--node=0", "-u=wasp", "-p=wasp", "--table")
4343
// Check for table output format with SUCCESS status
4444
found := false
4545
for _, line := range out {
@@ -71,25 +71,22 @@ func TestWaspAuth(t *testing.T) {
7171
require.Contains(t, authResult, "type", "JSON output should contain 'type' field")
7272
require.Contains(t, authResult, "status", "JSON output should contain 'status' field")
7373
require.Contains(t, authResult, "timestamp", "JSON output should contain 'timestamp' field")
74-
require.Contains(t, authResult, "data", "JSON output should contain 'data' field")
7574

7675
// Verify top-level field values
7776
require.Equal(t, "auth", authResult["type"], "Expected type to be 'auth'")
7877
require.Equal(t, "success", authResult["status"], "Expected status to be 'success'")
7978
require.NotEmpty(t, authResult["timestamp"], "Timestamp should not be empty")
8079

81-
// Verify the data structure contains auth-specific fields
82-
data, ok := authResult["data"].(map[string]interface{})
83-
require.True(t, ok, "Data field should be an object")
84-
require.Contains(t, data, "node", "Auth data should contain 'node' field")
85-
require.Contains(t, data, "username", "Auth data should contain 'username' field")
80+
// Verify auth-specific fields are at the top level (no data wrapper)
81+
require.Contains(t, authResult, "node", "Auth result should contain 'node' field")
82+
require.Contains(t, authResult, "username", "Auth result should contain 'username' field")
8683

87-
// Verify the auth data values are correct
88-
require.Equal(t, "0", data["node"], "Expected node to be '0'")
89-
require.Equal(t, "wasp", data["username"], "Expected username to be 'wasp'")
84+
// Verify the auth values are correct
85+
require.Equal(t, "0", authResult["node"], "Expected node to be '0'")
86+
require.Equal(t, "wasp", authResult["username"], "Expected username to be 'wasp'")
9087

91-
// Check if the message field exists in data (it's optional)
92-
if message, exists := data["message"]; exists {
88+
// Check if the message field exists (it's optional)
89+
if message, exists := authResult["message"]; exists {
9390
require.NotEmpty(t, message, "Message field should not be empty if present")
9491
}
9592

tools/wasp-cli/chain/access-nodes.go

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package chain
66

77
import (
88
"context"
9+
"fmt"
910

1011
"github.com/spf13/cobra"
1112

@@ -29,7 +30,10 @@ func initPermissionlessAccessNodesCmd() *cobra.Command {
2930
if err != nil {
3031
return err
3132
}
32-
chain = defaultChainFallback(chain)
33+
chain, err = defaultChainFallback(chain)
34+
if err != nil {
35+
return err
36+
}
3337

3438
action := args[0]
3539
node, err = waspcmd.DefaultWaspNodeFallback(node)
@@ -39,31 +43,39 @@ func initPermissionlessAccessNodesCmd() *cobra.Command {
3943
ctx := context.Background()
4044
client := cliclients.WaspClientWithVersionCheck(ctx, node)
4145

42-
var executeActionFunc func(peer string)
46+
var executeActionFunc func(peer string) error
4347

4448
switch action {
4549
case "add":
46-
executeActionFunc = func(peer string) {
50+
executeActionFunc = func(peer string) error {
4751
_, err := client.ChainsAPI.
4852
AddAccessNode(ctx, peer).
4953
Execute() //nolint:bodyclose // false positive
50-
log.Check(err)
54+
if err != nil {
55+
return err
56+
}
5157
log.Printf("added %s as an access node\n", peer)
58+
return nil
5259
}
5360
case "remove":
54-
executeActionFunc = func(peer string) {
61+
executeActionFunc = func(peer string) error {
5562
_, err := client.ChainsAPI.
5663
RemoveAccessNode(ctx, peer).
5764
Execute() //nolint:bodyclose // false positive
58-
log.Check(err)
65+
if err != nil {
66+
return err
67+
}
5968
log.Printf("removed %s as an access node\n", peer)
69+
return nil
6070
}
6171
default:
62-
log.Fatalf("unknown action: %s", action)
72+
return fmt.Errorf("unknown action: %s", action)
6373
}
6474

6575
for _, peer := range peers {
66-
executeActionFunc(peer)
76+
if err := executeActionFunc(peer); err != nil {
77+
return err
78+
}
6779
}
6880
return nil
6981
},

tools/wasp-cli/chain/accounts.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@ func initAccountObjectsCmd() *cobra.Command {
8282
if err != nil {
8383
return err
8484
}
85-
chain = defaultChainFallback(chain)
85+
chain, err = defaultChainFallback(chain)
86+
if err != nil {
87+
return err
88+
}
8689
agentID := util.AgentIDFromArgs(args)
8790
ctx := context.Background()
8891
client := cliclients.WaspClientWithVersionCheck(ctx, node)
@@ -154,7 +157,10 @@ func initDepositCmd() *cobra.Command {
154157
if err != nil {
155158
return err
156159
}
157-
chain = defaultChainFallback(chain)
160+
chain, err = defaultChainFallback(chain)
161+
if err != nil {
162+
return err
163+
}
158164
chainID := config.GetChain(chain)
159165

160166
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1000)

tools/wasp-cli/chain/activate.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ func initActivateCmd() *cobra.Command {
2727
if err != nil {
2828
return err
2929
}
30-
chainName = defaultChainFallback(chainName)
30+
chainName, err = defaultChainFallback(chainName)
31+
if err != nil {
32+
return err
33+
}
3134
chainID := config.GetChain(chainName)
3235
ctx := context.Background()
3336
activateChain(ctx, node, chainName, chainID)
@@ -75,9 +78,11 @@ func initDeactivateCmd() *cobra.Command {
7578
Short: "Deactivates the chain on selected nodes",
7679
Args: cobra.NoArgs,
7780
RunE: func(cmd *cobra.Command, args []string) error {
78-
chainName = defaultChainFallback(chainName)
79-
8081
var err error
82+
chainName, err = defaultChainFallback(chainName)
83+
if err != nil {
84+
return err
85+
}
8186
node, err = waspcmd.DefaultWaspNodeFallback(node)
8287
if err != nil {
8388
return err

tools/wasp-cli/chain/blocklog.go

Lines changed: 62 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,30 @@ func initBlockCmd() *cobra.Command {
3333
if err != nil {
3434
return err
3535
}
36-
chain = defaultChainFallback(chain)
36+
chain, err = defaultChainFallback(chain)
37+
if err != nil {
38+
return err
39+
}
3740
ctx := context.Background()
3841
client := cliclients.WaspClientWithVersionCheck(ctx, node)
3942

40-
bi := fetchBlockInfo(ctx, client, args)
43+
bi, err := fetchBlockInfo(ctx, client, args)
44+
if err != nil {
45+
return err
46+
}
4147
log.Printf("Block index: %d\n", bi.BlockIndex)
4248
log.Printf("Timestamp: %s\n", bi.Timestamp.UTC().Format(time.RFC3339))
4349
log.Printf("Total requests: %d\n", bi.TotalRequests)
4450
log.Printf("Successful requests: %d\n", bi.NumSuccessfulRequests)
4551
log.Printf("Off-ledger requests: %d\n", bi.NumOffLedgerRequests)
4652
log.Printf("\n")
47-
logRequestsInBlock(ctx, client, bi.BlockIndex)
53+
if err := logRequestsInBlock(ctx, client, bi.BlockIndex); err != nil {
54+
return err
55+
}
4856
log.Printf("\n")
49-
logEventsInBlock(ctx, client, bi.BlockIndex)
57+
if err := logEventsInBlock(ctx, client, bi.BlockIndex); err != nil {
58+
return err
59+
}
5060
return nil
5161
},
5262
}
@@ -55,76 +65,87 @@ func initBlockCmd() *cobra.Command {
5565
return cmd
5666
}
5767

58-
func fetchBlockInfo(ctx context.Context, client *apiclient.APIClient, args []string) *apiclient.BlockInfoResponse {
68+
func fetchBlockInfo(ctx context.Context, client *apiclient.APIClient, args []string) (*apiclient.BlockInfoResponse, error) {
5969
if len(args) == 0 {
6070
blockInfo, _, err := client.
6171
CorecontractsAPI.
6272
BlocklogGetLatestBlockInfo(ctx).
6373
Execute() //nolint:bodyclose // false positive
64-
65-
log.Check(err)
66-
return blockInfo
74+
if err != nil {
75+
return nil, err
76+
}
77+
return blockInfo, nil
6778
}
6879

6980
blockIndexStr := args[0]
7081
index, err := strconv.ParseUint(blockIndexStr, 10, 32)
71-
log.Check(err)
82+
if err != nil {
83+
return nil, fmt.Errorf("invalid block index '%s': %w", blockIndexStr, err)
84+
}
7285

7386
blockInfo, _, err := client.
7487
CorecontractsAPI.
7588
BlocklogGetBlockInfo(ctx, uint32(index)).
7689
Block(blockIndexStr).
7790
Execute() //nolint:bodyclose // false positive
78-
79-
log.Check(err)
80-
return blockInfo
91+
if err != nil {
92+
return nil, err
93+
}
94+
return blockInfo, nil
8195
}
8296

83-
func logRequestsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) {
97+
func logRequestsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) error {
8498
receipts, _, err := client.CorecontractsAPI.
8599
BlocklogGetRequestReceiptsOfBlock(ctx, index).
86100
Block(fmt.Sprintf("%d", index)).
87101
Execute() //nolint:bodyclose // false positive
88-
89-
log.Check(err)
102+
if err != nil {
103+
return err
104+
}
90105

91106
for i, receipt := range receipts {
92107
r := receipt
93108
util.LogReceipt(r, i)
94109
}
110+
return nil
95111
}
96112

97-
func logEventsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) {
113+
func logEventsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) error {
98114
events, _, err := client.CorecontractsAPI.
99115
BlocklogGetEventsOfBlock(ctx, index).
100116
Block(fmt.Sprintf("%d", index)).
101117
Execute() //nolint:bodyclose // false positive
102-
103-
log.Check(err)
118+
if err != nil {
119+
return err
120+
}
104121
logEvents(events)
122+
return nil
105123
}
106124

107125
func hexLenFromByteLen(length int) int {
108126
return (length * 2) + 2
109127
}
110128

111-
func reqIDFromString(s string) isc.RequestID {
129+
func reqIDFromString(s string) (isc.RequestID, error) {
112130
switch len(s) {
113131
case hexLenFromByteLen(iotago.AddressLen):
114132
// isc ReqID
115133
reqID, err := isc.RequestIDFromString(s)
116-
log.Check(err)
117-
return reqID
134+
if err != nil {
135+
return isc.RequestID{}, fmt.Errorf("invalid isc requestID: %w", err)
136+
}
137+
return reqID, nil
118138
case hexLenFromByteLen(common.HashLength):
119139
bytes, err := cryptolib.DecodeHex(s)
120-
log.Check(err)
140+
if err != nil {
141+
return isc.RequestID{}, fmt.Errorf("invalid evm tx hash: %w", err)
142+
}
121143
var txHash common.Hash
122144
copy(txHash[:], bytes)
123-
return isc.RequestIDFromEVMTxHash(txHash)
145+
return isc.RequestIDFromEVMTxHash(txHash), nil
124146
default:
125-
log.Fatalf("invalid requestID length: %d", len(s))
147+
return isc.RequestID{}, fmt.Errorf("invalid requestID length: %d", len(s))
126148
}
127-
panic("unreachable")
128149
}
129150

130151
func initRequestCmd() *cobra.Command {
@@ -140,11 +161,17 @@ func initRequestCmd() *cobra.Command {
140161
if err != nil {
141162
return err
142163
}
143-
chain = defaultChainFallback(chain)
164+
chain, err = defaultChainFallback(chain)
165+
if err != nil {
166+
return err
167+
}
144168
ctx := context.Background()
145169
client := cliclients.WaspClientWithVersionCheck(ctx, node)
146170

147-
reqID := reqIDFromString(args[0])
171+
reqID, err := reqIDFromString(args[0])
172+
if err != nil {
173+
return err
174+
}
148175

149176
// TODO add optional block param?
150177
receipt, _, err := client.ChainsAPI.
@@ -158,7 +185,9 @@ func initRequestCmd() *cobra.Command {
158185
util.LogReceipt(*receipt)
159186

160187
log.Printf("\n")
161-
logEventsInRequest(ctx, client, reqID)
188+
if err := logEventsInRequest(ctx, client, reqID); err != nil {
189+
return err
190+
}
162191
log.Printf("\n")
163192
return nil
164193
},
@@ -168,13 +197,15 @@ func initRequestCmd() *cobra.Command {
168197
return cmd
169198
}
170199

171-
func logEventsInRequest(ctx context.Context, client *apiclient.APIClient, reqID isc.RequestID) {
200+
func logEventsInRequest(ctx context.Context, client *apiclient.APIClient, reqID isc.RequestID) error {
172201
events, _, err := client.CorecontractsAPI.
173202
BlocklogGetEventsOfRequest(ctx, reqID.String()).
174203
Execute() //nolint:bodyclose // false positive
175-
176-
log.Check(err)
204+
if err != nil {
205+
return err
206+
}
177207
logEvents(events)
208+
return nil
178209
}
179210

180211
func logEvents(ret *apiclient.EventsResponse) {

tools/wasp-cli/chain/callview.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ func initCallViewCmd() *cobra.Command {
2727
if err != nil {
2828
return err
2929
}
30-
chain = defaultChainFallback(chain)
30+
chain, err = defaultChainFallback(chain)
31+
if err != nil {
32+
return err
33+
}
3134
ctx := context.Background()
3235
client := cliclients.WaspClientWithVersionCheck(ctx, node)
3336

0 commit comments

Comments
 (0)