Improved improper use of os.Exit

This commit is contained in:
keitosuwahara 2025-07-23 21:55:43 +09:00
parent 17ba6c7188
commit e539d22110
2 changed files with 6 additions and 21 deletions

View File

@ -18,7 +18,6 @@ package compatibility
import ( import (
"fmt" "fmt"
"os"
"strings" "strings"
"github.com/docker/compose/v2/cmd/compose" "github.com/docker/compose/v2/cmd/compose"
@ -52,7 +51,7 @@ func getStringFlags() []string {
} }
// Convert transforms standalone docker-compose args into CLI plugin compliant ones // Convert transforms standalone docker-compose args into CLI plugin compliant ones
func Convert(args []string) []string { func Convert(args []string) ([]string, error) {
var rootFlags []string var rootFlags []string
command := []string{compose.PluginName} command := []string{compose.PluginName}
l := len(args) l := len(args)
@ -87,8 +86,7 @@ ARGS:
if arg == flag { if arg == flag {
i++ i++
if i >= l { if i >= l {
fmt.Fprintf(os.Stderr, "flag needs an argument: '%s'\n", arg) return nil, fmt.Errorf("flag needs an argument: '%s'", arg)
os.Exit(1)
} }
rootFlags = append(rootFlags, arg, args[i]) rootFlags = append(rootFlags, arg, args[i])
continue ARGS continue ARGS
@ -103,7 +101,7 @@ ARGS:
} }
command = append(command, arg) command = append(command, arg)
} }
return append(rootFlags, command...) return append(rootFlags, command...), nil
} }
func contains(array []string, needle string) bool { func contains(array []string, needle string) bool {

View File

@ -17,9 +17,6 @@
package compatibility package compatibility
import ( import (
"errors"
"os"
"os/exec"
"testing" "testing"
"gotest.tools/v3/assert" "gotest.tools/v3/assert"
@ -110,21 +107,11 @@ func Test_convert(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
got, err := Convert(tt.args)
if tt.wantErr { if tt.wantErr {
if os.Getenv("BE_CRASHER") == "1" { assert.Assert(t, err != nil)
Convert(tt.args)
return
}
cmd := exec.Command(os.Args[0], "-test.run=^"+t.Name()+"$")
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
err := cmd.Run()
var e *exec.ExitError
if errors.As(err, &e) && !e.Success() {
return
}
t.Fatalf("process ran with err %v, want exit status 1", err)
} else { } else {
got := Convert(tt.args) assert.NilError(t, err)
assert.DeepEqual(t, tt.want, got) assert.DeepEqual(t, tt.want, got)
} }
}) })