forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cartfile.swift
217 lines (182 loc) · 7.33 KB
/
Cartfile.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import Foundation
import Result
/// The relative path to a project's checked out dependencies.
public let carthageProjectCheckoutsPath = "Carthage/Checkouts"
/// Represents a Cartfile, which is a specification of a project's dependencies
/// and any other settings Carthage needs to build it.
public struct Cartfile {
/// Any text following this character is considered a comment
static let commentIndicator = "#"
/// The dependencies listed in the Cartfile.
public var dependencies: [Dependency: VersionSpecifier]
public init(dependencies: [Dependency: VersionSpecifier] = [:]) {
self.dependencies = dependencies
}
/// Returns the location where Cartfile should exist within the given
/// directory.
public static func url(in directoryURL: URL) -> URL {
return directoryURL.appendingPathComponent("Cartfile")
}
/// Attempts to parse Cartfile information from a string.
public static func from(string: String) -> Result<Cartfile, CarthageError> {
var dependencies: [Dependency: VersionSpecifier] = [:]
var duplicates: [Dependency] = []
var result: Result<(), CarthageError> = .success(())
string.enumerateLines { line, stop in
let scannerWithComments = Scanner(string: line)
if scannerWithComments.scanString(Cartfile.commentIndicator, into: nil) {
// Skip the rest of the line.
return
}
if scannerWithComments.isAtEnd {
// The line was all whitespace.
return
}
guard let remainingString = scannerWithComments.remainingSubstring.map(String.init) else {
result = .failure(CarthageError.internalError(
description: "Can NSScanner split an extended grapheme cluster? If it does, this will be the error…"
))
stop = true
return
}
let scannerWithoutComments = Scanner(
string: remainingString.strippingTrailingCartfileComment
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
)
switch Dependency.from(scannerWithoutComments).fanout(VersionSpecifier.from(scannerWithoutComments)) {
case let .success((dependency, version)):
if case .binary = dependency, case .gitReference = version {
result = .failure(
CarthageError.parseError(
description: "binary dependencies cannot have a git reference for the version specifier in line: \(scannerWithComments.currentLine)"
)
)
stop = true
return
}
if dependencies[dependency] == nil {
dependencies[dependency] = version
} else {
duplicates.append(dependency)
}
case let .failure(error):
result = .failure(CarthageError(scannableError: error))
stop = true
return
}
if !scannerWithoutComments.isAtEnd {
result = .failure(CarthageError.parseError(description: "unexpected trailing characters in line: \(line)"))
stop = true
}
}
return result.flatMap { _ in
if !duplicates.isEmpty {
return .failure(.duplicateDependencies(duplicates.map { DuplicateDependency(dependency: $0, locations: []) }))
}
return .success(Cartfile(dependencies: dependencies))
}
}
/// Attempts to parse a Cartfile from a file at a given URL.
public static func from(file cartfileURL: URL) -> Result<Cartfile, CarthageError> {
return Result(catching: { try String(contentsOf: cartfileURL, encoding: .utf8) })
.mapError { .readFailed(cartfileURL, $0) }
.flatMap(Cartfile.from(string:))
.mapError { error in
guard case let .duplicateDependencies(dupes) = error else { return error }
let dependencies = dupes
.map { dupe in
return DuplicateDependency(
dependency: dupe.dependency,
locations: [ cartfileURL.path ]
)
}
return .duplicateDependencies(dependencies)
}
}
/// Appends the contents of another Cartfile to that of the receiver.
public mutating func append(_ cartfile: Cartfile) {
for (dependency, version) in cartfile.dependencies {
dependencies[dependency] = version
}
}
}
/// Returns an array containing dependencies that are listed in both arguments.
public func duplicateDependenciesIn(_ cartfile1: Cartfile, _ cartfile2: Cartfile) -> [Dependency] {
let projects1 = cartfile1.dependencies.keys
let projects2 = cartfile2.dependencies.keys
return Array(Set(projects1).intersection(Set(projects2)))
}
/// Represents a parsed Cartfile.resolved, which specifies which exact version was
/// checked out for each dependency.
public struct ResolvedCartfile {
/// The dependencies listed in the Cartfile.resolved.
public var dependencies: [Dependency: PinnedVersion]
public init(dependencies: [Dependency: PinnedVersion]) {
self.dependencies = dependencies
}
/// Returns the location where Cartfile.resolved should exist within the given
/// directory.
public static func url(in directoryURL: URL) -> URL {
return directoryURL.appendingPathComponent("Cartfile.resolved")
}
/// Attempts to parse Cartfile.resolved information from a string.
public static func from(string: String) -> Result<ResolvedCartfile, CarthageError> {
var cartfile = self.init(dependencies: [:])
var result: Result<(), CarthageError> = .success(())
let scanner = Scanner(string: string)
scannerLoop: while !scanner.isAtEnd {
switch Dependency.from(scanner).fanout(PinnedVersion.from(scanner)) {
case let .success((dep, version)):
cartfile.dependencies[dep] = version
case let .failure(error):
result = .failure(CarthageError(scannableError: error))
break scannerLoop
}
}
return result.map { _ in cartfile }
}
}
extension ResolvedCartfile: CustomStringConvertible {
public var description: String {
return dependencies
.sorted { $0.key.description < $1.key.description }
.map { "\($0.key) \($0.value)\n" }
.joined(separator: "")
}
}
extension String {
/// Returns self without any potential trailing Cartfile comment. A Cartfile
/// comment starts with the first `commentIndicator` that is not embedded in any quote
var strippingTrailingCartfileComment: String {
// Since the Cartfile syntax doesn't support nested quotes, such as `"version-\"alpha\""`,
// simply consider any odd-number occurence of a quote as a quote-start, and any
// even-numbered occurrence of a quote as quote-end.
// The comment indicator (e.g. `#`) is the start of a comment if it's not nested in quotes.
// The following code works also for comment indicators that are are more than one character
// long (e.g. double slashes).
let quote = "\""
// Splitting the string by quote will make odd-numbered chunks outside of quotes, and
// even-numbered chunks inside of quotes.
// `omittingEmptySubsequences` is needed to maintain this property even in case of empty quotes.
let quoteDelimitedChunks = self.split(
separator: quote.first!,
maxSplits: Int.max,
omittingEmptySubsequences: false
)
for (offset, chunk) in quoteDelimitedChunks.enumerated() {
let isInQuote = offset % 2 == 1 // even chunks are not in quotes, see comment above
if isInQuote {
continue // don't consider comment indicators inside quotes
}
if let range = chunk.range(of: Cartfile.commentIndicator) {
// there is a comment, return everything before its position
let advancedOffset = (..<offset).relative(to: quoteDelimitedChunks)
let previousChunks = quoteDelimitedChunks[advancedOffset]
let chunkBeforeComment = chunk[..<range.lowerBound]
return (previousChunks + [chunkBeforeComment])
.joined(separator: quote) // readd the quotes that were removed in the initial split
}
}
return self
}
}