Skip to content

Commit 22c2428

Browse files
authored
pkg/helpers: Use os.CopyFS to copy directory content
Closes #137
1 parent 4234b0a commit 22c2428

1 file changed

Lines changed: 6 additions & 53 deletions

File tree

pkg/helpers/helpers.go

Lines changed: 6 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import (
2525
"log"
2626
"os"
2727
"path/filepath"
28-
"strings"
2928
)
3029

3130
// IsDir reports whether path is a directory, returning an error if path does
@@ -114,8 +113,8 @@ func CopyFile(src, dst string) error {
114113
}
115114

116115
// CopyDirectoryContent copies the content of the src directory to the dst
117-
// directory. Returns an error if src does not exist, or if src is not a
118-
// directory.
116+
// directory, creating dst if necessary and overwriting existing files. Returns
117+
// an error if src does not exist, or if src is not a directory.
119118
func CopyDirectoryContent(src, dst string) error {
120119
fi, err := os.Stat(src)
121120
if err != nil {
@@ -125,59 +124,13 @@ func CopyDirectoryContent(src, dst string) error {
125124
return fmt.Errorf("%s is not a directory", src)
126125
}
127126

128-
err = filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
129-
if err != nil {
130-
return err
131-
}
132-
if path == src {
133-
return nil
134-
}
135-
136-
target := filepath.Join(dst, strings.TrimPrefix(path, src))
137-
err = os.MkdirAll(filepath.Dir(target), 0o777)
138-
if err != nil {
139-
return err
140-
}
141-
142-
if d.IsDir() {
143-
return nil
144-
}
145-
146-
source, err := os.Open(path)
147-
if err != nil {
148-
return err
149-
}
150-
defer source.Close()
127+
srcFS := os.DirFS(src)
151128

152-
destination, err := os.Create(target)
153-
if err != nil {
154-
return err
155-
}
156-
defer func() {
157-
if err := destination.Close(); err != nil {
158-
log.Fatal(err)
159-
}
160-
}()
161-
162-
_, err = io.Copy(destination, source)
163-
if err != nil {
164-
return err
165-
}
166-
167-
fi, err := d.Info()
168-
if err != nil {
169-
return err
170-
}
171-
srcPerm := fi.Mode().Perm()
172-
err = destination.Chmod(srcPerm)
173-
if err != nil {
129+
err = os.CopyFS(dst, srcFS)
130+
if err != nil {
131+
if !errors.Is(err, fs.ErrExist) {
174132
return err
175133
}
176-
177-
return nil
178-
})
179-
if err != nil {
180-
return err
181134
}
182135

183136
return nil

0 commit comments

Comments
 (0)