forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GitURL.swift
79 lines (67 loc) · 2.21 KB
/
GitURL.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import Foundation
/// Represents a URL for a Git remote.
public struct GitURL {
/// The string representation of the URL.
public let urlString: String
/// A normalized URL string, without protocol, authentication, or port
/// information. This is mostly useful for comparison, and not for any
/// actual Git operations.
internal var normalizedURLString: String {
if let parsedURL = URL(string: urlString), let host = parsedURL.host {
// Normal, valid URL.
let path = strippingGitSuffix(parsedURL.path)
return "\(host)\(path)"
} else if urlString.hasPrefix("/") // "/path/to/..."
|| urlString.hasPrefix(".") // "./path/to/...", "../path/to/..."
|| urlString.hasPrefix("~") // "~/path/to/..."
|| !urlString.contains(":") // "path/to/..." with avoiding "git@github.com:owner/name"
{
// Local path.
return strippingGitSuffix(urlString)
} else {
// scp syntax.
var strippedURLString = urlString
if let index = strippedURLString.index(of: "@") {
strippedURLString.removeSubrange(strippedURLString.startIndex...index)
}
var host = ""
if let index = strippedURLString.index(of: ":") {
host = String(strippedURLString[strippedURLString.startIndex..<index])
strippedURLString.removeSubrange(strippedURLString.startIndex...index)
}
var path = strippingGitSuffix(strippedURLString)
if !path.hasPrefix("/") {
// This probably isn't strictly legit, but we'll have a forward
// slash for other URL types.
path.insert("/", at: path.startIndex)
}
return "\(host)\(path)"
}
}
/// The name of the repository, if it can be inferred from the URL.
public var name: String? {
let components = urlString.split(omittingEmptySubsequences: true) { $0 == "/" }
return components
.last
.map(String.init)
.map(strippingGitSuffix)
}
public init(_ urlString: String) {
self.urlString = urlString
}
}
extension GitURL: Equatable {
public static func == (_ lhs: GitURL, _ rhs: GitURL) -> Bool {
return lhs.normalizedURLString == rhs.normalizedURLString
}
}
extension GitURL: Hashable {
public var hashValue: Int {
return normalizedURLString.hashValue
}
}
extension GitURL: CustomStringConvertible {
public var description: String {
return urlString
}
}