hako/git.go
2025-06-10 21:39:03 -03:00

68 lines
1.4 KiB
Go

package main
import (
"errors"
"os"
"path/filepath"
"strings"
)
func isGitRepository() bool {
_, err := os.Stat(".git")
return err == nil
}
func getGitRootPath() (string, error) {
output, err := runCommandOutput("git", "rev-parse", "--show-toplevel")
if err != nil {
return "", errors.New("not in a git repository")
}
return strings.TrimSpace(output), nil
}
func getProjectContainerName(lang string) (string, error) {
if !isGitRepository() {
return "", errors.New("must be run inside a git repository")
}
gitRoot, err := getGitRootPath()
if err != nil {
return "", err
}
cwd, err := os.Getwd()
if err != nil {
return "", err
}
relPath, err := filepath.Rel(gitRoot, cwd)
if err != nil {
return "", err
}
projectName := filepath.Base(gitRoot)
var pathComponents []string
if relPath != "." {
pathComponents = strings.Split(relPath, string(os.PathSeparator))
}
containerName := "hako-" + lang + "-" + sanitizeName(projectName)
for _, component := range pathComponents {
containerName += "-" + sanitizeName(component)
}
if len(containerName) > 60 {
return "", errors.New("container name too long, try running from a shallower directory")
}
return containerName, nil
}
func sanitizeName(name string) string {
result := strings.ToLower(name)
result = strings.ReplaceAll(result, " ", "_")
result = strings.ReplaceAll(result, ".", "_")
result = strings.ReplaceAll(result, "-", "_")
return result
}