Skip to content

Commit b088051

Browse files
committed
feat(core): add option to return specific error codes
Signed-off-by: Patrik Cyvoct <[email protected]>
1 parent f92de47 commit b088051

File tree

4 files changed

+53
-1
lines changed

4 files changed

+53
-1
lines changed

internal/core/bootstrap.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -125,11 +125,15 @@ func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err e
125125
if _, ok := err.(*interactive.InterruptError); ok {
126126
return 130, nil, err
127127
}
128+
errorCode := 1
129+
if cliErr, ok := err.(*CliError); ok && cliErr.Code != 0 {
130+
errorCode = cliErr.Code
131+
}
128132
printErr := meta.Printer.Print(err, nil)
129133
if printErr != nil {
130134
_, _ = fmt.Fprintln(os.Stderr, err)
131135
}
132-
return 1, nil, err
136+
return errorCode, nil, err
133137
}
134138
return 0, meta.result, nil
135139
}

internal/core/bootstrap_test.go

+38
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,42 @@ func TestInterruptError(t *testing.T) {
2727
Cmd: "scw test interrupt error",
2828
Check: TestCheckExitCode(130),
2929
}))
30+
t.Run("exit-code", Test(&TestConfig{
31+
Commands: NewCommands(
32+
&Command{
33+
Namespace: "test",
34+
Resource: "code",
35+
Verb: "error",
36+
ArgsType: reflect.TypeOf(args.RawArgs{}),
37+
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
38+
return nil, &CliError{Code: 99}
39+
},
40+
},
41+
),
42+
UseE2EClient: true,
43+
DisableParallel: true, // because e2e client is used
44+
Cmd: "scw test code error",
45+
Check: TestCheckExitCode(99),
46+
}))
47+
t.Run("emtpy-error", Test(&TestConfig{
48+
Commands: NewCommands(
49+
&Command{
50+
Namespace: "test",
51+
Resource: "empty",
52+
Verb: "error",
53+
ArgsType: reflect.TypeOf(args.RawArgs{}),
54+
Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
55+
return nil, &CliError{Code: 99, Empty: true}
56+
},
57+
},
58+
),
59+
UseE2EClient: true,
60+
DisableParallel: true, // because e2e client is used
61+
Cmd: "scw test empty error",
62+
Check: TestCheckCombine(
63+
TestCheckExitCode(99),
64+
TestCheckStderrGolden(),
65+
),
66+
}))
67+
3068
}

internal/core/error.go

+9
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,22 @@ type CliError struct {
2323

2424
Details string
2525
Hint string
26+
27+
// Code allows to return a sepcific error code from the main binary.
28+
Code int
29+
30+
// Empty tells the marshaler to not print any message for the error
31+
Empty bool
2632
}
2733

2834
func (s *CliError) Error() string {
2935
return s.Err.Error()
3036
}
3137

3238
func (s *CliError) MarshalHuman() (string, error) {
39+
if s.Empty {
40+
return "", nil
41+
}
3342
sections := []string(nil)
3443
if s.Err != nil {
3544
humanError := s.Err
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

0 commit comments

Comments
 (0)