// Package forgekey owns repository keys. Recognising a host is not permission // to execute work there; callers retain their forge admission policy. package forgekey import ( "errors" "regexp" "strings" ) const ( Hub = "amadan.net" GitHub = "github.com" ) var ErrKey = errors.New("invalid repository key") var segment = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`) var newName = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]{1,38}$`) // Key preserves the forge's spelling. Use Equal for identity comparisons. type Key struct{ Host, Owner, Name string } func KnownHost(host string) bool { return host == Hub || host == GitHub } func (k Key) String() string { return k.Host + "/" + k.Owner + "/" + k.Name } // Parse accepts a key, or a bare owner/name for the hub. URLs are not keys. func Parse(raw string) (Key, error) { parts := strings.Split(raw, "/") if len(parts) == 2 { if KnownHost(parts[0]) { return Key{}, ErrKey } parts = append([]string{Hub}, parts...) } if len(parts) != 3 || !KnownHost(parts[0]) { return Key{}, ErrKey } for _, p := range parts[1:] { if !segment.MatchString(p) || p == "." || p == ".." { return Key{}, ErrKey } } return Key{Host: parts[0], Owner: parts[1], Name: parts[2]}, nil } func Equal(a, b string) bool { ka, ea := Parse(a) kb, eb := Parse(b) if ea != nil || eb != nil || ka.Host != kb.Host { return false } if ka.Host == GitHub { return strings.EqualFold(ka.String(), kb.String()) } return ka == kb } // Display keeps the host on non-hub keys so names cannot hide their forge. func Display(raw string) string { return strings.TrimPrefix(raw, Hub+"/") } // Normalize accepts the person-facing HTTPS and .git spellings. Validation // remains explicit at the caller's admission boundary. func Normalize(raw string) string { r := strings.TrimSpace(raw) r = strings.TrimPrefix(r, "https://") r = strings.TrimSuffix(strings.TrimSuffix(r, "/"), ".git") if !strings.HasPrefix(r, Hub+"/") && !strings.HasPrefix(r, GitHub+"/") { r = Hub + "/" + r } return r } // ValidHub preserves the hub's historical key regexp. Parse additionally // rejects dot path segments where a canonical path is required. func ValidHub(raw string) bool { parts := strings.Split(raw, "/") return len(parts) == 3 && parts[0] == Hub && segment.MatchString(parts[1]) && segment.MatchString(parts[2]) } func NewHubRepo(raw string) bool { parts := strings.Split(raw, "/") return ValidHub(raw) && newName.MatchString(parts[2]) } // HasHubPrefix preserves legacy prefix-only checks. Canonical admission uses Parse. func HasHubPrefix(raw string) bool { return strings.HasPrefix(raw, Hub+"/") } // HubBranchURL preserves the hub's existing branch-link spelling. // Callers validate the repository and branch at their admission boundary. func HubBranchURL(repo, branch string) string { return "https://" + repo + "?branch=" + branch }