-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathDownloadFirmwareCommand.swift
More file actions
359 lines (301 loc) · 16.5 KB
/
DownloadFirmwareCommand.swift
File metadata and controls
359 lines (301 loc) · 16.5 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
//
// DownloadFirmwareCommand.swift
// Mist
//
// Created by Nindi Gill on 30/5/2022.
//
import ArgumentParser
import Foundation
/// Struct used to perform **Download Firmware** operations.
struct DownloadFirmwareCommand: ParsableCommand {
static var configuration: CommandConfiguration = .init(
commandName: "firmware",
abstract: """
Download a macOS Firmware.
* macOS Firmwares are for Apple Silicon Macs only.
"""
)
@OptionGroup var options: DownloadFirmwareOptions
/// Searches for and downloads a particular macOS version.
///
/// - Parameters:
/// - options: Download options for macOS Firmwares.
///
/// - Throws: A `MistError` if a macOS version fails to download.
static func run(options: DownloadFirmwareOptions) throws {
!options.quiet ? Mist.checkForNewVersion(noAnsi: options.noAnsi) : Mist.noop()
try inputValidation(options)
!options.quiet ? PrettyPrint.printHeader("SEARCH", noAnsi: options.noAnsi) : Mist.noop()
!options.quiet ? PrettyPrint.print("Searching for macOS download '\(options.searchString)'...", noAnsi: options.noAnsi) : Mist.noop()
guard
let firmware: Firmware = HTTP.firmware(
from: HTTP.retrieveFirmwares(includeBetas: options.includeBetas, compatible: options.compatible, metadataCachePath: options.metadataCachePath, noAnsi: options.noAnsi),
searchString: options.searchString
) else {
!options.quiet ? PrettyPrint.print("No macOS Firmware found with '\(options.searchString)', exiting...", noAnsi: options.noAnsi, prefix: .ending) : Mist.noop()
return
}
!options.quiet ? PrettyPrint.print("Found \(firmware.name) \(firmware.version) (\(firmware.build)) [\(firmware.dateDescription)]", noAnsi: options.noAnsi) : Mist.noop()
try verifyExistingFiles(firmware, options: options)
try setup(firmware, options: options)
try verifyFreeSpace(firmware, options: options)
try Downloader().download(firmware, options: options)
try Generator.generate(firmware, options: options)
try teardown(firmware, options: options)
try export(firmware, options: options)
}
/// Performs a series of validations on input data, throwing an error if the input data is invalid.
///
/// - Parameters:
/// - options: Download options for macOS Firmwares.
///
/// - Throws: A `MistError` if any of the input validations fail.
private static func inputValidation(_ options: DownloadFirmwareOptions) throws {
!options.quiet ? PrettyPrint.printHeader("INPUT VALIDATION", noAnsi: options.noAnsi) : Mist.noop()
guard !options.searchString.isEmpty else {
throw MistError.missingDownloadSearchString
}
!options.quiet ? PrettyPrint.print("Download search string will be '\(options.searchString)'...", noAnsi: options.noAnsi) : Mist.noop()
guard !options.outputDirectory.isEmpty else {
throw MistError.missingOutputDirectory
}
!options.quiet ? PrettyPrint.print("Include betas in search results will be '\(options.includeBetas)'...", noAnsi: options.noAnsi) : Mist.noop()
!options.quiet ? PrettyPrint.print("Only include compatible firmwares will be '\(options.compatible)'...", noAnsi: options.noAnsi) : Mist.noop()
!options.quiet ? PrettyPrint.print("Cache downloads will be '\(options.cacheDownloads)'...", noAnsi: options.noAnsi) : Mist.noop()
!options.quiet ? PrettyPrint.print("Output directory will be '\(options.outputDirectory)'...", noAnsi: options.noAnsi) : Mist.noop()
!options.quiet ? PrettyPrint.print("Temporary directory will be '\(options.temporaryDirectory)'...", noAnsi: options.noAnsi) : Mist.noop()
if let cachingServer: String = options.cachingServer {
guard let url: URL = URL(string: cachingServer) else {
throw MistError.invalidURL(cachingServer)
}
guard
let scheme: String = url.scheme,
scheme == "http" else {
throw MistError.invalidCachingServerProtocol(url)
}
!options.quiet ? PrettyPrint.print("Content Caching Server URL will be '\(url.absoluteString)'...", noAnsi: options.noAnsi) : Mist.noop()
}
let string: String = "Force flag\(options.force ? " " : " has not been ")set, existing files will\(options.force ? " " : " not ")be overwritten..."
!options.quiet ? PrettyPrint.print(string, noAnsi: options.noAnsi) : Mist.noop()
if let path: String = options.exportPath {
guard !path.isEmpty else {
throw MistError.missingExportPath
}
!options.quiet ? PrettyPrint.print("Export path will be '\(path)'...", noAnsi: options.noAnsi) : Mist.noop()
let url: URL = .init(fileURLWithPath: path)
guard ["json", "plist", "yaml"].contains(url.pathExtension) else {
throw MistError.invalidExportFileExtension
}
!options.quiet ? PrettyPrint.print("Export path file extension is valid...", noAnsi: options.noAnsi) : Mist.noop()
}
guard !options.metadataCachePath.isEmpty else {
throw MistError.missingFirmwareMetadataCachePath
}
!options.quiet ? PrettyPrint.print("macOS Firmware metadata cache path will be '\(options.metadataCachePath)'...", noAnsi: options.noAnsi) : Mist.noop()
try inputValidationFirmware(options)
}
/// Performs a series of input validations specific to macOS Firmware output.
///
/// - Parameters:
/// - options: Download options for macOS Firmwares.
///
/// - Throws: A `MistError` if any of the input validations fail.
private static func inputValidationFirmware(_ options: DownloadFirmwareOptions) throws {
guard !options.firmwareName.isEmpty else {
throw MistError.missingFirmwareName
}
!options.quiet ? PrettyPrint.print("Firmware name will be '\(options.firmwareName)'...", noAnsi: options.noAnsi) : Mist.noop()
}
/// Verifies if macOS Firmware files already exist.
///
/// - Parameters:
/// - firmware: The selected macOS Firmware to be downloaded.
/// - options: Download options for macOS Firmwares.
///
/// - Throws: A `MistError` if an existing file is found.
private static func verifyExistingFiles(_ firmware: Firmware, options: DownloadFirmwareOptions) throws {
guard !options.force else {
return
}
let path: String = firmwarePath(for: firmware, options: options)
guard !FileManager.default.fileExists(atPath: path) else {
throw MistError.existingFile(path: path)
}
}
/// Sets up directory structure for macOS Firmware downloads.
///
/// - Parameters:
/// - firmware: The selected macOS Firmware to be downloaded.
/// - options: Download options for macOS Firmwares.
///
/// - Throws: An `Error` if any of the directory operations fail.
private static func setup(_ firmware: Firmware, options: DownloadFirmwareOptions) throws {
let outputURL: URL = .init(fileURLWithPath: outputDirectory(for: firmware, options: options))
let temporaryURL: URL = .init(fileURLWithPath: temporaryDirectory(for: firmware, options: options))
var processing: Bool = false
!options.quiet ? PrettyPrint.printHeader("SETUP", noAnsi: options.noAnsi) : Mist.noop()
if !FileManager.default.fileExists(atPath: outputURL.path) {
!options.quiet ? PrettyPrint.print("Creating output directory '\(outputURL.path)'...", noAnsi: options.noAnsi) : Mist.noop()
try FileManager.default.createDirectory(atPath: outputURL.path, withIntermediateDirectories: true, attributes: nil)
processing = true
}
if FileManager.default.fileExists(atPath: temporaryURL.path), !options.cacheDownloads {
!options.quiet ? PrettyPrint.print("Deleting old temporary directory '\(temporaryURL.path)'...", noAnsi: options.noAnsi) : Mist.noop()
try FileManager.default.removeItem(at: temporaryURL)
processing = true
}
if !FileManager.default.fileExists(atPath: temporaryURL.path) {
!options.quiet ? PrettyPrint.print("Creating new temporary directory '\(temporaryURL.path)'...", noAnsi: options.noAnsi) : Mist.noop()
try FileManager.default.createDirectory(at: temporaryURL, withIntermediateDirectories: true, attributes: nil)
processing = true
}
if !processing {
!options.quiet ? PrettyPrint.print("Nothing to do!", noAnsi: options.noAnsi) : Mist.noop()
}
}
/// Verifies free space for macOS Firmware downloads.
///
/// - Parameters:
/// - firmware: The selected macOS Firmware to be downloaded.
/// - options: Download options for macOS Firmwares.
///
/// - Throws: A `MistError` if there is not enough free space.
private static func verifyFreeSpace(_ firmware: Firmware, options: DownloadFirmwareOptions) throws {
let outputURL: URL = .init(fileURLWithPath: outputDirectory(for: firmware, options: options))
let temporaryURL: URL = .init(fileURLWithPath: options.temporaryDirectory)
let required: Int64 = firmware.size
for url in [outputURL, temporaryURL] {
var free: Int64 = 0
#if os(Linux)
let values: URLResourceValues = try url.resourceValues(forKeys: [.volumeAvailableCapacityKey])
if let volumeAvailableCapacity: Int = values.volumeAvailableCapacity {
free = Int64(volumeAvailableCapacity)
}
#else
let values: URLResourceValues = try url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityKey])
if
let volumeAvailableCapacityForImportantUsage: Int64 = values.volumeAvailableCapacityForImportantUsage,
volumeAvailableCapacityForImportantUsage > 0 {
free = volumeAvailableCapacityForImportantUsage
} else if let volumeAvailableCapacity: Int = values.volumeAvailableCapacity {
free = Int64(volumeAvailableCapacity)
}
#endif
if free == 0 {
throw MistError.notEnoughFreeSpace(volume: url.path, free: 0, required: required)
}
guard required < free else {
throw MistError.notEnoughFreeSpace(volume: url.path, free: free, required: required)
}
}
}
/// Tears down temporary directory structure for macOS Firmware downloads.
///
/// - Parameters:
/// - firmware: The selected macOS Firmware that was downloaded.
/// - options: Download options for macOS Firmwares.
///
/// - Throws: An `Error` if any of the directory operations fail.
private static func teardown(_ firmware: Firmware, options: DownloadFirmwareOptions) throws {
let temporaryURL: URL = .init(fileURLWithPath: temporaryDirectory(for: firmware, options: options))
!options.quiet ? PrettyPrint.printHeader("TEARDOWN", noAnsi: options.noAnsi) : Mist.noop()
if FileManager.default.fileExists(atPath: temporaryURL.path), !options.cacheDownloads {
!options.quiet ? PrettyPrint.print("Deleting temporary directory '\(temporaryURL.path)'...", noAnsi: options.noAnsi, prefix: .ending) : Mist.noop()
try FileManager.default.removeItem(at: temporaryURL)
} else {
!options.quiet ? PrettyPrint.print("Nothing to do!", noAnsi: options.noAnsi, prefix: options.exportPath != nil ? .default : .ending) : Mist.noop()
}
}
/// Exports the results for macOS Firmware downloads.
///
/// - Parameters:
/// - firmware: The selected macOS Firmware that was downloaded.
/// - options: Download options for macOS Firmwares.
///
/// - Throws: An `Error` if any of the directory operations fail.
private static func export(_ firmware: Firmware, options: DownloadFirmwareOptions) throws {
guard let path: String = exportPath(for: firmware, options: options) else {
return
}
let url: URL = .init(fileURLWithPath: path)
let directory: URL = url.deletingLastPathComponent()
if !FileManager.default.fileExists(atPath: directory.path) {
!options.quiet ? PrettyPrint.print("Creating parent directory '\(directory.path)'...", noAnsi: options.noAnsi) : Mist.noop()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
}
let dictionary: [String: Any] = [
"firmware": firmware.dictionary,
"options": exportDictionary(for: firmware, options: options)
]
switch url.pathExtension {
case "json":
try dictionary.jsonString().write(toFile: path, atomically: true, encoding: .utf8)
!options.quiet ? PrettyPrint.print("Exported download results as JSON: '\(path)'", noAnsi: options.noAnsi) : Mist.noop()
case "plist":
try dictionary.propertyListString().write(toFile: path, atomically: true, encoding: .utf8)
!options.quiet ? PrettyPrint.print("Exported download results as Property List: '\(path)'", noAnsi: options.noAnsi) : Mist.noop()
case "yaml":
try dictionary.yamlString().write(toFile: path, atomically: true, encoding: .utf8)
!options.quiet ? PrettyPrint.print("Exported download results as YAML: '\(path)'", noAnsi: options.noAnsi) : Mist.noop()
default:
break
}
}
private static func exportDictionary(for firmware: Firmware, options: DownloadFirmwareOptions) -> [String: Any] {
[
"includeBetas": options.includeBetas,
"force": options.force,
"firmwarePath": firmwarePath(for: firmware, options: options),
"outputDirectory": outputDirectory(for: firmware, options: options),
"temporaryDirectory": temporaryDirectory(for: firmware, options: options),
"exportPath": exportPath(for: firmware, options: options) ?? "",
"quiet": options.quiet
]
}
private static func exportPath(for firmware: Firmware, options: DownloadFirmwareOptions) -> String? {
guard let path: String = options.exportPath else {
return nil
}
return path.stringWithSubstitutions(using: firmware)
}
static func firmwarePath(for firmware: Firmware, options: DownloadFirmwareOptions) -> String {
"\(options.outputDirectory)/\(options.firmwareName)".stringWithSubstitutions(using: firmware)
}
private static func outputDirectory(for firmware: Firmware, options: DownloadFirmwareOptions) -> String {
options.outputDirectory.stringWithSubstitutions(using: firmware)
}
static func temporaryDirectory(for firmware: Firmware, options: DownloadFirmwareOptions) -> String {
"\(options.temporaryDirectory)/\(firmware.identifier)".replacingOccurrences(of: "//", with: "/")
}
static func cachingServerURL(for source: URL, options: DownloadFirmwareOptions) -> URL? {
guard
let cachingServerHost: String = options.cachingServer,
let sourceHost: String = source.host else {
return nil
}
let cachingServerPath: String = source.path.replacingOccurrences(of: sourceHost, with: "")
let cachingServerString: String = "\(cachingServerHost)\(cachingServerPath)?source=\(sourceHost)&sourceScheme=https"
guard let cachingServerURL: URL = URL(string: cachingServerString) else {
return nil
}
return cachingServerURL
}
static func resumeDataURL(for firmware: Firmware, options: DownloadFirmwareOptions) -> URL {
let temporaryDirectory: String = temporaryDirectory(for: firmware, options: options)
let string: String = "\(temporaryDirectory)/\(firmware.filename).resumeData"
let url: URL = .init(fileURLWithPath: string)
return url
}
mutating func run() throws {
do {
try DownloadFirmwareCommand.run(options: options)
} catch {
if let mistError: MistError = error as? MistError {
PrettyPrint.print(mistError.description, noAnsi: options.noAnsi, prefix: .ending, prefixColor: .red)
} else {
PrettyPrint.print(error.localizedDescription, noAnsi: options.noAnsi, prefix: .ending, prefixColor: .red)
}
throw ExitCode(1)
}
}
}