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