copyConfigTree copies fixture bytes without following contained symlinks. Each destination is new and private; no caller configuration is copied implicitly.
(source, destination string)
| 27 | // copyConfigTree copies fixture bytes without following contained symlinks. |
| 28 | // Each destination is new and private; no caller configuration is copied implicitly. |
| 29 | func copyConfigTree(source, destination string) (err error) { |
| 30 | source, err = filepath.EvalSymlinks(source) |
| 31 | if err != nil { |
| 32 | return err |
| 33 | } |
| 34 | source, err = filepath.Abs(source) |
| 35 | if err != nil { |
| 36 | return err |
| 37 | } |
| 38 | src, err := os.OpenRoot(source) |
| 39 | if err != nil { |
| 40 | return err |
| 41 | } |
| 42 | defer src.Close() |
| 43 | destination, err = filepath.Abs(destination) |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 | parent, suffix := filepath.Dir(destination), filepath.Base(destination) |
| 48 | for { |
| 49 | resolved, resolveErr := filepath.EvalSymlinks(parent) |
| 50 | if resolveErr == nil { |
| 51 | destination = filepath.Join(resolved, suffix) |
| 52 | break |
| 53 | } |
| 54 | if !errors.Is(resolveErr, fs.ErrNotExist) || filepath.Dir(parent) == parent { |
| 55 | return resolveErr |
| 56 | } |
| 57 | suffix = filepath.Join(filepath.Base(parent), suffix) |
| 58 | parent = filepath.Dir(parent) |
| 59 | } |
| 60 | if pathWithin(source, destination) { |
| 61 | return fmt.Errorf("cannot copy configuration into its source") |
| 62 | } |
| 63 | if err := os.MkdirAll(filepath.Dir(destination), 0o700); err != nil { |
| 64 | return err |
| 65 | } |
| 66 | if err := os.Mkdir(destination, 0o700); err != nil { |
| 67 | return err |
| 68 | } |
| 69 | defer func() { |
| 70 | if err != nil { |
| 71 | err = errors.Join(err, os.RemoveAll(destination)) |
| 72 | } |
| 73 | }() |
| 74 | dst, err := os.OpenRoot(destination) |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | defer dst.Close() |
| 79 | return fs.WalkDir(src.FS(), ".", func(name string, entry fs.DirEntry, walkErr error) error { |
| 80 | if walkErr != nil || name == "." { |
| 81 | return walkErr |
| 82 | } |
| 83 | if entry.IsDir() { |
| 84 | return dst.Mkdir(filepath.FromSlash(name), 0o700) |
| 85 | } |
| 86 | info, err := entry.Info() |