Skip to content

Commit 4907e59

Browse files
committed
fix container list with json format
Signed-off-by: Kay Yan <[email protected]>
1 parent ec4bc82 commit 4907e59

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

cmd/nerdctl/container_list_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,21 @@ func TestContainerListWithFormatLabel(t *testing.T) {
4141
"--filter", "label="+labelK,
4242
"--format", fmt.Sprintf("{{.Label %q}}", labelK)).AssertOutExactly(labelV + "\n")
4343
}
44+
45+
func TestContainerListWithJsonFormatLabel(t *testing.T) {
46+
t.Parallel()
47+
base := testutil.NewBase(t)
48+
tID := testutil.Identifier(t)
49+
cID := tID
50+
labelK := "label-key-" + tID
51+
labelV := "label-value-" + tID
52+
53+
base.Cmd("run", "-d",
54+
"--name", cID,
55+
"--label", labelK+"="+labelV,
56+
testutil.CommonImage, "sleep", "infinity").AssertOK()
57+
defer base.Cmd("rm", "-f", cID).AssertOK()
58+
base.Cmd("ps", "-a",
59+
"--filter", "label="+labelK,
60+
"--format", "json").AssertOutContains(fmt.Sprintf("%s=%s", labelK, labelV))
61+
}

pkg/cmd/container/list.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,14 @@ type ListItem struct {
9797
Status string
9898
Runtime string // nerdctl extension
9999
Size string
100-
Labels map[string]string
100+
Labels string
101+
LabelsMap map[string]string `json:"-"`
102+
101103
// TODO: "LocalVolumes", "Mounts", "Networks", "RunningFor", "State"
102104
}
103105

104106
func (x *ListItem) Label(s string) string {
105-
return x.Labels[s]
107+
return x.LabelsMap[s]
106108
}
107109

108110
func prepareContainers(ctx context.Context, client *containerd.Client, containers []containerd.Container, options types.ContainerListOptions) ([]ListItem, error) {
@@ -138,7 +140,8 @@ func prepareContainers(ctx context.Context, client *containerd.Client, container
138140
Ports: formatter.FormatPorts(info.Labels),
139141
Status: formatter.ContainerStatus(ctx, c),
140142
Runtime: info.Runtime.Name,
141-
Labels: info.Labels,
143+
Labels: formatter.FormatLabels(info.Labels),
144+
LabelsMap: info.Labels,
142145
}
143146
if options.Size {
144147
containerSize, err := getContainerSize(ctx, client, c, info)

0 commit comments

Comments
 (0)