Skip to content

Commit 76832c2

Browse files
committed
Returns a non-zero error code when errors occur while using api, configure, event, and token commands
1 parent 7c44046 commit 76832c2

File tree

8 files changed

+93
-77
lines changed

8 files changed

+93
-77
lines changed

cmd/api.go

+24-19
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
package cmd
44

55
import (
6+
"fmt"
67
"io/ioutil"
78
"log"
89
"strings"
@@ -33,35 +34,35 @@ var getCmd = &cobra.Command{
3334
Short: "Performs a GET request on the specified command.",
3435
Args: cobra.MaximumNArgs(3),
3536
ValidArgs: api.ValidOptions("GET"),
36-
Run: cmdRun,
37+
RunE: cmdRun,
3738
}
3839
var postCmd = &cobra.Command{
3940
Use: "post",
4041
Short: "Performs a POST request on the specified command.",
4142
Args: cobra.MaximumNArgs(3),
4243
ValidArgs: api.ValidOptions("POST"),
43-
Run: cmdRun,
44+
RunE: cmdRun,
4445
}
4546
var patchCmd = &cobra.Command{
4647
Use: "patch",
4748
Short: "Performs a PATCH request on the specified command.",
4849
Args: cobra.MaximumNArgs(3),
4950
ValidArgs: api.ValidOptions("PATCH"),
50-
Run: cmdRun,
51+
RunE: cmdRun,
5152
}
5253
var deleteCmd = &cobra.Command{
5354
Use: "delete",
5455
Short: "Performs a DELETE request on the specified command.",
5556
Args: cobra.MaximumNArgs(3),
5657
ValidArgs: api.ValidOptions("DELETE"),
57-
Run: cmdRun,
58+
RunE: cmdRun,
5859
}
5960
var putCmd = &cobra.Command{
6061
Use: "put",
6162
Short: "Performs a PUT request on the specified command.",
6263
Args: cobra.MaximumNArgs(3),
6364
ValidArgs: api.ValidOptions("PUT"),
64-
Run: cmdRun,
65+
RunE: cmdRun,
6566
}
6667

6768
var mockCmd = &cobra.Command{
@@ -72,13 +73,13 @@ var mockCmd = &cobra.Command{
7273
var startCmd = &cobra.Command{
7374
Use: "start",
7475
Short: "Used to start the server for the mock API.",
75-
Run: mockStartRun,
76+
RunE: mockStartRun,
7677
}
7778

7879
var generateCmd = &cobra.Command{
7980
Use: "generate",
8081
Short: "Used to randomly generate data for use with the mock API. By default, this is run on the first invocation of the start command, however this allows you to generate further primitives.",
81-
Run: generateMockRun,
82+
RunE: generateMockRun,
8283
}
8384

8485
func init() {
@@ -105,44 +106,48 @@ func init() {
105106
generateCmd.Flags().IntVarP(&generateCount, "count", "c", 25, "Defines the number of fake users to generate.")
106107
}
107108

108-
func cmdRun(cmd *cobra.Command, args []string) {
109+
func cmdRun(cmd *cobra.Command, args []string) error {
109110
var path string
110111

111112
if len(args) == 0 {
112113
cmd.Help()
113-
return
114+
return fmt.Errorf("")
114115
} else if len(args) == 1 && args[0][:1] == "/" {
115116
path = args[0]
116117
} else {
117118
path = "/" + strings.Join(args[:], "/")
118119
}
119120

120121
if body != "" && body[:1] == "@" {
121-
body = getBodyFromFile(body[1:])
122+
var err error
123+
body, err = getBodyFromFile(body[1:])
124+
if err != nil {
125+
return err
126+
}
122127
}
123128

124129
if cmd.Name() == "get" && cmd.PersistentFlags().Lookup("autopaginate").Changed {
125-
api.NewRequest(cmd.Name(), path, queryParameters, []byte(body), !prettyPrint, &autoPaginate)
130+
return api.NewRequest(cmd.Name(), path, queryParameters, []byte(body), !prettyPrint, &autoPaginate)
126131
} else {
127-
api.NewRequest(cmd.Name(), path, queryParameters, []byte(body), !prettyPrint, nil) // only set on when the user changed the flag
132+
return api.NewRequest(cmd.Name(), path, queryParameters, []byte(body), !prettyPrint, nil) // only set on when the user changed the flag
128133
}
129-
130134
}
131135

132-
func getBodyFromFile(filename string) string {
136+
func getBodyFromFile(filename string) (string, error) {
133137
content, err := ioutil.ReadFile(filename)
134138
if err != nil {
135-
log.Fatal(err)
139+
return "", err
136140
}
137141

138-
return string(content)
142+
return string(content), nil
139143
}
140144

141-
func mockStartRun(cmd *cobra.Command, args []string) {
145+
func mockStartRun(cmd *cobra.Command, args []string) error {
142146
log.Printf("Starting mock API server on http://localhost:%v", port)
143-
mock_server.StartServer(port)
147+
return mock_server.StartServer(port)
144148
}
145149

146-
func generateMockRun(cmd *cobra.Command, args []string) {
150+
func generateMockRun(cmd *cobra.Command, args []string) error {
147151
generate.Generate(generateCount)
152+
return nil
148153
}

cmd/configure.go

+6-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ package cmd
55
import (
66
"errors"
77
"fmt"
8-
"log"
98

109
"github.com/twitchdev/twitch-cli/internal/util"
1110

@@ -21,7 +20,7 @@ var clientSecret string
2120
var configureCmd = &cobra.Command{
2221
Use: "configure",
2322
Short: "Configures your Twitch CLI with your Client ID and Secret",
24-
Run: configureCmdRun,
23+
RunE: configureCmdRun,
2524
}
2625

2726
func init() {
@@ -31,7 +30,7 @@ func init() {
3130
configureCmd.Flags().StringVarP(&clientSecret, "client-secret", "s", "", "Client Secret to use.")
3231
}
3332

34-
func configureCmdRun(cmd *cobra.Command, args []string) {
33+
func configureCmdRun(cmd *cobra.Command, args []string) error {
3534
var err error
3635
if clientID == "" {
3736
clientIDPrompt := promptui.Prompt{
@@ -62,22 +61,21 @@ func configureCmdRun(cmd *cobra.Command, args []string) {
6261
}
6362

6463
if clientID == "" && clientSecret == "" {
65-
fmt.Println("Must specify either the Client ID or Secret")
66-
return
64+
return fmt.Errorf("Must specify either the Client ID or Secret")
6765
}
6866

6967
viper.Set("clientId", clientID)
7068
viper.Set("clientSecret", clientSecret)
7169

7270
configPath, err := util.GetConfigPath()
7371
if err != nil {
74-
log.Fatal(err)
72+
return err
7573
}
7674

7775
if err := viper.WriteConfigAs(configPath); err != nil {
78-
log.Fatalf("Failed to write configuration: %v", err.Error())
76+
fmt.Errorf("Failed to write configuration: %v", err.Error())
7977
}
8078

8179
fmt.Println("Updated configuration.")
82-
return
80+
return nil
8381
}

cmd/events.go

+5-15
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ var triggerCmd = &cobra.Command{
7373
%s`, types.AllWebhookTopics()),
7474
Args: cobra.MaximumNArgs(1),
7575
ValidArgs: types.AllWebhookTopics(),
76-
PreRun: silenceBeforeRunE,
7776
RunE: triggerCmdRun,
7877
Example: `twitch event trigger subscribe`,
7978
Aliases: []string{
@@ -89,7 +88,6 @@ var verifyCmd = &cobra.Command{
8988
%s`, types.AllWebhookTopics()),
9089
Args: cobra.MaximumNArgs(1),
9190
ValidArgs: types.AllWebhookTopics(),
92-
PreRun: silenceBeforeRunE,
9391
RunE: verifyCmdRun,
9492
Example: `twitch event verify-subscription subscribe`,
9593
Aliases: []string{
@@ -98,12 +96,11 @@ var verifyCmd = &cobra.Command{
9896
}
9997

10098
var websocketCmd = &cobra.Command{
101-
Use: "websocket [action]",
102-
Short: `Executes actions regarding the mock EventSub WebSocket server. See "twitch event websocket --help" for usage info.`,
103-
Long: fmt.Sprintf(`Executes actions regarding the mock EventSub WebSocket server.`),
104-
Args: cobra.MaximumNArgs(1),
105-
PreRun: silenceBeforeRunE,
106-
RunE: websocketCmdRun,
99+
Use: "websocket [action]",
100+
Short: `Executes actions regarding the mock EventSub WebSocket server. See "twitch event websocket --help" for usage info.`,
101+
Long: fmt.Sprintf(`Executes actions regarding the mock EventSub WebSocket server.`),
102+
Args: cobra.MaximumNArgs(1),
103+
RunE: websocketCmdRun,
107104
Example: fmt.Sprintf(` twitch event websocket start-server
108105
twitch event websocket reconnect
109106
twitch event websocket close --session=e411cc1e_a2613d4e --reason=4006
@@ -119,7 +116,6 @@ var websocketCmd = &cobra.Command{
119116
var retriggerCmd = &cobra.Command{
120117
Use: "retrigger",
121118
Short: "Refires events based on the event ID. Can be forwarded to the local webserver for event testing.",
122-
PreRun: silenceBeforeRunE,
123119
RunE: retriggerCmdRun,
124120
Example: `twitch event retrigger subscribe`,
125121
}
@@ -129,12 +125,6 @@ var startWebsocketServerCmd = &cobra.Command{
129125
Deprecated: `use "twitch event websocket start-server" instead.`,
130126
}
131127

132-
// This is required with commands that use RunE to solve the issues described below
133-
func silenceBeforeRunE(cmd *cobra.Command, args []string) {
134-
cmd.SilenceErrors = true // Prevents printing the help message after an error occurs
135-
cmd.SilenceUsage = true // Prevents printing the error message; This is already done in root.go[cmd.Execute()]
136-
}
137-
138128
func init() {
139129
rootCmd.AddCommand(eventCmd)
140130

cmd/root.go

+2
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ func init() {
3838
os.Exit(1)
3939
}
4040

41+
rootCmd.SilenceErrors = true
42+
rootCmd.SilenceUsage = true
4143
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", fmt.Sprintf("config file (default is %s)", cfgFile))
4244
}
4345

cmd/token.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ var tokenServerIP string
2323
var loginCmd = &cobra.Command{
2424
Use: "token",
2525
Short: "Logs into Twitch and returns an access token according to your client id/secret in the configuration.",
26-
Run: loginCmdRun,
26+
RunE: loginCmdRun,
2727
}
2828

2929
func init() {
@@ -37,7 +37,7 @@ func init() {
3737
loginCmd.Flags().IntVarP(&tokenServerPort, "port", "p", 3000, "Manually set the port to be used for the User Token web server.")
3838
}
3939

40-
func loginCmdRun(cmd *cobra.Command, args []string) {
40+
func loginCmdRun(cmd *cobra.Command, args []string) error {
4141
clientID = viper.GetString("clientId")
4242
clientSecret = viper.GetString("clientSecret")
4343

@@ -74,4 +74,6 @@ func loginCmdRun(cmd *cobra.Command, args []string) {
7474
p.URL = login.ClientCredentialsURL
7575
login.ClientCredentialsLogin(p)
7676
}
77+
78+
return nil
7779
}

cmd/version.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package cmd
44

55
import (
66
"fmt"
7+
78
"github.com/twitchdev/twitch-cli/internal/util"
89

910
"github.com/spf13/cobra"
@@ -12,8 +13,9 @@ import (
1213
var versionCmd = &cobra.Command{
1314
Use: "version",
1415
Short: "Returns the current version of the CLI.",
15-
Run: func(cmd *cobra.Command, args []string) {
16+
RunE: func(cmd *cobra.Command, args []string) error {
1617
fmt.Println("twitch-cli/" + util.GetVersion())
18+
return nil
1719
},
1820
}
1921

0 commit comments

Comments
 (0)