Skip to content

Commit 5af18d8

Browse files
Merge pull request #7 from carolynvs/fix-copy-over-existing-dir
Fix copying over an existing directory
2 parents bf968bb + a4a8515 commit 5af18d8

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

shx/copy.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,19 @@ func Copy(src string, dest string, opts ...CopyOption) error {
2828
}
2929

3030
if len(items) == 0 {
31-
return errors.Errorf("no such file or directory %q", src)
31+
return errors.Errorf("no such file or directory '%s'", src)
3232
}
3333

3434
var combinedOpts CopyOption
3535
for _, opt := range opts {
3636
combinedOpts |= opt
3737
}
3838

39+
// Check if the destination exists, e.g. if we are copying to /tmp/foo, /tmp should already exist
40+
if _, err := os.Stat(filepath.Dir(dest)); err != nil {
41+
return err
42+
}
43+
3944
for _, item := range items {
4045
err := copyFileOrDirectory(item, dest, combinedOpts)
4146
if err != nil {
@@ -71,7 +76,7 @@ func copyFileOrDirectory(src string, dest string, opts CopyOption) error {
7176
destPath := filepath.Join(dest, relPath)
7277

7378
if srcInfo.IsDir() {
74-
return os.Mkdir(destPath, srcInfo.Mode())
79+
return os.MkdirAll(destPath, srcInfo.Mode())
7580
}
7681

7782
return copyFile(srcPath, destPath, opts)

shx/copy_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,24 @@ func TestCopy(t *testing.T) {
2727
assertFile(t, filepath.Join(tmp, "a/ab/ab2.txt"))
2828
})
2929

30+
t.Run("recursively copy directory into populated dest dir", func(t *testing.T) {
31+
tmp, err := ioutil.TempDir("", "magex")
32+
require.NoError(t, err, "could not create temp directory for test")
33+
defer os.RemoveAll(tmp)
34+
35+
require.NoError(t, os.MkdirAll(filepath.Join(tmp, "a"), 0755))
36+
37+
err = Copy("testdata/copy/a", tmp, CopyRecursive)
38+
require.NoError(t, err, "Copy into directory with same directory name")
39+
40+
assert.DirExists(t, filepath.Join(tmp, "a"))
41+
assertFile(t, filepath.Join(tmp, "a/a1.txt"))
42+
assertFile(t, filepath.Join(tmp, "a/a2.txt"))
43+
assert.DirExists(t, filepath.Join(tmp, "a/ab"))
44+
assertFile(t, filepath.Join(tmp, "a/ab/ab1.txt"))
45+
assertFile(t, filepath.Join(tmp, "a/ab/ab2.txt"))
46+
})
47+
3048
t.Run("copy glob", func(t *testing.T) {
3149
tmp, err := ioutil.TempDir("", "magex")
3250
require.NoError(t, err, "could not create temp directory for test")

0 commit comments

Comments
 (0)