changes.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package docker
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. )
  8. type ChangeType int
  9. const (
  10. ChangeModify = iota
  11. ChangeAdd
  12. ChangeDelete
  13. )
  14. type Change struct {
  15. Path string
  16. Kind ChangeType
  17. }
  18. func (change *Change) String() string {
  19. var kind string
  20. switch change.Kind {
  21. case ChangeModify:
  22. kind = "C"
  23. case ChangeAdd:
  24. kind = "A"
  25. case ChangeDelete:
  26. kind = "D"
  27. }
  28. return fmt.Sprintf("%s %s", kind, change.Path)
  29. }
  30. func Changes(layers []string, rw string) ([]Change, error) {
  31. var changes []Change
  32. err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error {
  33. if err != nil {
  34. return err
  35. }
  36. // Rebase path
  37. path, err = filepath.Rel(rw, path)
  38. if err != nil {
  39. return err
  40. }
  41. path = filepath.Join("/", path)
  42. // Skip root
  43. if path == "/" {
  44. return nil
  45. }
  46. // Skip AUFS metadata
  47. if matched, err := filepath.Match("/.wh..wh.*", path); err != nil || matched {
  48. return err
  49. }
  50. change := Change{
  51. Path: path,
  52. }
  53. // Find out what kind of modification happened
  54. file := filepath.Base(path)
  55. // If there is a whiteout, then the file was removed
  56. if strings.HasPrefix(file, ".wh.") {
  57. originalFile := strings.TrimPrefix(file, ".wh.")
  58. change.Path = filepath.Join(filepath.Dir(path), originalFile)
  59. change.Kind = ChangeDelete
  60. } else {
  61. // Otherwise, the file was added
  62. change.Kind = ChangeAdd
  63. // ...Unless it already existed in a top layer, in which case, it's a modification
  64. for _, layer := range layers {
  65. stat, err := os.Stat(filepath.Join(layer, path))
  66. if err != nil && !os.IsNotExist(err) {
  67. return err
  68. }
  69. if err == nil {
  70. // The file existed in the top layer, so that's a modification
  71. // However, if it's a directory, maybe it wasn't actually modified.
  72. // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar
  73. if stat.IsDir() && f.IsDir() {
  74. if f.Size() == stat.Size() && f.Mode() == stat.Mode() && f.ModTime() == stat.ModTime() {
  75. // Both directories are the same, don't record the change
  76. return nil
  77. }
  78. }
  79. change.Kind = ChangeModify
  80. break
  81. }
  82. }
  83. }
  84. // Record change
  85. changes = append(changes, change)
  86. return nil
  87. })
  88. if err != nil {
  89. return nil, err
  90. }
  91. return changes, nil
  92. }