Skip to content

Commit

Permalink
Merge pull request #7 from carolynvs/fix-copy-over-existing-dir
Browse files Browse the repository at this point in the history
Fix copying over an existing directory
  • Loading branch information
carolynvs-msft authored May 3, 2021
2 parents bf968bb + a4a8515 commit 5af18d8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
9 changes: 7 additions & 2 deletions shx/copy.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,19 @@ func Copy(src string, dest string, opts ...CopyOption) error {
}

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

var combinedOpts CopyOption
for _, opt := range opts {
combinedOpts |= opt
}

// Check if the destination exists, e.g. if we are copying to /tmp/foo, /tmp should already exist
if _, err := os.Stat(filepath.Dir(dest)); err != nil {
return err
}

for _, item := range items {
err := copyFileOrDirectory(item, dest, combinedOpts)
if err != nil {
Expand Down Expand Up @@ -71,7 +76,7 @@ func copyFileOrDirectory(src string, dest string, opts CopyOption) error {
destPath := filepath.Join(dest, relPath)

if srcInfo.IsDir() {
return os.Mkdir(destPath, srcInfo.Mode())
return os.MkdirAll(destPath, srcInfo.Mode())
}

return copyFile(srcPath, destPath, opts)
Expand Down
18 changes: 18 additions & 0 deletions shx/copy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,24 @@ func TestCopy(t *testing.T) {
assertFile(t, filepath.Join(tmp, "a/ab/ab2.txt"))
})

t.Run("recursively copy directory into populated dest dir", func(t *testing.T) {
tmp, err := ioutil.TempDir("", "magex")
require.NoError(t, err, "could not create temp directory for test")
defer os.RemoveAll(tmp)

require.NoError(t, os.MkdirAll(filepath.Join(tmp, "a"), 0755))

err = Copy("testdata/copy/a", tmp, CopyRecursive)
require.NoError(t, err, "Copy into directory with same directory name")

assert.DirExists(t, filepath.Join(tmp, "a"))
assertFile(t, filepath.Join(tmp, "a/a1.txt"))
assertFile(t, filepath.Join(tmp, "a/a2.txt"))
assert.DirExists(t, filepath.Join(tmp, "a/ab"))
assertFile(t, filepath.Join(tmp, "a/ab/ab1.txt"))
assertFile(t, filepath.Join(tmp, "a/ab/ab2.txt"))
})

t.Run("copy glob", func(t *testing.T) {
tmp, err := ioutil.TempDir("", "magex")
require.NoError(t, err, "could not create temp directory for test")
Expand Down

0 comments on commit 5af18d8

Please sign in to comment.