| 1 |
package url |
| 2 |
|
| 3 |
import ( |
| 4 |
"regexp" |
| 5 |
"runtime" |
| 6 |
"strings" |
| 7 |
) |
| 8 |
|
| 9 |
var ( |
| 10 |
isSchemeRegExp = regexp.MustCompile(`^[^:]+://`) |
| 11 |
|
| 12 |
// Ref: https://github.com/git/git/blob/v2.54.0/Documentation/urls.adoc#L41-L48 |
| 13 |
scpLikeUrlRegExp = regexp.MustCompile(`^(?:(?P<user>[^@]+)@)?(?P<host>[^:\s]+):(?:(?P<port>[0-9]{1,5}):)?(?P<path>[^\\].*)$`) |
| 14 |
) |
| 15 |
|
| 16 |
// MatchesScheme returns true if the given string matches a URL-like |
| 17 |
// format scheme. |
| 18 |
func MatchesScheme(url string) bool { |
| 19 |
return isSchemeRegExp.MatchString(url) |
| 20 |
} |
| 21 |
|
| 22 |
// MatchesScpLike returns true if the given string matches an SCP-like |
| 23 |
// format scheme. |
| 24 |
func MatchesScpLike(url string) bool { |
| 25 |
if !scpLikeUrlRegExp.MatchString(url) { |
| 26 |
return false |
| 27 |
} |
| 28 |
// Mirror canonical Git's url_is_local_not_ssh in connect.c[1] for |
| 29 |
// the cases the regex above cannot disambiguate by itself: a URL |
| 30 |
// is treated as a local path (not SCP-style SSH) when a `/` |
| 31 |
// precedes the first `:` (e.g. `./relative:path`, |
| 32 |
// `/abs/with:colon/file`), or — on Windows only — when it has a |
| 33 |
// DOS drive prefix like `C:foo` where the host is a single |
| 34 |
// ASCII letter. |
| 35 |
// |
| 36 |
// [1]: https://github.com/git/git/blob/v2.54.0/connect.c#L710-L716 |
| 37 |
if before, _, _ := strings.Cut(url, ":"); strings.Contains(before, "/") { |
| 38 |
return false |
| 39 |
} |
| 40 |
if runtime.GOOS == "windows" && hasDosDrivePrefix(url) { |
| 41 |
return false |
| 42 |
} |
| 43 |
return true |
| 44 |
} |
| 45 |
|
| 46 |
// hasDosDrivePrefix reports whether s begins with `<letter>:` (a |
| 47 |
// Windows drive prefix such as `C:` or `c:`). Mirrors canonical Git's |
| 48 |
// win32_has_dos_drive_prefix[1]. |
| 49 |
// |
| 50 |
// [1]: https://github.com/git/git/blob/v2.54.0/compat/win32/path-utils.c#L20-L29 |
| 51 |
func hasDosDrivePrefix(s string) bool { |
| 52 |
if len(s) < 2 || s[1] != ':' { |
| 53 |
return false |
| 54 |
} |
| 55 |
c := s[0] |
| 56 |
return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') |
| 57 |
} |
| 58 |
|
| 59 |
// FindScpLikeComponents returns the user, host, port and path of the |
| 60 |
// given SCP-like URL. |
| 61 |
func FindScpLikeComponents(url string) (user, host, port, path string) { |
| 62 |
m := scpLikeUrlRegExp.FindStringSubmatch(url) |
| 63 |
return m[1], m[2], m[3], m[4] |
| 64 |
} |
| 65 |
|
| 66 |
// IsLocalEndpoint returns true if the given URL string specifies a |
| 67 |
// local file endpoint. For example, on a Linux machine, |
| 68 |
// `/home/user/src/go-git` would match as a local endpoint, but |
| 69 |
// `https://github.com/src-d/go-git` would not. |
| 70 |
func IsLocalEndpoint(url string) bool { |
| 71 |
return !MatchesScheme(url) && !MatchesScpLike(url) |
| 72 |
} |