Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buildctl (du|prune|debug info): support --format {{json .}} #2992

Merged
merged 4 commits into from
Aug 2, 2022
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
22 changes: 11 additions & 11 deletions client/diskusage.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ import (
)

type UsageInfo struct {
ID string
Mutable bool
InUse bool
Size int64
ID string `json:"id"`
Mutable bool `json:"mutable"`
InUse bool `json:"inUse"`
Size int64 `json:"size"`

CreatedAt time.Time
LastUsedAt *time.Time
UsageCount int
Parents []string
Description string
RecordType UsageRecordType
Shared bool
CreatedAt time.Time `json:"createdAt"`
LastUsedAt *time.Time `json:"lastUsedAt"`
UsageCount int `json:"usageCount"`
Parents []string `json:"parents"`
Description string `json:"description"`
RecordType UsageRecordType `json:"recordType"`
Shared bool `json:"shared"`
}

func (c *Client) DiskUsage(ctx context.Context, opts ...DiskUsageOption) ([]*UsageInfo, error) {
Expand Down
8 changes: 4 additions & 4 deletions client/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import (
)

type Info struct {
BuildkitVersion BuildkitVersion
BuildkitVersion BuildkitVersion `json:"buildkitVersion"`
}

type BuildkitVersion struct {
Package string
Version string
Revision string
Package string `json:"package"`
Version string `json:"version"`
Revision string `json:"revision"`
}

func (c *Client) Info(ctx context.Context) (*Info, error) {
Expand Down
26 changes: 26 additions & 0 deletions cmd/buildctl/common/common.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package common

import (
"bytes"
"context"
"encoding/json"
"net/url"
"os"
"path/filepath"
"strings"
"text/template"
"time"

"github.com/moby/buildkit/client"
Expand Down Expand Up @@ -88,3 +92,25 @@ func ResolveClient(c *cli.Context) (*client.Client, error) {

return client.New(ctx, c.GlobalString("addr"), opts...)
}

func ParseTemplate(format string) (*template.Template, error) {
// aliases is from https://github.com/containerd/nerdctl/blob/v0.17.1/cmd/nerdctl/fmtutil.go#L116-L126 (Apache License 2.0)
aliases := map[string]string{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this? I think the examples in the PR work without this as well.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not new in this PR, just moved from cmd/buildctl/debug/workers.go
405565c

"json": "{{json .}}",
}
if alias, ok := aliases[format]; ok {
format = alias
}
// funcs is from https://github.com/docker/cli/blob/v20.10.12/templates/templates.go#L12-L20 (Apache License 2.0)
funcs := template.FuncMap{
"json": func(v interface{}) string {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
enc.Encode(v)
// Remove the trailing new line added by the encoder
return strings.TrimSpace(buf.String())
},
}
return template.New("").Funcs(funcs).Parse(format)
}
18 changes: 18 additions & 0 deletions cmd/buildctl/debug/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ var InfoCommand = cli.Command{
Name: "info",
Usage: "display internal information",
Action: info,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format",
Usage: "Format the output using the given Go template, e.g, '{{json .}}'",
},
},
}

func info(clicontext *cli.Context) error {
Expand All @@ -24,6 +30,18 @@ func info(clicontext *cli.Context) error {
if err != nil {
return err
}
if format := clicontext.String("format"); format != "" {
tmpl, err := bccommon.ParseTemplate(format)
if err != nil {
return err
}
if err := tmpl.Execute(clicontext.App.Writer, res); err != nil {
return err
}
_, err = fmt.Fprintf(clicontext.App.Writer, "\n")
return err
}

w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
_, _ = fmt.Fprintf(w, "BuildKit:\t%s %s %s\n", res.BuildkitVersion.Package, res.BuildkitVersion.Version, res.BuildkitVersion.Revision)
return w.Flush()
Expand Down
27 changes: 1 addition & 26 deletions cmd/buildctl/debug/workers.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package debug

import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"text/tabwriter"
"text/template"

"github.com/containerd/containerd/platforms"
"github.com/moby/buildkit/client"
Expand Down Expand Up @@ -54,7 +51,7 @@ func listWorkers(clicontext *cli.Context) error {
if clicontext.Bool("verbose") {
logrus.Debug("Ignoring --verbose")
}
tmpl, err := parseTemplate(format)
tmpl, err := bccommon.ParseTemplate(format)
if err != nil {
return err
}
Expand Down Expand Up @@ -137,25 +134,3 @@ func joinPlatforms(p []ocispecs.Platform) string {
}
return strings.Join(str, ",")
}

func parseTemplate(format string) (*template.Template, error) {
// aliases is from https://github.com/containerd/nerdctl/blob/v0.17.1/cmd/nerdctl/fmtutil.go#L116-L126 (Apache License 2.0)
aliases := map[string]string{
"json": "{{json .}}",
}
if alias, ok := aliases[format]; ok {
format = alias
}
// funcs is from https://github.com/docker/cli/blob/v20.10.12/templates/templates.go#L12-L20 (Apache License 2.0)
funcs := template.FuncMap{
"json": func(v interface{}) string {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
enc.Encode(v)
// Remove the trailing new line added by the encoder
return strings.TrimSpace(buf.String())
},
}
return template.New("").Funcs(funcs).Parse(format)
}
20 changes: 20 additions & 0 deletions cmd/buildctl/diskusage.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/moby/buildkit/client"
bccommon "github.com/moby/buildkit/cmd/buildctl/common"
"github.com/sirupsen/logrus"
"github.com/tonistiigi/units"
"github.com/urfave/cli"
)
Expand All @@ -26,6 +27,10 @@ var diskUsageCommand = cli.Command{
Name: "verbose, v",
Usage: "Verbose output",
},
cli.StringFlag{
Name: "format",
Usage: "Format the output using the given Go template, e.g, '{{json .}}'",
},
},
}

Expand All @@ -40,6 +45,21 @@ func diskUsage(clicontext *cli.Context) error {
return err
}

if format := clicontext.String("format"); format != "" {
if clicontext.Bool("verbose") {
logrus.Debug("Ignoring --verbose")
}
tmpl, err := bccommon.ParseTemplate(format)
if err != nil {
return err
}
if err := tmpl.Execute(clicontext.App.Writer, du); err != nil {
return err
}
_, err = fmt.Fprintf(clicontext.App.Writer, "\n")
return err
}

tw := tabwriter.NewWriter(os.Stdout, 1, 8, 1, '\t', 0)

if clicontext.Bool("verbose") {
Expand Down
82 changes: 56 additions & 26 deletions cmd/buildctl/prune.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/moby/buildkit/client"
bccommon "github.com/moby/buildkit/cmd/buildctl/common"
"github.com/sirupsen/logrus"
"github.com/tonistiigi/units"
"github.com/urfave/cli"
)
Expand Down Expand Up @@ -36,6 +37,10 @@ var pruneCommand = cli.Command{
Name: "verbose, v",
Usage: "Verbose output",
},
cli.StringFlag{
Name: "format",
Usage: "Format the output using the given Go template, e.g, '{{json .}}'",
},
},
}

Expand All @@ -47,27 +52,7 @@ func prune(clicontext *cli.Context) error {

ch := make(chan client.UsageInfo)
printed := make(chan struct{})

tw := tabwriter.NewWriter(os.Stdout, 1, 8, 1, '\t', 0)
first := true
total := int64(0)

go func() {
defer close(printed)
for du := range ch {
total += du.Size
if clicontext.Bool("verbose") {
printVerbose(tw, []*client.UsageInfo{&du})
} else {
if first {
printTableHeader(tw)
first = false
}
printTableRow(tw, &du)
tw.Flush()
}
}
}()
var summarizer func()

opts := []client.PruneOption{
client.WithFilter(clicontext.StringSlice("filter")),
Expand All @@ -78,16 +63,61 @@ func prune(clicontext *cli.Context) error {
opts = append(opts, client.PruneAll)
}

if format := clicontext.String("format"); format != "" {
if clicontext.Bool("verbose") {
logrus.Debug("Ignoring --verbose")
}
tmpl, err := bccommon.ParseTemplate(format)
if err != nil {
return err
}
go func() {
defer close(printed)
for du := range ch {
// Unlike `buildctl du`, the template is applied to a UsageInfo, not to a slice of UsageInfo
if err := tmpl.Execute(clicontext.App.Writer, du); err != nil {
panic(err)
}
if _, err = fmt.Fprintf(clicontext.App.Writer, "\n"); err != nil {
panic(err)
}
}
}()
} else {
tw := tabwriter.NewWriter(os.Stdout, 1, 8, 1, '\t', 0)
first := true
total := int64(0)
go func() {
defer close(printed)
for du := range ch {
total += du.Size
if clicontext.Bool("verbose") {
printVerbose(tw, []*client.UsageInfo{&du})
} else {
if first {
printTableHeader(tw)
first = false
}
printTableRow(tw, &du)
tw.Flush()
}
}
}()
summarizer = func() {
tw = tabwriter.NewWriter(os.Stdout, 1, 8, 1, '\t', 0)
fmt.Fprintf(tw, "Total:\t%.2f\n", units.Bytes(total))
tw.Flush()
}
}

err = c.Prune(bccommon.CommandContext(clicontext), ch, opts...)
close(ch)
<-printed
if err != nil {
return err
}

tw = tabwriter.NewWriter(os.Stdout, 1, 8, 1, '\t', 0)
fmt.Fprintf(tw, "Total:\t%.2f\n", units.Bytes(total))
tw.Flush()

if summarizer != nil {
summarizer()
}
return nil
}