diff --git a/pkg/helpers/file.go b/pkg/helpers/file.go index 1d4a268f..6aa7f3d0 100644 --- a/pkg/helpers/file.go +++ b/pkg/helpers/file.go @@ -19,6 +19,8 @@ import ( "io/ioutil" "os" "path/filepath" + "sort" + "strings" "time" copy "github.com/otiai10/copy" @@ -41,6 +43,8 @@ func OrderFiles(target string, files []string) ([]string, []string) { } } + dirs := []string{} + for _, f := range files { target := filepath.Join(target, f) fi, err := os.Lstat(target) @@ -48,11 +52,16 @@ func OrderFiles(target string, files []string) ([]string, []string) { continue } if m := fi.Mode(); m.IsDir() { - newFiles = append(newFiles, f) + dirs = append(dirs, f) } } - return newFiles, notPresent + // Compare how many sub paths there are, and push at the end the ones that have less subpaths + sort.Slice(dirs, func(i, j int) bool { + return len(strings.Split(dirs[i], string(os.PathSeparator))) > len(strings.Split(dirs[j], string(os.PathSeparator))) + }) + + return append(newFiles, dirs...), notPresent } func ListDir(dir string) ([]string, error) { diff --git a/pkg/helpers/file_test.go b/pkg/helpers/file_test.go index a691a387..e8d08aef 100644 --- a/pkg/helpers/file_test.go +++ b/pkg/helpers/file_test.go @@ -60,5 +60,27 @@ var _ = Describe("Helpers", func() { Expect(ordered).To(Equal([]string{"baz", "bar/foo", "foo", "baz2/foo", "bar", "baz2"})) Expect(notExisting).To(Equal([]string{"notexisting"})) }) + + It("orders correctly when there are folders with folders", func() { + testDir, err := ioutil.TempDir(os.TempDir(), "test") + Expect(err).ToNot(HaveOccurred()) + defer os.RemoveAll(testDir) + + err = os.MkdirAll(filepath.Join(testDir, "bar"), os.ModePerm) + Expect(err).ToNot(HaveOccurred()) + err = os.MkdirAll(filepath.Join(testDir, "foo"), os.ModePerm) + Expect(err).ToNot(HaveOccurred()) + + err = os.MkdirAll(filepath.Join(testDir, "foo", "bar"), os.ModePerm) + Expect(err).ToNot(HaveOccurred()) + + err = os.MkdirAll(filepath.Join(testDir, "foo", "baz"), os.ModePerm) + Expect(err).ToNot(HaveOccurred()) + err = os.MkdirAll(filepath.Join(testDir, "foo", "baz", "fa"), os.ModePerm) + Expect(err).ToNot(HaveOccurred()) + + ordered, _ := OrderFiles(testDir, []string{"foo", "foo/bar", "bar", "foo/baz/fa", "foo/baz"}) + Expect(ordered).To(Equal([]string{"foo/baz/fa", "foo/bar", "foo/baz", "foo", "bar"})) + }) }) })