code.oscarkilo.com/klex-git/util/root_test.go

..
commit.go
commit_test.go
committest/
files.go
files_test.go
paths.go
paths_test.go
root.go
root_test.go
run.go
run_test.go
package util

import (
  "os"
  "path"
  "testing"
)

// build creates a directory tree structure.
func build(root string, paths []string) {
  for _, p := range paths {
    if p[len(p)-1] == '/' {
      os.MkdirAll(path.Join(root, p), 0755)
    } else {
      os.Create(path.Join(root, p))
    }
  }
}

func TestFindRoot(t *testing.T) {
  tmp_dir := t.TempDir()

  test := func(cwd, expected_root string) {
    os.Chdir(path.Join(tmp_dir, cwd))
    root, err := FindRoot()
    if err == nil {
      root = root[len(tmp_dir)+1:]
    }
    if expected_root == "" && err == nil {
      t.Errorf("FindRoot(%s) returned %s; want error", cwd, root)
    } else if expected_root != "" && err != nil {
      t.Errorf("FindRoot(%s) returned error %v; want %s", cwd, err, expected_root)
    } else if root != expected_root {
      t.Errorf("FindRoot(%s) returned %s; want %s", cwd, root, expected_root)
    }
  }

  build(tmp_dir, []string{
    "foo/.git/",
    "foo/bar/.git/",
    "baz/",
    "qux/.git",
  })

  test("foo", "foo")          // foo is a Git repo
  test("foo/bar", "foo/bar")  // foo/bar is a Git repo inside a Git repo
  test("baz", "")             // baz is just an emtpy directory
  test("qux", "")             // qux is not a Git repo because .git is not a directory
}