Skip to content

Commit

Permalink
Initial import
Browse files Browse the repository at this point in the history
  • Loading branch information
muesli committed Jul 13, 2020
1 parent 65ca3c5 commit 0621bb6
Show file tree
Hide file tree
Showing 2 changed files with 126 additions and 0 deletions.
63 changes: 63 additions & 0 deletions gitcha.go
Original file line number Diff line number Diff line change
@@ -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")
}
63 changes: 63 additions & 0 deletions gitcha_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit 0621bb6

Please sign in to comment.