Sort correctly also subfolders

This commit is contained in:
Ettore Di Giacinto
2020-12-05 23:16:16 +01:00
parent 6d19f8d2cc
commit 18e6e085d5
2 changed files with 33 additions and 2 deletions

View File

@@ -19,6 +19,8 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"strings"
"time" "time"
copy "github.com/otiai10/copy" copy "github.com/otiai10/copy"
@@ -41,6 +43,8 @@ func OrderFiles(target string, files []string) ([]string, []string) {
} }
} }
dirs := []string{}
for _, f := range files { for _, f := range files {
target := filepath.Join(target, f) target := filepath.Join(target, f)
fi, err := os.Lstat(target) fi, err := os.Lstat(target)
@@ -48,11 +52,16 @@ func OrderFiles(target string, files []string) ([]string, []string) {
continue continue
} }
if m := fi.Mode(); m.IsDir() { 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) { func ListDir(dir string) ([]string, error) {

View File

@@ -60,5 +60,27 @@ var _ = Describe("Helpers", func() {
Expect(ordered).To(Equal([]string{"baz", "bar/foo", "foo", "baz2/foo", "bar", "baz2"})) Expect(ordered).To(Equal([]string{"baz", "bar/foo", "foo", "baz2/foo", "bar", "baz2"}))
Expect(notExisting).To(Equal([]string{"notexisting"})) 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"}))
})
}) })
}) })