package git

import (
	"fmt"
	"path/filepath"
	"strings"
)

func isUnderWorkspace(workspace, dir string) (bool, error) {
	workspace = filepath.Clean(workspace)
	dir = filepath.Clean(dir)

	rel, err := filepath.Rel(workspace, dir)
	if err != nil {
		return false, err
	}
	if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
		return false, nil
	}
	return true, nil
}

// EnsureUnderWorkspace verifies dir is within workspace.
func EnsureUnderWorkspace(workspace, dir string) error {
	ok, err := isUnderWorkspace(workspace, dir)
	if err != nil {
		return err
	}
	if !ok {
		return fmt.Errorf("path %q is outside workspace %q", dir, workspace)
	}
	return nil
}
