Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions container/container.from_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/stretchr/testify/require"

"github.com/docker/go-sdk/client"
"github.com/docker/go-sdk/container"
)

Expand Down Expand Up @@ -45,3 +46,20 @@ func TestFromID(t *testing.T) {
err = ctr.Terminate(context.Background())
require.Error(t, err)
}

func TestFromID_Errors(t *testing.T) {
cli, err := client.New(context.Background())
require.NoError(t, err)

// Attempt to create a container with an invalid ID
recreated, err := container.FromID(context.Background(), cli, "invalid-id")
require.Error(t, err)
require.Contains(t, err.Error(), "not found")
require.Nil(t, recreated)

// Attempt to create a container with an empty ID
recreated, err = container.FromID(context.Background(), cli, "")
require.Error(t, err)
require.Contains(t, err.Error(), "id is empty")
require.Nil(t, recreated)
}
20 changes: 5 additions & 15 deletions container/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"log/slog"

"github.com/moby/moby/api/types/container"
dockerclient "github.com/moby/moby/client"

"github.com/docker/go-sdk/client"
"github.com/docker/go-sdk/container/wait"
Expand Down Expand Up @@ -97,23 +96,14 @@ func FromID(ctx context.Context, dockerClient client.SDKClient, containerID stri
dockerClient = sdk
}

response, err := dockerClient.ContainerList(ctx, dockerclient.ContainerListOptions{
All: true,
Filters: make(dockerclient.Filters).Add("id", containerID),
})
summary, err := dockerClient.FindContainerByID(ctx, containerID)
if err != nil {
return nil, fmt.Errorf("list containers: %w", err)
return nil, fmt.Errorf("find container by ID: %w", err)
Comment thread
xHozey marked this conversation as resolved.
}
Comment thread
xHozey marked this conversation as resolved.
Comment thread
xHozey marked this conversation as resolved.

if len(response.Items) == 0 {
return nil, fmt.Errorf("container %s not found", containerID)
}

if len(response.Items) > 1 {
return nil, fmt.Errorf("multiple containers match ID %s", containerID)
if summary == nil {
return nil, fmt.Errorf("find container by ID: container %s not found", containerID)
}

return FromResponse(ctx, dockerClient, response.Items[0])
return FromResponse(ctx, dockerClient, *summary)
}

// FromResponse builds a container struct from the response of the Docker API.
Expand Down