cli/command: Avoid panics after client initialization errors

When client.New rejects an invalid Docker host or other client option,
it returns a nil concrete client with an error.

Returning that pointer directly as client.APIClient stores a typed-nil
interface, so lazy version checks dereference it.

Return an error instead.

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
This commit is contained in:
Paweł Gronowski
2026-09-03 10:59:11 +02:00
parent 9878ff214b
commit b07de47694
2 changed files with 14 additions and 1 deletions
+5 -1
View File
@@ -316,7 +316,11 @@ func newAPIClientFromEndpoint(ep docker.Endpoint, configFile *configfile.ConfigF
opts = append(opts, withCustomHeaders)
}
opts = append(opts, extraOpts...)
return client.New(opts...)
apiClient, err := client.New(opts...)
if err != nil {
return nil, err
}
return apiClient, nil
}
func resolveDockerEndpoint(s store.Reader, contextName string) (docker.Endpoint, error) {
+9
View File
@@ -132,6 +132,15 @@ func TestNewAPIClientFromFlagsWithAPIVersionFromEnv(t *testing.T) {
assert.Equal(t, apiclient.ClientVersion(), expectedVersion)
}
func TestNewAPIClientFromFlagsWithInvalidAPIVersionFromEnv(t *testing.T) {
t.Setenv("DOCKER_API_VERSION", "1")
t.Setenv("DOCKER_HOST", ":2375")
apiClient, err := NewAPIClientFromFlags(&flags.ClientOptions{}, &configfile.ConfigFile{})
assert.ErrorContains(t, err, "invalid API version")
assert.Check(t, apiClient == nil)
}
type fakeClient struct {
client.Client
pingFunc func() (client.PingResult, error)