diff.go 1.4 KB

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