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.
14 // overlayDir makes a minimal-overhead copy of srcRoot in which new files may be added.
16 // TODO: Once we no longer need to support the misc module in GOPATH mode,
17 // factor this function out into a package to reduce duplication.
18 func overlayDir(dstRoot, srcRoot string) error {
19 dstRoot = filepath.Clean(dstRoot)
20 if err := os.MkdirAll(dstRoot, 0777); err != nil {
24 srcRoot, err := filepath.Abs(srcRoot)
29 return filepath.Walk(srcRoot, func(srcPath string, info os.FileInfo, err error) error {
30 if err != nil || srcPath == srcRoot {
34 suffix := strings.TrimPrefix(srcPath, srcRoot)
35 for len(suffix) > 0 && suffix[0] == filepath.Separator {
38 dstPath := filepath.Join(dstRoot, suffix)
40 perm := info.Mode() & os.ModePerm
41 if info.Mode()&os.ModeSymlink != 0 {
42 info, err = os.Stat(srcPath)
46 perm = info.Mode() & os.ModePerm
49 // Always copy directories (don't symlink them).
50 // If we add a file in the overlay, we don't want to add it in the original.
52 return os.MkdirAll(dstPath, perm|0200)
55 // If the OS supports symlinks, use them instead of copying bytes.
56 if err := os.Symlink(srcPath, dstPath); err == nil {
60 // Otherwise, copy the bytes.
61 src, err := os.Open(srcPath)
67 dst, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
72 _, err = io.Copy(dst, src)
73 if closeErr := dst.Close(); err == nil {