Skip to content

Commit

Permalink
Merge pull request #2619 from AkihiroSuda/fix-2598
Browse files Browse the repository at this point in the history
nerdctl ps: implement `--format {{.Label "foo"}}`
  • Loading branch information
AkihiroSuda authored Nov 2, 2023
2 parents 13d6d9a + 2af4cef commit 4e3fd3b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion cmd/nerdctl/container_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func formatAndPrintContainerInfo(containers []container.ListItem, options Format
for _, c := range containers {
if tmpl != nil {
var b bytes.Buffer
if err := tmpl.Execute(&b, c); err != nil {
if err := tmpl.Execute(&b, &c); err != nil {
return err
}
if _, err := fmt.Fprintln(w, b.String()); err != nil {
Expand Down
43 changes: 43 additions & 0 deletions cmd/nerdctl/container_list_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"fmt"
"testing"

"github.com/containerd/nerdctl/pkg/testutil"
)

// https://github.com/containerd/nerdctl/issues/2598
func TestContainerListWithFormatLabel(t *testing.T) {
t.Parallel()
base := testutil.NewBase(t)
tID := testutil.Identifier(t)
cID := tID
labelK := "label-key-" + tID
labelV := "label-value-" + tID

base.Cmd("run", "-d",
"--name", cID,
"--label", labelK+"="+labelV,
testutil.CommonImage, "sleep", "infinity").AssertOK()
defer base.Cmd("rm", "-f", cID).AssertOK()
base.Cmd("ps", "-a",
"--filter", "label="+labelK,
"--format", fmt.Sprintf("{{.Label %q}}", labelK)).AssertOutExactly(labelV + "\n")
}
4 changes: 4 additions & 0 deletions pkg/cmd/container/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ type ListItem struct {
// TODO: "LocalVolumes", "Mounts", "Networks", "RunningFor", "State"
}

func (x *ListItem) Label(s string) string {
return x.Labels[s]
}

func prepareContainers(ctx context.Context, client *containerd.Client, containers []containerd.Container, options types.ContainerListOptions) ([]ListItem, error) {
listItems := make([]ListItem, len(containers))
for i, c := range containers {
Expand Down

0 comments on commit 4e3fd3b

Please sign in to comment.