diff --git a/cmd/podman/system/df.go b/cmd/podman/system/df.go index c734bea7e5..099bbb0948 100644 --- a/cmd/podman/system/df.go +++ b/cmd/podman/system/df.go @@ -1,6 +1,7 @@ package system import ( + "bytes" "errors" "fmt" "math" @@ -145,6 +146,7 @@ func printSummary(cmd *cobra.Command, reports *entities.SystemDfReport) error { rpt := report.New(os.Stdout, cmd.Name()) defer rpt.Flush() + report.DefaultFuncs["json"] = rptJSON var err error if cmd.Flags().Changed("format") { @@ -162,7 +164,46 @@ func printSummary(cmd *cobra.Command, reports *entities.SystemDfReport) error { return writeTemplate(rpt, hdrs, dfSummaries) } -func printJSON(data interface{}) error { +type jsonSummary struct { + Type string + Total int + Active int + RawSize int64 + RawReclaimable int64 + + TotalCount int + Size string + Reclaimable string +} + +func jsonConvert(df *dfSummary) *jsonSummary { + return &jsonSummary{ + Type: df.Type, + Total: df.Total, + TotalCount: df.Total, + Active: df.Active, + RawSize: df.RawSize, + RawReclaimable: df.RawReclaimable, + Size: df.Size(), + Reclaimable: df.Reclaimable(), + } +} + +func rptJSON(df *dfSummary) string { + buf := new(bytes.Buffer) + enc := json.NewEncoder(buf) + enc.SetEscapeHTML(false) + _ = enc.Encode(jsonConvert(df)) + // Remove the trailing new line added by the encoder + return strings.TrimSpace(buf.String()) +} + +func printJSON(dfSummaries []*dfSummary) error { + data := make([]jsonSummary, len(dfSummaries)) + for i, df := range dfSummaries { + data[i] = *jsonConvert(df) + } + bytes, err := json.MarshalIndent(data, "", " ") if err != nil { return err diff --git a/test/system/320-system-df.bats b/test/system/320-system-df.bats index 46cd890a24..b7ba34006d 100644 --- a/test/system/320-system-df.bats +++ b/test/system/320-system-df.bats @@ -19,6 +19,23 @@ function teardown() { is "$output" ".*Local Volumes *0 *0 " "No volumes" } +@test "podman system df --format {{ json . }} functionality" { + run_podman system df --format '{{json .}}' + is "$output" '.*"TotalCount":1' "Exactly one image" + is "$output" '.*"RawSize".*"Size"' "RawSize and Size reported" + is "$output" '.*"RawReclaimable".*"Reclaimable"' "RawReclaimable and Reclaimable reported" + is "$output" '.*"Containers".*"Total":0' "Total containers reported" + is "$output" '.*"Local Volumes".*"Size":"0B"' "Total containers reported" + is "$output" '.*"Local Volumes".*"Size":"0B"' "Total containers reported" +} + +@test "podman system df --format json functionality" { + run_podman system df --format json + is "$output" '.*"TotalCount": 1' "Exactly one image" + is "$output" '.*"RawSize": 0' "RawSize reported" + is "$output" '.*"Size": "0B"' "Size reported" +} + @test "podman system df - with active containers and volumes" { run_podman run -v /myvol1 --name c1 $IMAGE true run_podman run -d -v /myvol2 --name c2 $IMAGE \