github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/builder/prune.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package builder
    18  
    19  import (
    20  	"context"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"os/exec"
    25  
    26  	"github.com/containerd/log"
    27  	"github.com/containerd/nerdctl/v2/pkg/api/types"
    28  	"github.com/containerd/nerdctl/v2/pkg/buildkitutil"
    29  )
    30  
    31  // Prune will prune all build cache.
    32  func Prune(ctx context.Context, options types.BuilderPruneOptions) ([]buildkitutil.UsageInfo, error) {
    33  	buildctlBinary, err := buildkitutil.BuildctlBinary()
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	buildctlArgs := buildkitutil.BuildctlBaseArgs(options.BuildKitHost)
    38  	buildctlArgs = append(buildctlArgs, "prune", "--format={{json .}}")
    39  	if options.All {
    40  		buildctlArgs = append(buildctlArgs, "--all")
    41  	}
    42  	buildctlCmd := exec.Command(buildctlBinary, buildctlArgs...)
    43  	log.G(ctx).Debugf("running %v", buildctlCmd.Args)
    44  	buildctlCmd.Stderr = options.Stderr
    45  	stdout, err := buildctlCmd.StdoutPipe()
    46  	if err != nil {
    47  		return nil, fmt.Errorf("faild to get stdout piper for %v: %w", buildctlCmd.Args, err)
    48  	}
    49  	defer stdout.Close()
    50  	if err = buildctlCmd.Start(); err != nil {
    51  		return nil, fmt.Errorf("faild to start %v: %w", buildctlCmd.Args, err)
    52  	}
    53  	dec := json.NewDecoder(stdout)
    54  	result := make([]buildkitutil.UsageInfo, 0)
    55  	for {
    56  		var v buildkitutil.UsageInfo
    57  		if err := dec.Decode(&v); err == io.EOF {
    58  			break
    59  		} else if err != nil {
    60  			return nil, fmt.Errorf("faild to decode output from %v: %w", buildctlCmd.Args, err)
    61  		}
    62  		result = append(result, v)
    63  	}
    64  	if err = buildctlCmd.Wait(); err != nil {
    65  		return nil, fmt.Errorf("faild to wait for %v to complete: %w", buildctlCmd.Args, err)
    66  	}
    67  
    68  	return result, nil
    69  }