diff --git a/gitcha.go b/gitcha.go new file mode 100644 index 0000000..f6a7d4d --- /dev/null +++ b/gitcha.go @@ -0,0 +1,63 @@ +package gitcha + +import ( + "errors" + "os" + "path/filepath" + "strings" +) + +func IsPathInGit(path string) (bool, error) { + absPath, err := filepath.Abs(path) + if err != nil { + return false, err + } + + for { + dir := filepath.Dir(absPath) + + st, err := os.Stat(filepath.Join(dir, ".git")) + if err == nil && st.IsDir() { + return true, nil + } + + if dir == absPath { + // reached root + return false, nil + } + absPath = dir + } +} + +func FindFirstInList(path string, list []string) (string, error) { + path, err := filepath.Abs(path) + if err != nil { + return "", err + } + st, err := os.Stat(path) + if err != nil { + return "", err + } + if !st.IsDir() { + return "", errors.New("not a directory") + } + + var res string + _ = filepath.Walk(path, func(path string, info os.FileInfo, err error) error { + for _, v := range list { + if strings.EqualFold(filepath.Base(path), v) { + res, _ = filepath.Abs(path) + + // abort filepath.Walk + return errors.New("source found") + } + } + return nil + }) + + if res != "" { + return res, nil + } + + return "", errors.New("none found") +} diff --git a/gitcha_test.go b/gitcha_test.go new file mode 100644 index 0000000..bb2e6d3 --- /dev/null +++ b/gitcha_test.go @@ -0,0 +1,63 @@ +package gitcha + +import ( + "path/filepath" + "testing" +) + +func TestIsPathInGit(t *testing.T) { + tt := []struct { + path string + exp bool + }{ + {"/", false}, + {".", false}, + {"gitcha.go", true}, + } + + for _, test := range tt { + r, err := IsPathInGit(test.path) + if err != nil { + t.Error(err) + } + + if test.exp != r { + t.Errorf("Expected %v, got %v for %s", test.exp, r, test.path) + } + } +} + +func TestFindFirstInList(t *testing.T) { + tt := []struct { + path string + list []string + exp string + expErr bool + }{ + {"../", []string{"gitcha.go"}, "gitcha.go", false}, + {".", []string{"gitcha_test.go"}, "gitcha_test.go", false}, + {".", []string{"exist.not"}, "", true}, + } + + for _, test := range tt { + r, err := FindFirstInList(test.path, test.list) + if err != nil && !test.expErr { + t.Error(err) + } + if err == nil && test.expErr { + t.Errorf("Expected error, got none for %s", test.path) + } + + if err != nil && test.expErr { + continue + } + + test.exp, err = filepath.Abs(test.exp) + if err != nil { + t.Fatal(err) + } + if test.exp != r { + t.Errorf("Expected %v, got %v for %s", test.exp, r, test.path) + } + } +}