utils.go

 1package utils
 2
 3import (
 4	"fmt"
 5	"path/filepath"
 6	"strings"
 7	"unicode"
 8)
 9
10// SanitizeRepo returns a sanitized version of the given repository name.
11func SanitizeRepo(repo string) string {
12	repo = strings.TrimPrefix(repo, "/")
13	repo = filepath.Clean(repo)
14	repo = strings.TrimSuffix(repo, ".git")
15	return repo
16}
17
18// RepoPath returns the path to the repository.
19func RepoPath(dataPath, repo string) string {
20	repo = SanitizeRepo(repo) + ".git"
21	repo = strings.ReplaceAll(repo, "/", string(filepath.Separator))
22	return filepath.Join(dataPath, repo)
23}
24
25// ValidateUsername returns an error if any of the given usernames are invalid.
26func ValidateUsername(username string) error {
27	if username == "" {
28		return fmt.Errorf("username cannot be empty")
29	}
30
31	if !unicode.IsLetter(rune(username[0])) {
32		return fmt.Errorf("username must start with a letter")
33	}
34
35	for _, r := range username {
36		if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '-' {
37			return fmt.Errorf("username can only contain letters, numbers, and hyphens")
38		}
39	}
40
41	return nil
42}
43
44// ValidateRepo returns an error if the given repository name is invalid.
45func ValidateRepo(repo string) error {
46	if repo == "" {
47		return fmt.Errorf("repo cannot be empty")
48	}
49
50	for _, r := range repo {
51		if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '-' && r != '_' && r != '.' && r != '/' {
52			return fmt.Errorf("repo can only contain letters, numbers, hyphens, underscores, periods, and slashes")
53		}
54	}
55
56	return nil
57}