github.com/ali-iotechsys/cli@v20.10.0+incompatible/cli/command/container/formatter_diff.go (about)

     1  package container
     2  
     3  import (
     4  	"github.com/docker/cli/cli/command/formatter"
     5  	"github.com/docker/docker/api/types/container"
     6  	"github.com/docker/docker/pkg/archive"
     7  )
     8  
     9  const (
    10  	defaultDiffTableFormat = "table {{.Type}}\t{{.Path}}"
    11  
    12  	changeTypeHeader = "CHANGE TYPE"
    13  	pathHeader       = "PATH"
    14  )
    15  
    16  // NewDiffFormat returns a format for use with a diff Context
    17  func NewDiffFormat(source string) formatter.Format {
    18  	switch source {
    19  	case formatter.TableFormatKey:
    20  		return defaultDiffTableFormat
    21  	}
    22  	return formatter.Format(source)
    23  }
    24  
    25  // DiffFormatWrite writes formatted diff using the Context
    26  func DiffFormatWrite(ctx formatter.Context, changes []container.ContainerChangeResponseItem) error {
    27  
    28  	render := func(format func(subContext formatter.SubContext) error) error {
    29  		for _, change := range changes {
    30  			if err := format(&diffContext{c: change}); err != nil {
    31  				return err
    32  			}
    33  		}
    34  		return nil
    35  	}
    36  	return ctx.Write(newDiffContext(), render)
    37  }
    38  
    39  type diffContext struct {
    40  	formatter.HeaderContext
    41  	c container.ContainerChangeResponseItem
    42  }
    43  
    44  func newDiffContext() *diffContext {
    45  	diffCtx := diffContext{}
    46  	diffCtx.Header = formatter.SubHeaderContext{
    47  		"Type": changeTypeHeader,
    48  		"Path": pathHeader,
    49  	}
    50  	return &diffCtx
    51  }
    52  
    53  func (d *diffContext) MarshalJSON() ([]byte, error) {
    54  	return formatter.MarshalJSON(d)
    55  }
    56  
    57  func (d *diffContext) Type() string {
    58  	var kind string
    59  	switch d.c.Kind {
    60  	case archive.ChangeModify:
    61  		kind = "C"
    62  	case archive.ChangeAdd:
    63  		kind = "A"
    64  	case archive.ChangeDelete:
    65  		kind = "D"
    66  	}
    67  	return kind
    68  
    69  }
    70  
    71  func (d *diffContext) Path() string {
    72  	return d.c.Path
    73  }