From e646c9daef1ba0d3656341af0aa48569dddb7ec9 Mon Sep 17 00:00:00 2001 From: Vincent Batts Date: Sun, 29 Jan 2017 15:50:51 -0500 Subject: [PATCH] util: file path finder Convenience to walk a directory tree looking for a file like "ChangeLog.txt" Signed-off-by: Vincent Batts --- util/find.go | 23 +++++++++++++++++++++++ util/find_test.go | 14 ++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 util/find.go create mode 100644 util/find_test.go diff --git a/util/find.go b/util/find.go new file mode 100644 index 0000000..025d4c0 --- /dev/null +++ b/util/find.go @@ -0,0 +1,23 @@ +package util + +import ( + "os" + "path/filepath" +) + +func FindFiles(root, name string) (paths []string, err error) { + paths = []string{} + err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if filepath.Base(path) == name { + paths = append(paths, path) + } + return nil + }) + if err != nil { + return nil, err + } + return paths, nil +} diff --git a/util/find_test.go b/util/find_test.go new file mode 100644 index 0000000..b75103c --- /dev/null +++ b/util/find_test.go @@ -0,0 +1,14 @@ +package util + +import "testing" + +func TestFind(t *testing.T) { + paths, err := FindFiles("../changelog", "ChangeLog.txt") + if err != nil { + t.Fatal(err) + } + + if len(paths) != 1 { + t.Errorf("expected to find %d file, but found %d", 1, len(paths)) + } +}