code.oscarkilo.com/klex-git/util/root.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 (
  "fmt"
  "os"
  "path"
)

// FindRoot finds the Git repo root directory.
func FindRoot() (string, error) {
  dir, err := os.Getwd()
  if err != nil {
    return "", err
  }
  for dir != "/" {
    if s, err := os.Stat(path.Join(dir, ".git")); err == nil && s.IsDir() {
      return dir, nil
    }
    dir = path.Dir(dir)
  }
  return "", fmt.Errorf("We are not in a Git repository")
}

// CdRoot change the current working directory to the Git repo root.
func CdRoot() error {
  root, err := FindRoot()
  if err != nil {
    return err
  }
  return os.Chdir(root)
}