package gokdkly

import (
	"os"
	"os/exec"
	"strings"
	"syscall"

	"github.com/pkg/errors"
)

// GetRepoRoot returns the path of the root of the repository enclosing the given path.  If the argument is the empty
// string, it uses the current working directory instead.  If the path is not within a repository, it returns the empty
// string.  An error is returned iff invoking 'git' fails for some other reason.
func GetRepoRoot(p string) (string, error) {
	var err error
	if p == "" {
		p, err = os.Getwd()
		if err != nil {
			return "", errors.Wrap(err, "failed to get working directory")
		}
	}

	cmd := exec.Command("git", "rev-parse", "--show-toplevel")
	stdout, err := cmd.Output()
	if err != nil {
		if exitErr, ok := err.(*exec.ExitError); ok {
			exitStatus := exitErr.Sys().(syscall.WaitStatus).ExitStatus()
			if exitStatus == 128 { // not in a repository
				return "", nil
			}
		}
		return "", errors.Wrap(err, "failed to invoke git")
	}
	repoRoot := strings.TrimSpace(string(stdout))
	return repoRoot, nil
}
