overlaydir_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package shared_test
  5. import (
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. )
  11. // overlayDir makes a minimal-overhead copy of srcRoot in which new files may be added.
  12. //
  13. // TODO: Once we no longer need to support the misc module in GOPATH mode,
  14. // factor this function out into a package to reduce duplication.
  15. func overlayDir(dstRoot, srcRoot string) error {
  16. dstRoot = filepath.Clean(dstRoot)
  17. if err := os.MkdirAll(dstRoot, 0777); err != nil {
  18. return err
  19. }
  20. srcRoot, err := filepath.Abs(srcRoot)
  21. if err != nil {
  22. return err
  23. }
  24. return filepath.Walk(srcRoot, func(srcPath string, info os.FileInfo, err error) error {
  25. if err != nil || srcPath == srcRoot {
  26. return err
  27. }
  28. suffix := strings.TrimPrefix(srcPath, srcRoot)
  29. for len(suffix) > 0 && suffix[0] == filepath.Separator {
  30. suffix = suffix[1:]
  31. }
  32. dstPath := filepath.Join(dstRoot, suffix)
  33. perm := info.Mode() & os.ModePerm
  34. if info.Mode()&os.ModeSymlink != 0 {
  35. info, err = os.Stat(srcPath)
  36. if err != nil {
  37. return err
  38. }
  39. perm = info.Mode() & os.ModePerm
  40. }
  41. // Always copy directories (don't symlink them).
  42. // If we add a file in the overlay, we don't want to add it in the original.
  43. if info.IsDir() {
  44. return os.MkdirAll(dstPath, perm|0200)
  45. }
  46. // If the OS supports symlinks, use them instead of copying bytes.
  47. if err := os.Symlink(srcPath, dstPath); err == nil {
  48. return nil
  49. }
  50. // Otherwise, copy the bytes.
  51. src, err := os.Open(srcPath)
  52. if err != nil {
  53. return err
  54. }
  55. defer src.Close()
  56. dst, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
  57. if err != nil {
  58. return err
  59. }
  60. _, err = io.Copy(dst, src)
  61. if closeErr := dst.Close(); err == nil {
  62. err = closeErr
  63. }
  64. return err
  65. })
  66. }