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