package gitpb import ( "fmt" "net/url" "regexp" "strings" ) // scpLikeURLRegex is a regex to parse scp-like URLs, e.g., "git@github.com:user/repo.git". // It captures the user, host, and path. var scpLikeURLRegex = regexp.MustCompile(`^([^@]+)@([^:]+):(.+)$`) // ParseGitURL parses a Git URL, handling both standard schemes (http, https, ssh) // and the scp-like syntax (e.g., git@github.com:user/repo.git). func ParseGitURL(rawURL string) (*url.URL, error) { // First, try to parse it as a standard URL. // This will handle http://, https://, ssh://, git://, etc. parsedURL, err := url.Parse(rawURL) if err == nil && parsedURL.Scheme != "" { return parsedURL, nil } // If parsing failed or the scheme is missing, it might be an scp-like URL. // Try to match it against our regex. matches := scpLikeURLRegex.FindStringSubmatch(rawURL) if len(matches) != 4 { // If it doesn't match, we return the original parsing error or a new one. if err != nil { return nil, err } return nil, fmt.Errorf("invalid or unsupported URL format: %s", rawURL) } // If it matches, we manually construct a url.URL struct. // We'll use the "ssh" scheme to represent this connection type. user := matches[1] host := matches[2] path := matches[3] // The path might have a ".git" suffix, which we can optionally remove. path = strings.TrimSuffix(path, ".git") return &url.URL{ Scheme: "ssh", User: url.User(user), Host: host, Path: "/" + path, // Standard URL paths start with a slash. }, nil } /* func parsemain() { urlsToTest := []string{ // The problematic scp-like syntax "git@git.wit.com:jcarr/jcarr.git", // A standard HTTPS URL "https://gitea.wit.com/wit/bash.git", // A standard SSH URL "ssh://git@github.com/golang/go.git", // An invalid URL "this is not a url", } for _, u := range urlsToTest { fmt.Printf("Parsing URL: %s\n", u) parsed, err := ParseGitURL(u) if err != nil { fmt.Printf(" Error: %v\n\n", err) continue } fmt.Printf(" Scheme: %s\n", parsed.Scheme) fmt.Printf(" User: %s\n", parsed.User.Username()) fmt.Printf(" Host: %s\n", parsed.Host) fmt.Printf(" Path: %s\n\n", parsed.Path) } } */