github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/git/url.go (about)

     1  package git
     2  
     3  import (
     4  	"net/url"
     5  	"strings"
     6  )
     7  
     8  func IsURL(u string) bool {
     9  	return strings.HasPrefix(u, "git@") || isSupportedProtocol(u)
    10  }
    11  
    12  func isSupportedProtocol(u string) bool {
    13  	return strings.HasPrefix(u, "ssh:") ||
    14  		strings.HasPrefix(u, "git+ssh:") ||
    15  		strings.HasPrefix(u, "git:") ||
    16  		strings.HasPrefix(u, "http:") ||
    17  		strings.HasPrefix(u, "git+https:") ||
    18  		strings.HasPrefix(u, "https:")
    19  }
    20  
    21  func isPossibleProtocol(u string) bool {
    22  	return isSupportedProtocol(u) ||
    23  		strings.HasPrefix(u, "ftp:") ||
    24  		strings.HasPrefix(u, "ftps:") ||
    25  		strings.HasPrefix(u, "file:")
    26  }
    27  
    28  // ParseURL normalizes git remote urls
    29  func ParseURL(rawURL string) (u *url.URL, err error) {
    30  	if !isPossibleProtocol(rawURL) &&
    31  		strings.ContainsRune(rawURL, ':') &&
    32  		// not a Windows path
    33  		!strings.ContainsRune(rawURL, '\\') {
    34  		// support scp-like syntax for ssh protocol
    35  		rawURL = "ssh://" + strings.Replace(rawURL, ":", "/", 1)
    36  	}
    37  
    38  	u, err = url.Parse(rawURL)
    39  	if err != nil {
    40  		return
    41  	}
    42  
    43  	if u.Scheme == "git+ssh" {
    44  		u.Scheme = "ssh"
    45  	}
    46  
    47  	if u.Scheme == "git+https" {
    48  		u.Scheme = "https"
    49  	}
    50  
    51  	if u.Scheme != "ssh" {
    52  		return
    53  	}
    54  
    55  	if strings.HasPrefix(u.Path, "//") {
    56  		u.Path = strings.TrimPrefix(u.Path, "/")
    57  	}
    58  
    59  	if idx := strings.Index(u.Host, ":"); idx >= 0 {
    60  		u.Host = u.Host[0:idx]
    61  	}
    62  
    63  	return
    64  }