MCPcopy Create free account
hub / github.com/containerd/nerdctl / FormatSlice

Function FormatSlice

pkg/formatter/common.go:41–79  ·  view source on GitHub ↗

FormatSlice formats the slice with `--format` flag. --format="" (default): JSON --format='{{json .}}': JSON lines FormatSlice is expected to be only used for `nerdctl OBJECT inspect` commands.

(format string, writer io.Writer, x []interface{})

Source from the content-addressed store, hash-verified

39//
40// FormatSlice is expected to be only used for `nerdctl OBJECT inspect` commands.
41func FormatSlice(format string, writer io.Writer, x []interface{}) error {
42 var tmpl *template.Template
43 switch format {
44 case "":
45 // Avoid escaping "<", ">", "&"
46 // https://pkg.go.dev/encoding/json
47 encoder := json.NewEncoder(writer)
48 encoder.SetIndent("", " ")
49 encoder.SetEscapeHTML(false)
50 err := encoder.Encode(x)
51 if err != nil {
52 return err
53 }
54 fmt.Fprint(writer, "\n")
55 case "raw", "table", "wide":
56 return errors.New("unsupported format: \"raw\", \"table\", and \"wide\"")
57 default:
58 var err error
59 tmpl, err = ParseTemplate(format)
60 if err != nil {
61 return err
62 }
63 for _, f := range x {
64 var b bytes.Buffer
65 if err := tmpl.Execute(&b, f); err != nil {
66 if _, ok := err.(template.ExecError); ok {
67 // FallBack to Raw Format
68 if err = tryRawFormat(&b, f, tmpl); err != nil {
69 return err
70 }
71 }
72 }
73 if _, err = fmt.Fprintln(writer, b.String()); err != nil {
74 return err
75 }
76 }
77 }
78 return nil
79}
80
81// FormatInspectSlice formats inspect results and propagates template errors back
82// to the caller so CLI commands can fail with a non-zero exit code.

Callers 4

InspectFunction · 0.92
InspectFunction · 0.92
inspectActionFunction · 0.92
FormatInspectSliceFunction · 0.85

Calls 4

ParseTemplateFunction · 0.85
tryRawFormatFunction · 0.85
EncodeMethod · 0.80
StringMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…