utils.go

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