This repository has been archived by the owner on Jul 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.swift
201 lines (163 loc) · 6.35 KB
/
update.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
import Foundation
// MARK: - Linux
#if canImport(FoundationNetworking)
import FoundationNetworking
extension URLSession {
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
return try await withUnsafeThrowingContinuation { continuation in
let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, let response = response else {
let error = error ?? URLError(.unknown)
continuation.resume(throwing: error)
return
}
continuation.resume(returning: (data, response))
}
dataTask.resume()
}
}
func data(from url: URL) async throws -> (Data, URLResponse) {
return try await withUnsafeThrowingContinuation { continuation in
let dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let response = response else {
let error = error ?? URLError(.unknown)
continuation.resume(throwing: error)
return
}
continuation.resume(returning: (data, response))
}
dataTask.resume()
}
}
}
#endif // canImport(FoundationNetworking)
// MARK: - Models
struct Release: Decodable {
let tagName: String
let body: String
}
struct ReleasePayload: Encodable {
let tagName: String
let name: String
let body: String
}
// MARK: - Errors
enum UpdateError: Error {
case fetchReleases(statusCode: Int)
case createRelease(statusCode: Int)
case packageDotSwift
case noAccessToken
case updatePackageDotSwift(Error)
case pushChanges(Error)
}
// MARK: - Networking
func releases(from url: URL) async throws -> [Release] {
let (data, response) = try await URLSession.shared.data(from: url)
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
throw UpdateError.fetchReleases(statusCode: httpResponse.statusCode)
} else {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let releases = try decoder.decode([Release].self, from: data)
return releases
}
}
func createRelease(accessToken: String, url: URL, payload: ReleasePayload) async throws {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let data = try encoder.encode(payload)
var request = URLRequest(url: url)
request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("token \(accessToken)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = data
let (_, response) = try await URLSession.shared.data(for: request)
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
throw UpdateError.createRelease(statusCode: httpResponse.statusCode)
}
}
func packageDotSwift(from url: URL) async throws -> String {
let (data, _) = try await URLSession.shared.data(from: url)
if let packageDotSwift = String(data: data, encoding: .utf8) {
return packageDotSwift
} else {
throw UpdateError.packageDotSwift
}
}
// MARK: - Shell
func git(_ args: String...) throws {
let process = Process()
let url = URL(fileURLWithPath: "/usr/bin/git")
process.executableURL = url
process.arguments = args
try process.run()
process.waitUntilExit()
}
// MARK: - Helpers
func accessToken() throws -> String {
guard CommandLine.arguments.count > 1 else { throw UpdateError.noAccessToken }
return CommandLine.arguments[1]
}
func updatePackageDotSwift(with newContent: String) throws {
let file = FileManager.default.currentDirectoryPath + "/Package.swift"
do {
try newContent.write(toFile: file, atomically: true, encoding: .utf8)
} catch {
throw UpdateError.updatePackageDotSwift(error)
}
}
func pushChanges(release: Release) throws {
do {
try git("add", ".")
try git("commit", "-m", "Bump to \(release.tagName)")
try git("push")
} catch {
throw UpdateError.pushChanges(error)
}
}
// MARK: - Execution
let executionTask = Task.detached {
guard let intercomReleasesURL = URL(string: "https://api.github.com/repos/intercom/intercom-ios/releases"),
let packageReleasesURL = URL(string: "https://api.github.com/repos/FelixHerrmann/intercom-ios/releases"),
let packageDotSwiftURL = URL(string: "https://raw.githubusercontent.com/intercom/intercom-ios/master/Package.swift") else {
exit(EXIT_FAILURE)
}
let accessToken = try accessToken()
print("Checking and comparing releases ...")
let intercomReleases = try await releases(from: intercomReleasesURL)
let packageReleases = try await releases(from: packageReleasesURL)
guard let intercomLatest = intercomReleases.first, let packageLatest = packageReleases.first else {
print("One of the repositories has no releases")
exit(EXIT_FAILURE)
}
guard intercomLatest.tagName != packageLatest.tagName else {
print("Version \(packageLatest.tagName) is latest")
exit(EXIT_SUCCESS)
}
print("Updating Package.swift ...")
let packageDotSwift = try await packageDotSwift(from: packageDotSwiftURL)
guard packageDotSwift != "" else {
print("New Package.swift not available")
exit(EXIT_FAILURE)
}
try updatePackageDotSwift(with: packageDotSwift)
print("Package.swift updated successfully")
print("Pushing changes to master ...")
try pushChanges(release: intercomLatest)
print("Changes pushed to master successfully")
print("Creating release \(intercomLatest.tagName) ...")
let payload = ReleasePayload(tagName: intercomLatest.tagName, name: intercomLatest.tagName, body: intercomLatest.body)
try await createRelease(accessToken: accessToken, url: packageReleasesURL, payload: payload)
print("Release \(intercomLatest.tagName) created successfully")
}
Task {
do {
_ = try await executionTask.value
exit(EXIT_SUCCESS)
} catch {
print("Error:", error)
exit(EXIT_FAILURE)
}
}
RunLoop.current.run()