Setters with subpackages

This commit is contained in:
Phani Teja Marupaka
2020-08-27 21:22:43 -07:00
parent 0e9428c8b0
commit f432f4d75e
35 changed files with 795 additions and 210 deletions

View File

@@ -6,23 +6,29 @@ package pathutil
import (
"os"
"path/filepath"
"strings"
)
// SubDirsWithFile takes the root directory path and returns all the paths of
// sub-directories which contain file with input fileName including itself
func SubDirsWithFile(root, fileName string) ([]string, error) {
// DirsWithFile takes the root directory path and returns all the paths of
// sub-directories(including itself) which contain file with input fileName
// at top level if recurse is true
func DirsWithFile(root, fileName string, recurse bool) ([]string, error) {
var res []string
if !recurse {
// check if the file with fileName is present in root and return it
// else return empty list
_, err := os.Stat(filepath.Join(root, fileName))
if !os.IsNotExist(err) {
res = append(res, root)
}
return res, nil
}
err := filepath.Walk(root,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasSuffix(path, fileName) {
if root == "." {
path = root + "/" + path
}
res = append(res, path)
if filepath.Base(path) == fileName {
res = append(res, filepath.Dir(path))
}
return nil
})

View File

@@ -13,6 +13,32 @@ import (
)
func TestSubDirsWithFile(t *testing.T) {
var tests = []struct {
name string
fileName string
recurse bool
outFilesCount int
}{
{
name: "dirs-with-file-recurse",
fileName: "Krmfile",
outFilesCount: 3,
recurse: true,
},
{
name: "dirs-with-non-existent-file-recurse",
fileName: "non-existent-file.txt",
outFilesCount: 0,
recurse: true,
},
{
name: "dir-with-file-no-recurse",
fileName: "Krmfile",
outFilesCount: 1,
recurse: false,
},
}
dir, err := ioutil.TempDir("", "")
if !assert.NoError(t, err) {
t.FailNow()
@@ -23,28 +49,17 @@ func TestSubDirsWithFile(t *testing.T) {
t.FailNow()
}
res, err := SubDirsWithFile(dir, "Krmfile")
if !assert.NoError(t, err) {
t.FailNow()
}
if !assert.Equal(t, 3, len(res)) {
t.FailNow()
}
}
func TestSubDirsWithFileNoMatch(t *testing.T) {
dir, err := ioutil.TempDir("", "")
if !assert.NoError(t, err) {
t.FailNow()
}
defer os.RemoveAll(dir)
res, err := SubDirsWithFile(dir, "non-existent-file.txt")
if !assert.NoError(t, err) {
t.FailNow()
}
var expected []string
if !assert.Equal(t, expected, res) {
t.FailNow()
for i := range tests {
test := tests[i]
t.Run(test.name, func(t *testing.T) {
res, err := DirsWithFile(dir, test.fileName, test.recurse)
if !assert.NoError(t, err) {
t.FailNow()
}
if !assert.Equal(t, test.outFilesCount, len(res)) {
t.FailNow()
}
})
}
}