From 6d7753ea66ad14ddee05cc98bec4988a826630b5 Mon Sep 17 00:00:00 2001 From: Rajiv Shah Date: Mon, 25 May 2020 16:27:53 -0400 Subject: [PATCH 1/4] Add SwiftLint config --- .swiftlint.yml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .swiftlint.yml diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 00000000..2eadeec0 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,4 @@ +excluded: + - Vendor +disabled_rules: + - opening_brace From 9c13919fd8119d7f2bbd35425820a1a1b2c7e9a6 Mon Sep 17 00:00:00 2001 From: Rajiv Shah Date: Mon, 25 May 2020 17:06:53 -0400 Subject: [PATCH 2/4] Run SwiftLint autocorrect --- .swiftlint.yml | 5 + Tests/SPUDownloaderTest.swift | 52 +++++----- Tests/SUAppcastTest.swift | 98 +++++++++--------- Tests/SUFileManagerTest.swift | 140 +++++++++++++------------- Tests/SUSpotlightImporterTest.swift | 28 +++--- Tests/SUUnarchiverTest.swift | 58 +++++------ UITests/SUTestApplicationTest.swift | 58 +++++------ generate_appcast/Appcast.swift | 110 ++++++++++---------- generate_appcast/ArchiveItem.swift | 150 ++++++++++++++-------------- generate_appcast/FeedXML.swift | 137 +++++++++++++------------ generate_appcast/Signatures.swift | 98 +++++++++--------- generate_appcast/URL+Hashing.swift | 2 +- generate_appcast/Unarchive.swift | 88 ++++++++-------- generate_appcast/main.swift | 102 +++++++++---------- generate_keys/main.swift | 64 ++++++------ sign_update/main.swift | 47 ++++----- 16 files changed, 617 insertions(+), 620 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index 2eadeec0..bf68de16 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -2,3 +2,8 @@ excluded: - Vendor disabled_rules: - opening_brace + - empty_parentheses_with_trailing_closure + +# Rule-specific config +trailing_comma: + mandatory_comma: true diff --git a/Tests/SPUDownloaderTest.swift b/Tests/SPUDownloaderTest.swift index b08bdb5f..f1d27a9d 100644 --- a/Tests/SPUDownloaderTest.swift +++ b/Tests/SPUDownloaderTest.swift @@ -10,30 +10,30 @@ import XCTest import Sparkle class SPUDownloaderTestDelegate: NSObject, SPUDownloaderDelegate { - + var asyncExpectation: XCTestExpectation? var tempResult: SPUDownloadData? var downloadPath: URL? - + func downloaderDidReceiveData(ofLength length: UInt64) { } - + func downloaderDidReceiveExpectedContentLength(_ expectedContentLength: Int64) { } - + func downloaderDidSetDestinationName(_ destinationName: String, temporaryDirectory: String) { self.downloadPath = NSURL(fileURLWithPath: temporaryDirectory).appendingPathComponent(destinationName) } - + func downloaderDidFailWithError(_ error: Error) { - XCTFail(error.localizedDescription); + XCTFail(error.localizedDescription) self.asyncExpectation?.fulfill() } - + func downloaderDidFinish(withTemporaryDownloadData downloadData: SPUDownloadData?) { self.tempResult = downloadData @@ -47,35 +47,35 @@ class SPUDownloaderTest: XCTestCase { let delegateExpectation = expectation(description: "SPUDownloader temporary download") delegate.asyncExpectation = delegateExpectation - + let url = URL.init(string: "https://sparkle-project.org/unit_test/test.xml") var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 30.0) request.setValue("application/rss+xml,*/*;q=0.1", forHTTPHeaderField: "Accept") - + let downloaderRequest = SPUURLRequest(request: request as URLRequest) downloader.startTemporaryDownload(with: downloaderRequest) - + super.waitForExpectations(timeout: 30.0) { error in if let error = error { XCTFail("waitForExpectations had error: \(error)") } - + guard let result = delegate.tempResult else { XCTFail("Expected result to be non-nil") return } - + let str = String.init(data: result.data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) XCTAssert(str == "appcast\n") } } - + // SHA256 code from: https://stackoverflow.com/a/42934185/3938401 func sha256(data: Data) -> Data { var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH)) - + _ = digestData.withUnsafeMutableBytes {digestBytes in data.withUnsafeBytes {messageBytes in CC_SHA256(messageBytes, CC_LONG(data.count), digestBytes) @@ -83,59 +83,59 @@ class SPUDownloaderTest: XCTestCase } return digestData } - + func performPersistentDownloadTest(withDownloader downloader: SPUDownloader, delegate: SPUDownloaderTestDelegate) { let delegateExpectation = expectation(description: "SPUDownloader persistent download") delegate.asyncExpectation = delegateExpectation - + let url = URL.init(string: "https://sparkle-project.org/unit_test/icon.png") var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 30.0) request.setValue("image/png", forHTTPHeaderField: "Accept") - + let downloaderRequest = SPUURLRequest(request: request as URLRequest) let bundleIdentifier = Bundle.init(for: self.superclass!).bundleIdentifier downloader.startPersistentDownload(with: downloaderRequest, bundleIdentifier: bundleIdentifier!, desiredFilename: "icon") - + super.waitForExpectations(timeout: 30.0) { error in if let error = error { XCTFail("waitForExpectations had error: \(error)") } - + guard let filePath = delegate.downloadPath else { XCTFail("Expected download path to be non-nil") return } - + let fileManager = FileManager.default XCTAssert(fileManager.fileExists(atPath: filePath.path)) - + do { let iconData = try Data.init(contentsOf: filePath) let sha256HashData = self.sha256(data: iconData) let hashString = sha256HashData.map { String(format: "%02hhx", $0) }.joined().uppercased() - + XCTAssert(hashString == "F262E65663C505B9C6449B61660FA3F223912465AE637014288294A8CB286B85") } catch { XCTFail("Something went wrong reading the file data") } } } - + func testDeprecatedDownloader() { let delegate = SPUDownloaderTestDelegate() let downloader = SPUDownloaderDeprecated(delegate: delegate) - + self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) self.performPersistentDownloadTest(withDownloader: downloader!, delegate: delegate) } - + func testSessionDownloader() { let delegate = SPUDownloaderTestDelegate() var downloader = SPUDownloaderSession(delegate: delegate) - + self.performTemporaryDownloadTest(withDownloader: downloader!, delegate: delegate) downloader = SPUDownloaderSession(delegate: delegate) self.performPersistentDownloadTest(withDownloader: downloader!, delegate: delegate) diff --git a/Tests/SUAppcastTest.swift b/Tests/SUAppcastTest.swift index 0038489c..c06d8fd7 100644 --- a/Tests/SUAppcastTest.swift +++ b/Tests/SUAppcastTest.swift @@ -7,64 +7,64 @@ // import XCTest -import Sparkle; +import Sparkle class SUAppcastTest: XCTestCase { func testParseAppcast() { - let appcast = SUAppcast(); - let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testappcast", ofType: "xml")!; - let testFileUrl = URL(fileURLWithPath: testFile); - XCTAssertNotNil(testFileUrl); - + let appcast = SUAppcast() + let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testappcast", ofType: "xml")! + let testFileUrl = URL(fileURLWithPath: testFile) + XCTAssertNotNil(testFileUrl) + do { - let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem]; - - XCTAssertEqual(4, items.count); - - XCTAssertEqual("Version 2.0", items[0].title); - XCTAssertEqual("desc", items[0].itemDescription); + let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem] + + XCTAssertEqual(4, items.count) + + XCTAssertEqual("Version 2.0", items[0].title) + XCTAssertEqual("desc", items[0].itemDescription) XCTAssertEqual("Sat, 26 Jul 2014 15:20:11 +0000", items[0].dateString) - XCTAssertTrue(items[0].isCriticalUpdate); - + XCTAssertTrue(items[0].isCriticalUpdate) + // This is the best release matching our system version - XCTAssertEqual("Version 3.0", items[1].title); - XCTAssertNil(items[1].itemDescription); + XCTAssertEqual("Version 3.0", items[1].title) + XCTAssertNil(items[1].itemDescription) XCTAssertNil(items[1].dateString) - XCTAssertFalse(items[1].isCriticalUpdate); - XCTAssertEqual(items[1].phasedRolloutInterval, 86400); - - XCTAssertEqual("Version 4.0", items[2].title); - XCTAssertNil(items[2].itemDescription); + XCTAssertFalse(items[1].isCriticalUpdate) + XCTAssertEqual(items[1].phasedRolloutInterval, 86400) + + XCTAssertEqual("Version 4.0", items[2].title) + XCTAssertNil(items[2].itemDescription) XCTAssertEqual("Sat, 26 Jul 2014 15:20:13 +0000", items[2].dateString) - XCTAssertFalse(items[2].isCriticalUpdate); - - XCTAssertEqual("Version 5.0", items[3].title); - XCTAssertNil(items[3].itemDescription); + XCTAssertFalse(items[2].isCriticalUpdate) + + XCTAssertEqual("Version 5.0", items[3].title) + XCTAssertNil(items[3].itemDescription) XCTAssertNil(items[3].dateString) - XCTAssertFalse(items[3].isCriticalUpdate); - + XCTAssertFalse(items[3].isCriticalUpdate) + // Test best appcast item & a delta update item - var deltaItem: SUAppcastItem? = nil + var deltaItem: SUAppcastItem? let bestAppcastItem = SUBasicUpdateDriver.bestItem(fromAppcastItems: items, getDeltaItem: &deltaItem, withHostVersion: "1.0", comparator: SUStandardVersionComparator.default()) XCTAssertEqual(bestAppcastItem, items[1]) XCTAssertEqual(deltaItem!.fileURL.lastPathComponent, "3.0_from_1.0.patch") - + // Test latest delta update item available - var latestDeltaItem: SUAppcastItem? = nil + var latestDeltaItem: SUAppcastItem? SUBasicUpdateDriver.bestItem(fromAppcastItems: items, getDeltaItem: &latestDeltaItem, withHostVersion: "2.0", comparator: SUStandardVersionComparator.default()) - + XCTAssertEqual(latestDeltaItem!.fileURL.lastPathComponent, "3.0_from_2.0.patch") - + // Test a delta item that does not exist - var nonexistantDeltaItem: SUAppcastItem? = nil + var nonexistantDeltaItem: SUAppcastItem? SUBasicUpdateDriver.bestItem(fromAppcastItems: items, getDeltaItem: &nonexistantDeltaItem, withHostVersion: "2.1", comparator: SUStandardVersionComparator.default()) - + XCTAssertNil(nonexistantDeltaItem) } catch let err as NSError { - NSLog("%@", err); - XCTFail(err.localizedDescription); + NSLog("%@", err) + XCTFail(err.localizedDescription) } } @@ -76,7 +76,7 @@ class SUAppcastTest: XCTestCase { XCTAssertNotNil(testFileUrl) do { - let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem]; + let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem] XCTAssertEqual("https://sparkle-project.org/#localized_notes_link_works", items[0].releaseNotesURL.absoluteString) } catch let err as NSError { NSLog("%@", err) @@ -85,23 +85,23 @@ class SUAppcastTest: XCTestCase { } func testNamespaces() { - let appcast = SUAppcast(); - let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testnamespaces", ofType: "xml")!; - let testFileUrl = URL(fileURLWithPath: testFile); - XCTAssertNotNil(testFileUrl); + let appcast = SUAppcast() + let testFile = Bundle(for: SUAppcastTest.self).path(forResource: "testnamespaces", ofType: "xml")! + let testFileUrl = URL(fileURLWithPath: testFile) + XCTAssertNotNil(testFileUrl) do { - let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem]; + let items = try appcast.parseAppcastItems(fromXMLFile: testFileUrl) as! [SUAppcastItem] - XCTAssertEqual(2, items.count); + XCTAssertEqual(2, items.count) - XCTAssertEqual("Version 2.0", items[1].title); - XCTAssertEqual("desc", items[1].itemDescription); - XCTAssertNotNil(items[0].releaseNotesURL); - XCTAssertEqual("https://sparkle-project.org/#works", items[0].releaseNotesURL!.absoluteString); + XCTAssertEqual("Version 2.0", items[1].title) + XCTAssertEqual("desc", items[1].itemDescription) + XCTAssertNotNil(items[0].releaseNotesURL) + XCTAssertEqual("https://sparkle-project.org/#works", items[0].releaseNotesURL!.absoluteString) } catch let err as NSError { - NSLog("%@", err); - XCTFail(err.localizedDescription); + NSLog("%@", err) + XCTFail(err.localizedDescription) } } diff --git a/Tests/SUFileManagerTest.swift b/Tests/SUFileManagerTest.swift index 50aa40c9..043dc5a2 100644 --- a/Tests/SUFileManagerTest.swift +++ b/Tests/SUFileManagerTest.swift @@ -13,54 +13,54 @@ class SUFileManagerTest: XCTestCase func makeTempFiles(_ testBlock: (SUFileManager, URL, URL, URL, URL, URL, URL) -> Void) { let fileManager = SUFileManager.default() - + let tempDirectoryURL = (try! fileManager.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory()))) - + defer { try! fileManager.removeItem(at: tempDirectoryURL) } - + let ordinaryFileURL = tempDirectoryURL.appendingPathComponent("a file written by sparkles unit tests") try! "foo".data(using: String.Encoding.utf8)!.write(to: ordinaryFileURL, options: .atomic) - + let directoryURL = tempDirectoryURL.appendingPathComponent("a directory written by sparkles unit tests") try! FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: false, attributes: nil) - + let fileInDirectoryURL = directoryURL.appendingPathComponent("a file inside a directory written by sparkles unit tests") try! "bar baz".data(using: String.Encoding.utf8)!.write(to: fileInDirectoryURL, options: .atomic) - + let validSymlinkURL = tempDirectoryURL.appendingPathComponent("symlink test") try! FileManager.default.createSymbolicLink(at: validSymlinkURL, withDestinationURL: directoryURL) - + let invalidSymlinkURL = tempDirectoryURL.appendingPathComponent("symlink test 2") try! FileManager.default.createSymbolicLink(at: invalidSymlinkURL, withDestinationURL: (tempDirectoryURL.appendingPathComponent("does not exist"))) - + testBlock(fileManager, tempDirectoryURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL) } - + func testMoveFiles() { makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in XCTAssertNil(try? fileManager.moveItem(at: ordinaryFileURL, to: directoryURL)) XCTAssertNil(try? fileManager.moveItem(at: ordinaryFileURL, to: directoryURL.appendingPathComponent("foo").appendingPathComponent("bar"))) XCTAssertNil(try? fileManager.moveItem(at: rootURL.appendingPathComponent("does not exist"), to: directoryURL)) - + let newFileURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new file")) try! fileManager.moveItem(at: ordinaryFileURL, to: newFileURL) XCTAssertFalse(fileManager._itemExists(at: ordinaryFileURL)) XCTAssertTrue(fileManager._itemExists(at: newFileURL)) - + let newValidSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new symlink")) try! fileManager.moveItem(at: validSymlinkURL, to: newValidSymlinkURL) XCTAssertFalse(fileManager._itemExists(at: validSymlinkURL)) XCTAssertTrue(fileManager._itemExists(at: newValidSymlinkURL)) XCTAssertTrue(fileManager._itemExists(at: directoryURL)) - + let newInvalidSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new invalid symlink")) try! fileManager.moveItem(at: invalidSymlinkURL, to: newInvalidSymlinkURL) XCTAssertFalse(fileManager._itemExists(at: invalidSymlinkURL)) XCTAssertTrue(fileManager._itemExists(at: newValidSymlinkURL)) - + let newDirectoryURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new directory")) try! fileManager.moveItem(at: directoryURL, to: newDirectoryURL) XCTAssertFalse(fileManager._itemExists(at: directoryURL)) @@ -69,23 +69,23 @@ class SUFileManagerTest: XCTestCase XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL.appendingPathComponent(fileInDirectoryURL.lastPathComponent))) } } - + func testCopyFiles() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, _, invalidSymlinkURL in XCTAssertNil(try? fileManager.copyItem(at: ordinaryFileURL, to: directoryURL)) XCTAssertNil(try? fileManager.copyItem(at: ordinaryFileURL, to: directoryURL.appendingPathComponent("foo").appendingPathComponent("bar"))) XCTAssertNil(try? fileManager.copyItem(at: rootURL.appendingPathComponent("does not exist"), to: directoryURL)) - + let newFileURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new file")) try! fileManager.copyItem(at: ordinaryFileURL, to: newFileURL) XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL)) XCTAssertTrue(fileManager._itemExists(at: newFileURL)) - + let newSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new symlink file")) try! fileManager.copyItem(at: invalidSymlinkURL, to: newSymlinkURL) XCTAssertTrue(fileManager._itemExists(at: newSymlinkURL)) - + let newDirectoryURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new directory")) try! fileManager.copyItem(at: directoryURL, to: newDirectoryURL) XCTAssertTrue(fileManager._itemExists(at: directoryURL)) @@ -97,80 +97,80 @@ class SUFileManagerTest: XCTestCase func testRemoveFiles() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, _ in XCTAssertNil(try? fileManager.removeItem(at: rootURL.appendingPathComponent("does not exist"))) - + try! fileManager.removeItem(at: ordinaryFileURL) XCTAssertFalse(fileManager._itemExists(at: ordinaryFileURL)) - + try! fileManager.removeItem(at: validSymlinkURL) XCTAssertFalse(fileManager._itemExists(at: validSymlinkURL)) XCTAssertTrue(fileManager._itemExists(at: directoryURL)) - + try! fileManager.removeItem(at: directoryURL) XCTAssertFalse(fileManager._itemExists(at: directoryURL)) XCTAssertFalse(fileManager._itemExists(at: fileInDirectoryURL)) } } - + func testReleaseFilesFromQuarantine() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + makeTempFiles() { fileManager, _, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, _ in try! fileManager.releaseItemFromQuarantine(atRootURL: ordinaryFileURL) try! fileManager.releaseItemFromQuarantine(atRootURL: directoryURL) try! fileManager.releaseItemFromQuarantine(atRootURL: validSymlinkURL) - + let quarantineData = "does not really matter what is here".cString(using: String.Encoding.utf8)! let quarantineDataLength = Int(strlen(quarantineData)) - + XCTAssertEqual(0, setxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) XCTAssertGreaterThan(getxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) - + try! fileManager.releaseItemFromQuarantine(atRootURL: ordinaryFileURL) XCTAssertEqual(-1, getxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) - + XCTAssertEqual(0, setxattr(directoryURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) XCTAssertGreaterThan(getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) - + XCTAssertEqual(0, setxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE)) XCTAssertGreaterThan(getxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) - + // Extended attributes can't be set on symbolic links currently try! fileManager.releaseItemFromQuarantine(atRootURL: validSymlinkURL) XCTAssertGreaterThan(getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0) XCTAssertEqual(-1, getxattr(validSymlinkURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) - + try! fileManager.releaseItemFromQuarantine(atRootURL: directoryURL) - + XCTAssertEqual(-1, getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) XCTAssertEqual(-1, getxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW)) } } - + func groupIDAtPath(_ path: String) -> gid_t { let attributes = try! FileManager.default.attributesOfItem(atPath: path) let groupID = attributes[FileAttributeKey.groupOwnerAccountID] as! NSNumber return groupID.uint32Value } - + // Only the super user can alter user IDs, so changing user IDs is not tested here // Instead we try to change the group ID - we just have to be a member of that group func testAlterFilesGroupID() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, _ in XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItem(atRootURL: ordinaryFileURL, toMatch: rootURL.appendingPathComponent("does not exist"))) - + XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItem(atRootURL: rootURL.appendingPathComponent("does not exist"), toMatch: ordinaryFileURL)) - + let everyoneGroup = getgrnam("everyone") let everyoneGroupID = everyoneGroup?.pointee.gr_gid - + let staffGroup = getgrnam("staff") let staffGroupID = staffGroup?.pointee.gr_gid - + XCTAssertNotEqual(staffGroupID, everyoneGroupID) - + XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path)) XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path)) XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) @@ -179,103 +179,103 @@ class SUFileManagerTest: XCTestCase try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: ordinaryFileURL) try! fileManager.changeOwnerAndGroupOfItem(atRootURL: ordinaryFileURL, toMatch: ordinaryFileURL) try! fileManager.changeOwnerAndGroupOfItem(atRootURL: validSymlinkURL, toMatch: ordinaryFileURL) - + XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path)) XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path)) XCTAssertEqual(staffGroupID, self.groupIDAtPath(validSymlinkURL.path)) - + XCTAssertEqual(0, chown(ordinaryFileURL.path, getuid(), everyoneGroupID!)) XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(ordinaryFileURL.path)) - + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: ordinaryFileURL) XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) - + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: directoryURL) XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) - + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: validSymlinkURL, toMatch: ordinaryFileURL) XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(validSymlinkURL.path)) - + try! fileManager.changeOwnerAndGroupOfItem(atRootURL: directoryURL, toMatch: ordinaryFileURL) XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(directoryURL.path)) XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path)) } } - + func testUpdateFileModificationTime() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, _, validSymlinkURL, _ in XCTAssertNil(try? fileManager.updateModificationAndAccessTimeOfItem(at: rootURL.appendingPathComponent("does not exist"))) - + let oldOrdinaryFileAttributes = try! FileManager.default.attributesOfItem(atPath: ordinaryFileURL.path) let oldDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: directoryURL.path) let oldValidSymlinkAttributes = try! FileManager.default.attributesOfItem(atPath: validSymlinkURL.path) - + sleep(1); // wait for clock to advance - + try! fileManager.updateModificationAndAccessTimeOfItem(at: ordinaryFileURL) try! fileManager.updateModificationAndAccessTimeOfItem(at: directoryURL) try! fileManager.updateModificationAndAccessTimeOfItem(at: validSymlinkURL) - + let newOrdinaryFileAttributes = try! FileManager.default.attributesOfItem(atPath: ordinaryFileURL.path) XCTAssertGreaterThan((newOrdinaryFileAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldOrdinaryFileAttributes[FileAttributeKey.modificationDate] as! Date), 0) - + let newDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: directoryURL.path) XCTAssertGreaterThan((newDirectoryAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldDirectoryAttributes[FileAttributeKey.modificationDate] as! Date), 0) - + let newSymlinkAttributes = try! FileManager.default.attributesOfItem(atPath: validSymlinkURL.path) XCTAssertGreaterThan((newSymlinkAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldValidSymlinkAttributes[FileAttributeKey.modificationDate] as! Date), 0) } } - + func testFileExists() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, _, validSymlinkURL, invalidSymlinkURL in XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL)) XCTAssertTrue(fileManager._itemExists(at: directoryURL)) XCTAssertFalse(fileManager._itemExists(at: rootURL.appendingPathComponent("does not exist"))) - + var isOrdinaryFileDirectory: ObjCBool = false XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL, isDirectory: &isOrdinaryFileDirectory) && !isOrdinaryFileDirectory.boolValue) - + var isDirectoryADirectory: ObjCBool = false XCTAssertTrue(fileManager._itemExists(at: directoryURL, isDirectory: &isDirectoryADirectory) && isDirectoryADirectory.boolValue) - + XCTAssertFalse(fileManager._itemExists(at: rootURL.appendingPathComponent("does not exist"), isDirectory: nil)) - + XCTAssertTrue(fileManager._itemExists(at: validSymlinkURL)) - + var validSymlinkIsADirectory: ObjCBool = false XCTAssertTrue(fileManager._itemExists(at: validSymlinkURL, isDirectory: &validSymlinkIsADirectory) && !validSymlinkIsADirectory.boolValue) - + // Symlink should still exist even if it doesn't point to a file that exists XCTAssertTrue(fileManager._itemExists(at: invalidSymlinkURL)) - + var invalidSymlinkIsADirectory: ObjCBool = false XCTAssertTrue(fileManager._itemExists(at: invalidSymlinkURL, isDirectory: &invalidSymlinkIsADirectory) && !invalidSymlinkIsADirectory.boolValue) } } - + func testMakeDirectory() { - makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in + makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, _, validSymlinkURL, _ in XCTAssertNil(try? fileManager.makeDirectory(at: ordinaryFileURL)) XCTAssertNil(try? fileManager.makeDirectory(at: directoryURL)) - + XCTAssertNil(try? fileManager.makeDirectory(at: rootURL.appendingPathComponent("this should").appendingPathComponent("be a failure"))) - + let newDirectoryURL = rootURL.appendingPathComponent("new test directory") XCTAssertFalse(fileManager._itemExists(at: newDirectoryURL)) try! fileManager.makeDirectory(at: newDirectoryURL) - + var isDirectory: ObjCBool = false XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL, isDirectory: &isDirectory)) - + try! fileManager.removeItem(at: directoryURL) XCTAssertNil(try? fileManager.makeDirectory(at: validSymlinkURL)) } } - + func testAcquireBadAuthorization() { let fileManager = SUFileManager.default() diff --git a/Tests/SUSpotlightImporterTest.swift b/Tests/SUSpotlightImporterTest.swift index 25193055..c3709039 100644 --- a/Tests/SUSpotlightImporterTest.swift +++ b/Tests/SUSpotlightImporterTest.swift @@ -14,47 +14,47 @@ class SUSpotlightImporterTest: XCTestCase { let fileManager = SUFileManager.default() let tempDirectoryURL = try! fileManager.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())) - + let bundleDirectory = tempDirectoryURL.appendingPathComponent("bundle.app") try! fileManager.makeDirectory(at: bundleDirectory) - + let innerDirectory = bundleDirectory.appendingPathComponent("foo") try! fileManager.makeDirectory(at: innerDirectory) try! Data().write(to: (bundleDirectory.appendingPathComponent("bar")), options: .atomicWrite) - + let importerDirectory = innerDirectory.appendingPathComponent("baz.mdimporter") - + try! fileManager.makeDirectory(at: importerDirectory) try! fileManager.makeDirectory(at: innerDirectory.appendingPathComponent("flag")) - + try! Data().write(to: (importerDirectory.appendingPathComponent("file")), options: .atomicWrite) - + let oldFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.path) let oldBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory.appendingPathComponent("bar").path) let oldImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.path) let oldFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.appendingPathComponent("flag").path) let oldFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.appendingPathComponent("file").path) - + sleep(1) // wait for clock to advance - + // Update spotlight bundles SUBinaryDeltaUnarchiver.updateSpotlightImporters(atBundlePath: bundleDirectory.path) - + let newFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.path) XCTAssertEqual((newFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date), 0) - + let newBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory.appendingPathComponent("bar").path) XCTAssertEqual((newBarFileAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldBarFileAttributes[FileAttributeKey.modificationDate] as! Date), 0) - + let newImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.path) XCTAssertGreaterThan((newImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0) - + let newFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.appendingPathComponent("flag").path) XCTAssertEqual((newFlagAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFlagAttributes[FileAttributeKey.modificationDate] as! Date), 0) - + let newFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.appendingPathComponent("file").path) XCTAssertEqual((newFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0) - + try! fileManager.removeItem(at: tempDirectoryURL) } } diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 3ce04f5b..c198c523 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -13,84 +13,84 @@ class SUUnarchiverTest: XCTestCase func unarchiveTestAppWithExtension(_ archiveExtension: String, password: String? = nil) { let appName = "SparkleTestCodeSignApp" let archiveResourceURL = Bundle(for: type(of: self)).url(forResource: appName, withExtension: archiveExtension)! - + let fileManager = FileManager.default - + // Do not remove this temporary directory // If we do want to clean up and remove it (which isn't necessary but nice), we'd have to remove it // after *both* our unarchive success and failure calls below finish (they both have async completion blocks inside their implementation) let tempDirectoryURL = try! fileManager.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: URL(fileURLWithPath: NSHomeDirectory()), create: true) - + let unarchivedSuccessExpectation = super.expectation(description: "Unarchived Success (format: \(archiveExtension))") let unarchivedFailureExpectation = super.expectation(description: "Unarchived Failure (format: \(archiveExtension))") - + let tempArchiveURL = tempDirectoryURL.appendingPathComponent(archiveResourceURL.lastPathComponent) let extractedAppURL = tempDirectoryURL.appendingPathComponent(appName).appendingPathExtension("app") - - self.unarchiveTestSuccessAppWithExtension(archiveExtension, appName: appName, tempDirectoryURL: tempDirectoryURL, tempArchiveURL: tempArchiveURL, archiveResourceURL: archiveResourceURL, password: password, testExpectation: unarchivedSuccessExpectation); - self.unarchiveTestFailureAppWithExtension(archiveExtension, tempDirectoryURL: tempDirectoryURL, password: password, testExpectation: unarchivedFailureExpectation); - + + self.unarchiveTestSuccessAppWithExtension(archiveExtension, appName: appName, tempDirectoryURL: tempDirectoryURL, tempArchiveURL: tempArchiveURL, archiveResourceURL: archiveResourceURL, password: password, testExpectation: unarchivedSuccessExpectation) + self.unarchiveTestFailureAppWithExtension(archiveExtension, tempDirectoryURL: tempDirectoryURL, password: password, testExpectation: unarchivedFailureExpectation) + super.waitForExpectations(timeout: 7.0, handler: nil) - + XCTAssertTrue(fileManager.fileExists(atPath: extractedAppURL.path)) - + XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path)) } - + func unarchiveTestFailureAppWithExtension(_ archiveExtension: String, tempDirectoryURL: URL, password: String?, testExpectation: XCTestExpectation) { - let tempArchiveURL = tempDirectoryURL.appendingPathComponent("error-invalid").appendingPathExtension(archiveExtension); + let tempArchiveURL = tempDirectoryURL.appendingPathComponent("error-invalid").appendingPathExtension(archiveExtension) let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: password)! - + unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in - XCTAssertNotNil(error); + XCTAssertNotNil(error) testExpectation.fulfill() - }, progressBlock: nil); + }, progressBlock: nil) } - + func unarchiveTestSuccessAppWithExtension(_ archiveExtension: String, appName: String, tempDirectoryURL: URL, tempArchiveURL: URL, archiveResourceURL: URL, password: String?, testExpectation: XCTestExpectation) { - + let fileManager = FileManager.default - + try! fileManager.copyItem(at: archiveResourceURL, to: tempArchiveURL) - + let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: password)! - + unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in - XCTAssertNil(error); + XCTAssertNil(error) testExpectation.fulfill() - }, progressBlock: nil); + }, progressBlock: nil) } - + func testUnarchivingZip() { self.unarchiveTestAppWithExtension("zip") } - + func testUnarchivingTarDotGz() { self.unarchiveTestAppWithExtension("tar.gz") } - + func testUnarchivingTar() { self.unarchiveTestAppWithExtension("tar") } - + func testUnarchivingTarDotBz2() { self.unarchiveTestAppWithExtension("tar.bz2") } - + func testUnarchivingTarDotXz() { self.unarchiveTestAppWithExtension("tar.xz") } - + func testUnarchivingDmg() { self.unarchiveTestAppWithExtension("dmg") } - + func testUnarchivingEncryptedDmg() { self.unarchiveTestAppWithExtension("enc.dmg", password: "testpass") diff --git a/UITests/SUTestApplicationTest.swift b/UITests/SUTestApplicationTest.swift index 7f360a20..36deb7cd 100644 --- a/UITests/SUTestApplicationTest.swift +++ b/UITests/SUTestApplicationTest.swift @@ -10,10 +10,10 @@ import XCTest class SUTestApplicationTest: XCTestCase { - var testApplicationURL: URL? = nil - var testApplicationBackupURL: URL? = nil - var tempDirectoryURL: URL? = nil - + var testApplicationURL: URL? + var testApplicationBackupURL: URL? + var tempDirectoryURL: URL? + func runningTestApplication() -> NSRunningApplication { // TODO: don't hardcode bundle ID? @@ -21,91 +21,91 @@ class SUTestApplicationTest: XCTestCase XCTAssertEqual(runningApplications.count, 1, "More than one or zero running instances of the Test Application are found") return runningApplications[0] } - + override func setUp() { super.setUp() - + let app = XCUIApplication() app.launch() - + XCTAssertFalse(app.dialogs["alert"].staticTexts["Update succeeded!"].exists, "Update is already installed; please do a clean build") - + // We need to grab the app URL so we can back up the app // When a successful test is over we'll revert the update let testApplicationURL = self.runningTestApplication().bundleURL! - + let tempDirectoryURL = try! FileManager.default.url(for: .itemReplacementDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: testApplicationURL, create: true) - + let testApplicationBackupURL = tempDirectoryURL.appendingPathComponent(testApplicationURL.lastPathComponent) - + try! FileManager.default.copyItem(at: testApplicationURL, to: testApplicationBackupURL) - + self.testApplicationURL = testApplicationURL self.testApplicationBackupURL = testApplicationBackupURL self.tempDirectoryURL = tempDirectoryURL - + // when we add more tests we don't want to continue after a failure // since a test can fail after the new app has been placed in self.continueAfterFailure = false } - + override func tearDown() { // Terminate just in case the app hasn't already quit XCUIApplication().terminate() - + // Revert our update with the original test application - - var resultingURL: NSURL? = nil + + var resultingURL: NSURL? try! FileManager.default.replaceItem(at: self.testApplicationURL!, withItemAt: self.testApplicationBackupURL!, backupItemName: nil, options: .usingNewMetadataOnly, resultingItemURL: &resultingURL) - + do { try FileManager.default.removeItem(at: self.tempDirectoryURL!) } catch let error as NSError { NSLog("Failed to remove temporary directory \(self.tempDirectoryURL) with error: \(error)") } - + // The URL we get back from NSFileManager should be the same.. XCTAssertEqual(self.testApplicationURL, resultingURL as URL?, "Test application was replaced, but at a different location") - + super.tearDown() } - + func testRegularUpdate() { let app = XCUIApplication() let menuBarsQuery = app.menuBars menuBarsQuery.menuBarItems["Sparkle Test App"].click() - + // If the update window already showed up automatically, this option will be disabled. // Even if it's disabled, attempting to click it will do no harm and continue on menuBarsQuery.menuItems["Check for Updates…"].click() - + // Workaround to make sure we can click the install update button later // This workaround is needed if the alert prompts up automatically *before* we manually check for updates // I'm not sure why this workaround works or is necessary app.dialogs["SUUpdateAlert"].staticTexts["Software Update"].click() - + app.dialogs["SUUpdateAlert"].buttons["Install Update"].click() app.windows["SUStatus"].buttons["Install and Relaunch"].click() - + // Wait for the new updated app to finish launching so we can test if it's the frontmost app sleep(3) - + // Our new updated app should be launched now. Test if it's the active app // We used to run into timing issues where the updated app sometimes may not show up as the frontmost one XCTAssertTrue(self.runningTestApplication().isActive) - + // Grab another XCUIApplication instance rather than using the old one, just in case let updatedApp = XCUIApplication() - + // Check if we can click the "Update succeeded!" label rather than using the exists property // Checking the exists property doesn't reload the "cache" and as such the UI tests still would think we are // referring to the older app. Clicking does force the UI tests to find the new app however updatedApp.dialogs["alert"].staticTexts["Update succeeded!"].click() - + updatedApp.dialogs["alert"].buttons["OK"].click() } } diff --git a/generate_appcast/Appcast.swift b/generate_appcast/Appcast.swift index 0f4ff293..166dbc25 100644 --- a/generate_appcast/Appcast.swift +++ b/generate_appcast/Appcast.swift @@ -6,159 +6,159 @@ import Foundation // Maximum number of delta updates (per OS). -let maxDeltas = 5; +let maxDeltas = 5 func makeError(code: SUError, _ description: String) -> NSError { return NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(code.rawValue)), userInfo: [ NSLocalizedDescriptionKey: description, - ]); + ]) } -func makeAppcast(archivesSourceDir: URL, keys: PrivateKeys, verbose: Bool) throws -> [String:[ArchiveItem]] { - let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("Sparkle_generate_appcast"); - let comparator = SUStandardVersionComparator(); +func makeAppcast(archivesSourceDir: URL, keys: PrivateKeys, verbose: Bool) throws -> [String: [ArchiveItem]] { + let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("Sparkle_generate_appcast") + let comparator = SUStandardVersionComparator() - let allUpdates = (try unarchiveUpdates(archivesSourceDir: archivesSourceDir, archivesDestDir: cacheDir, verbose:verbose)) + let allUpdates = (try unarchiveUpdates(archivesSourceDir: archivesSourceDir, archivesDestDir: cacheDir, verbose: verbose)) .sorted(by: { - .orderedDescending == comparator.compareVersion($0.version, toVersion:$1.version) + .orderedDescending == comparator.compareVersion($0.version, toVersion: $1.version) }) if allUpdates.count == 0 { - throw makeError(code: .noUpdateError, "No usable archives found in \(archivesSourceDir.path)"); + throw makeError(code: .noUpdateError, "No usable archives found in \(archivesSourceDir.path)") } - var updatesByAppcast:[String:[ArchiveItem]] = [:]; + var updatesByAppcast: [String: [ArchiveItem]] = [:] - let group = DispatchGroup(); + let group = DispatchGroup() for update in allUpdates { - group.enter(); + group.enter() DispatchQueue.global().async { if let privateDSAKey = keys.privateDSAKey { do { - update.dsaSignature = try dsaSignature(path: update.archivePath, privateDSAKey: privateDSAKey); + update.dsaSignature = try dsaSignature(path: update.archivePath, privateDSAKey: privateDSAKey) } catch { - print(update, error); + print(update, error) } } else if update.supportsDSA { - print("Note: did not sign with legacy DSA \(update.archivePath.path) because private DSA key file was not specified"); + print("Note: did not sign with legacy DSA \(update.archivePath.path) because private DSA key file was not specified") } if let publicEdKey = update.publicEdKey { if let privateEdKey = keys.privateEdKey, let expectedPublicKey = keys.publicEdKey { if publicEdKey == expectedPublicKey { do { - update.edSignature = try edSignature(path: update.archivePath, publicEdKey: publicEdKey, privateEdKey: privateEdKey); + update.edSignature = try edSignature(path: update.archivePath, publicEdKey: publicEdKey, privateEdKey: privateEdKey) } catch { - print(update, error); + print(update, error) } } else { - print("Warning: SUPublicEDKey in the app \(update.archivePath.path) does not match key EdDSA in the Keychain. Run generate_keys and update Info.plist to match"); + print("Warning: SUPublicEDKey in the app \(update.archivePath.path) does not match key EdDSA in the Keychain. Run generate_keys and update Info.plist to match") } } else { - print("Warning: could not sign \(update.archivePath.path) due to lack of private EdDSA key"); + print("Warning: could not sign \(update.archivePath.path) due to lack of private EdDSA key") } } - group.leave(); + group.leave() } - let appcastFile = update.feedURL?.lastPathComponent ?? "appcast.xml"; + let appcastFile = update.feedURL?.lastPathComponent ?? "appcast.xml" if updatesByAppcast[appcastFile] == nil { - updatesByAppcast[appcastFile] = []; + updatesByAppcast[appcastFile] = [] } - updatesByAppcast[appcastFile]!.append(update); + updatesByAppcast[appcastFile]!.append(update) } for (_, updates) in updatesByAppcast { - var latestUpdatePerOS:[String:ArchiveItem] = [:]; + var latestUpdatePerOS: [String: ArchiveItem] = [:] for update in updates { // items are ordered starting latest first - let os = update.minimumSystemVersion; + let os = update.minimumSystemVersion if latestUpdatePerOS[os] == nil { - latestUpdatePerOS[os] = update; + latestUpdatePerOS[os] = update } } - for (_,latestItem) in latestUpdatePerOS { - var numDeltas = 0; - let appBaseName = latestItem.appPath.deletingPathExtension().lastPathComponent; + for (_, latestItem) in latestUpdatePerOS { + var numDeltas = 0 + let appBaseName = latestItem.appPath.deletingPathExtension().lastPathComponent for item in updates { if numDeltas > maxDeltas { - break; + break } // No downgrades if .orderedAscending != comparator.compareVersion(item.version, toVersion: latestItem.version) { - continue; + continue } // Old version will not be able to verify the new version if !item.supportsDSA && item.publicEdKey == nil { - continue; + continue } - let deltaBaseName = appBaseName + latestItem.version + "-" + item.version; - let deltaPath = archivesSourceDir.appendingPathComponent(deltaBaseName).appendingPathExtension("delta"); + let deltaBaseName = appBaseName + latestItem.version + "-" + item.version + let deltaPath = archivesSourceDir.appendingPathComponent(deltaBaseName).appendingPathExtension("delta") - var delta:DeltaUpdate; - let ignoreMarkerPath = cacheDir.appendingPathComponent(deltaPath.lastPathComponent).appendingPathExtension(".ignore"); - let fm = FileManager.default; + var delta: DeltaUpdate + let ignoreMarkerPath = cacheDir.appendingPathComponent(deltaPath.lastPathComponent).appendingPathExtension(".ignore") + let fm = FileManager.default if fm.fileExists(atPath: ignoreMarkerPath.path) { - continue; + continue } if !fm.fileExists(atPath: deltaPath.path) { do { - delta = try DeltaUpdate.create(from: item, to: latestItem, archivePath: deltaPath); + delta = try DeltaUpdate.create(from: item, to: latestItem, archivePath: deltaPath) } catch { - print("Could not create delta update", deltaPath.path, error); - continue; + print("Could not create delta update", deltaPath.path, error) + continue } } else { - delta = DeltaUpdate(fromVersion: item.version, archivePath: deltaPath); + delta = DeltaUpdate(fromVersion: item.version, archivePath: deltaPath) } - numDeltas += 1; + numDeltas += 1 // Require delta to be a bit smaller if delta.fileSize / 7 > latestItem.fileSize / 8 { markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath) - continue; + continue } - group.enter(); + group.enter() DispatchQueue.global().async { if item.supportsDSA, let privateDSAKey = keys.privateDSAKey { do { - delta.dsaSignature = try dsaSignature(path: deltaPath, privateDSAKey: privateDSAKey); + delta.dsaSignature = try dsaSignature(path: deltaPath, privateDSAKey: privateDSAKey) } catch { - print(delta.archivePath.lastPathComponent, error); + print(delta.archivePath.lastPathComponent, error) } } if let publicEdKey = item.publicEdKey, let privateEdKey = keys.privateEdKey { do { - delta.edSignature = try edSignature(path: deltaPath, publicEdKey: publicEdKey, privateEdKey: privateEdKey); + delta.edSignature = try edSignature(path: deltaPath, publicEdKey: publicEdKey, privateEdKey: privateEdKey) } catch { - print(delta.archivePath.lastPathComponent, error); + print(delta.archivePath.lastPathComponent, error) } } if delta.dsaSignature != nil || delta.edSignature != nil { - latestItem.deltas.append(delta); + latestItem.deltas.append(delta) } else { markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath) - print("Delta \(delta.archivePath.path) ignored, because it could not be signed"); + print("Delta \(delta.archivePath.path) ignored, because it could not be signed") } - group.leave(); + group.leave() } } } } - group.wait(); + group.wait() - return updatesByAppcast; + return updatesByAppcast } func markDeltaAsIgnored(delta: DeltaUpdate, markerPath: URL) { - let _ = try? FileManager.default.removeItem(at: delta.archivePath) - let _ = try? Data.init().write(to: markerPath); // 0-sized file + _ = try? FileManager.default.removeItem(at: delta.archivePath) + _ = try? Data.init().write(to: markerPath); // 0-sized file } diff --git a/generate_appcast/ArchiveItem.swift b/generate_appcast/ArchiveItem.swift index 8ed56d72..f86ce470 100644 --- a/generate_appcast/ArchiveItem.swift +++ b/generate_appcast/ArchiveItem.swift @@ -6,63 +6,63 @@ import Foundation class DeltaUpdate { - let fromVersion: String; - let archivePath: URL; - var dsaSignature: String?; - var edSignature: String?; + let fromVersion: String + let archivePath: URL + var dsaSignature: String? + var edSignature: String? init(fromVersion: String, archivePath: URL) { - self.archivePath = archivePath; - self.fromVersion = fromVersion; + self.archivePath = archivePath + self.fromVersion = fromVersion } - var fileSize : Int64 { - let archiveFileAttributes = try! FileManager.default.attributesOfItem(atPath: self.archivePath.path); - return (archiveFileAttributes[.size] as! NSNumber).int64Value; + var fileSize: Int64 { + let archiveFileAttributes = try! FileManager.default.attributesOfItem(atPath: self.archivePath.path) + return (archiveFileAttributes[.size] as! NSNumber).int64Value } class func create(from: ArchiveItem, to: ArchiveItem, archivePath: URL) throws -> DeltaUpdate { - var applyDiffError: NSError? = nil; + var applyDiffError: NSError? - if (!createBinaryDelta(from.appPath.path, to.appPath.path, archivePath.path, .beigeMajorVersion, false, &applyDiffError)) { - throw applyDiffError!; + if !createBinaryDelta(from.appPath.path, to.appPath.path, archivePath.path, .beigeMajorVersion, false, &applyDiffError) { + throw applyDiffError! } - return DeltaUpdate(fromVersion: from.version, archivePath: archivePath); + return DeltaUpdate(fromVersion: from.version, archivePath: archivePath) } } class ArchiveItem: CustomStringConvertible { - let version: String; - let _shortVersion: String?; - let minimumSystemVersion: String; - let archivePath: URL; - let appPath: URL; - let feedURL: URL?; - let publicEdKey: Data?; - let supportsDSA: Bool; - let archiveFileAttributes: [FileAttributeKey:Any]; - var deltas: [DeltaUpdate]; + let version: String + let _shortVersion: String? + let minimumSystemVersion: String + let archivePath: URL + let appPath: URL + let feedURL: URL? + let publicEdKey: Data? + let supportsDSA: Bool + let archiveFileAttributes: [FileAttributeKey: Any] + var deltas: [DeltaUpdate] - var dsaSignature: String?; - var edSignature: String?; - var downloadUrlPrefix: URL?; + var dsaSignature: String? + var edSignature: String? + var downloadUrlPrefix: URL? init(version: String, shortVersion: String?, feedURL: URL?, minimumSystemVersion: String?, publicEdKey: String?, supportsDSA: Bool, appPath: URL, archivePath: URL) throws { - self.version = version; - self._shortVersion = shortVersion; - self.feedURL = feedURL; - self.minimumSystemVersion = minimumSystemVersion ?? "10.7"; - self.archivePath = archivePath; - self.appPath = appPath; - self.supportsDSA = supportsDSA; + self.version = version + self._shortVersion = shortVersion + self.feedURL = feedURL + self.minimumSystemVersion = minimumSystemVersion ?? "10.7" + self.archivePath = archivePath + self.appPath = appPath + self.supportsDSA = supportsDSA if let publicEdKey = publicEdKey { - self.publicEdKey = Data(base64Encoded: publicEdKey); + self.publicEdKey = Data(base64Encoded: publicEdKey) } else { - self.publicEdKey = nil; + self.publicEdKey = nil } - self.archiveFileAttributes = try FileManager.default.attributesOfItem(atPath: self.archivePath.path); - self.deltas = []; + self.archiveFileAttributes = try FileManager.default.attributesOfItem(atPath: self.archivePath.path) + self.deltas = [] } convenience init(fromArchive archivePath: URL, unarchivedDir: URL) throws { @@ -75,24 +75,24 @@ class ArchiveItem: CustomStringConvertible { } else { return false } - }); + }) if bundles.count > 0 { if bundles.count > 1 { - throw makeError(code: .unarchivingError, "Too many bundles in \(unarchivedDir.path) \(bundles)"); + throw makeError(code: .unarchivingError, "Too many bundles in \(unarchivedDir.path) \(bundles)") } - let appPath = bundles[0]; + let appPath = bundles[0] guard let infoPlist = NSDictionary(contentsOf: appPath.appendingPathComponent("Contents/Info.plist")) else { - throw makeError(code: .unarchivingError, "No plist \(appPath.path)"); + throw makeError(code: .unarchivingError, "No plist \(appPath.path)") } guard let version = infoPlist[kCFBundleVersionKey] as? String else { - throw makeError(code: .unarchivingError, "No Version \(kCFBundleVersionKey as String? ?? "missing kCFBundleVersionKey") \(appPath)"); + throw makeError(code: .unarchivingError, "No Version \(kCFBundleVersionKey as String? ?? "missing kCFBundleVersionKey") \(appPath)") } - let shortVersion = infoPlist["CFBundleShortVersionString"] as? String; - let publicEdKey = infoPlist[SUPublicEDKeyKey] as? String; - let supportsDSA = infoPlist[SUPublicDSAKeyKey] != nil || infoPlist[SUPublicDSAKeyFileKey] != nil; + let shortVersion = infoPlist["CFBundleShortVersionString"] as? String + let publicEdKey = infoPlist[SUPublicEDKeyKey] as? String + let supportsDSA = infoPlist[SUPublicDSAKeyKey] != nil || infoPlist[SUPublicDSAKeyFileKey] != nil - var feedURL:URL? = nil; + var feedURL: URL? if let feedURLStr = infoPlist["SUFeedURL"] as? String { feedURL = URL(string: feedURLStr) if feedURL?.pathExtension == "php" { @@ -108,23 +108,23 @@ class ArchiveItem: CustomStringConvertible { publicEdKey: publicEdKey, supportsDSA: supportsDSA, appPath: appPath, - archivePath: archivePath); + archivePath: archivePath) } else { - throw makeError(code: .missingUpdateError, "No supported items in \(unarchivedDir) \(items) [note: only .app bundles are supported]"); + throw makeError(code: .missingUpdateError, "No supported items in \(unarchivedDir) \(items) [note: only .app bundles are supported]") } } var shortVersion: String { - return self._shortVersion ?? self.version; + return self._shortVersion ?? self.version } - var description : String { + var description: String { return "\(self.archivePath) \(self.version)" } var archiveURL: URL? { guard let escapedFilename = self.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - return nil; + return nil } if let downloadUrlPrefix = self.downloadUrlPrefix { // if a download url prefix was given use this one @@ -135,27 +135,27 @@ class ArchiveItem: CustomStringConvertible { return URL(string: escapedFilename) } - var pubDate : String { - let date = self.archiveFileAttributes[.creationDate] as! Date; - let formatter = DateFormatter(); - formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss ZZ"; - return formatter.string(from: date); + var pubDate: String { + let date = self.archiveFileAttributes[.creationDate] as! Date + let formatter = DateFormatter() + formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss ZZ" + return formatter.string(from: date) } - var fileSize : Int64 { - return (self.archiveFileAttributes[.size] as! NSNumber).int64Value; + var fileSize: Int64 { + return (self.archiveFileAttributes[.size] as! NSNumber).int64Value } - - private var releaseNotesPath : URL? { - var basename = self.archivePath.deletingPathExtension(); + + private var releaseNotesPath: URL? { + var basename = self.archivePath.deletingPathExtension() if basename.pathExtension == "tar" { // tar.gz - basename = basename.deletingPathExtension(); + basename = basename.deletingPathExtension() } - let releaseNotes = basename.appendingPathExtension("html"); + let releaseNotes = basename.appendingPathExtension("html") if !FileManager.default.fileExists(atPath: releaseNotes.path) { - return nil; + return nil } - return releaseNotes; + return releaseNotes } private func getReleaseNotesAsHTMLFragment(_ path: URL) -> String? { @@ -163,29 +163,29 @@ class ArchiveItem: CustomStringConvertible { if html.utf8.count < 1000 && !html.localizedCaseInsensitiveContains(" XMLElement? { if let found = try? parent.nodes(forXPath: name) { if found.count > 0 { if let element = found[0] as? XMLElement { - return element; + return element } } } - return nil; + return nil } func findOrCreateElement(name: String, parent: XMLElement) -> XMLElement { if let element = findElement(name: name, parent: parent) { - return element; + return element } - let element = XMLElement(name: name); - parent.addChild(element); - return element; + let element = XMLElement(name: name) + parent.addChild(element) + return element } func text(_ text: String) -> XMLNode { return XMLNode.text(withStringValue: text) as! XMLNode } - func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { - let appBaseName = updates[0].appPath.deletingPathExtension().lastPathComponent; + let appBaseName = updates[0].appPath.deletingPathExtension().lastPathComponent - let sparkleNS = "http://www.andymatuschak.org/xml-namespaces/sparkle"; + let sparkleNS = "http://www.andymatuschak.org/xml-namespaces/sparkle" - var doc: XMLDocument; + var doc: XMLDocument do { let options: XMLNode.Options = [ XMLNode.Options.nodeLoadExternalEntitiesNever, XMLNode.Options.nodePreserveCDATA, XMLNode.Options.nodePreserveWhitespace, - ]; - doc = try XMLDocument(contentsOf: appcastDestPath, options: options); + ] + doc = try XMLDocument(contentsOf: appcastDestPath, options: options) } catch { - let root = XMLElement(name: "rss"); - root.addAttribute(XMLNode.attribute(withName: "xmlns:sparkle", stringValue: sparkleNS) as! XMLNode); - root.addAttribute(XMLNode.attribute(withName: "version", stringValue: "2.0") as! XMLNode); - doc = XMLDocument(rootElement: root); - doc.isStandalone = true; + let root = XMLElement(name: "rss") + root.addAttribute(XMLNode.attribute(withName: "xmlns:sparkle", stringValue: sparkleNS) as! XMLNode) + root.addAttribute(XMLNode.attribute(withName: "version", stringValue: "2.0") as! XMLNode) + doc = XMLDocument(rootElement: root) + doc.isStandalone = true } - var channel: XMLElement; + var channel: XMLElement - let rootNodes = try doc.nodes(forXPath: "/rss"); + let rootNodes = try doc.nodes(forXPath: "/rss") if rootNodes.count != 1 { - throw makeError(code: .appcastError, "Weird XML? \(appcastDestPath.path)"); + throw makeError(code: .appcastError, "Weird XML? \(appcastDestPath.path)") } let root = rootNodes[0] as! XMLElement - let channelNodes = try root.nodes(forXPath: "channel"); + let channelNodes = try root.nodes(forXPath: "channel") if channelNodes.count > 0 { - channel = channelNodes[0] as! XMLElement; + channel = channelNodes[0] as! XMLElement } else { - channel = XMLElement(name: "channel"); - channel.addChild(XMLElement.element(withName: "title", stringValue: appBaseName) as! XMLElement); - root.addChild(channel); + channel = XMLElement(name: "channel") + channel.addChild(XMLElement.element(withName: "title", stringValue: appBaseName) as! XMLElement) + root.addChild(channel) } - var numItems = 0; + var numItems = 0 for update in updates { - var item: XMLElement; - let existingItems = try channel.nodes(forXPath: "item[enclosure[@sparkle:version=\"\(update.version)\"]]"); - let createNewItem = existingItems.count == 0; + var item: XMLElement + let existingItems = try channel.nodes(forXPath: "item[enclosure[@sparkle:version=\"\(update.version)\"]]") + let createNewItem = existingItems.count == 0 // Update all old items, but aim for less than 5 in new feeds if createNewItem && numItems >= maxVersionsInFeed { - continue; + continue } - numItems += 1; + numItems += 1 if createNewItem { - item = XMLElement.element(withName: "item") as! XMLElement; - channel.addChild(item); + item = XMLElement.element(withName: "item") as! XMLElement + channel.addChild(item) } else { - item = existingItems[0] as! XMLElement; + item = existingItems[0] as! XMLElement } if nil == findElement(name: "title", parent: item) { - item.addChild(XMLElement.element(withName: "title", stringValue: update.shortVersion) as! XMLElement); + item.addChild(XMLElement.element(withName: "title", stringValue: update.shortVersion) as! XMLElement) } if nil == findElement(name: "pubDate", parent: item) { - item.addChild(XMLElement.element(withName: "pubDate", stringValue: update.pubDate) as! XMLElement); + item.addChild(XMLElement.element(withName: "pubDate", stringValue: update.pubDate) as! XMLElement) } if let html = update.releaseNotesHTML { - let descElement = findOrCreateElement(name: "description", parent: item); - let cdata = XMLNode(kind:.text, options:.nodeIsCDATA); - cdata.stringValue = html; - descElement.setChildren([cdata]); + let descElement = findOrCreateElement(name: "description", parent: item) + let cdata = XMLNode(kind: .text, options: .nodeIsCDATA) + cdata.stringValue = html + descElement.setChildren([cdata]) } - var minVer = findElement(name: SUAppcastElementMinimumSystemVersion, parent: item); + var minVer = findElement(name: SUAppcastElementMinimumSystemVersion, parent: item) if nil == minVer { - minVer = XMLElement.element(withName: SUAppcastElementMinimumSystemVersion, uri: sparkleNS) as? XMLElement; - item.addChild(minVer!); + minVer = XMLElement.element(withName: SUAppcastElementMinimumSystemVersion, uri: sparkleNS) as? XMLElement + item.addChild(minVer!) } - minVer?.setChildren([text(update.minimumSystemVersion)]); + minVer?.setChildren([text(update.minimumSystemVersion)]) let releaseNotesXpath = "\(SUAppcastElementReleaseNotesLink)" let results = ((try? item.nodes(forXPath: releaseNotesXpath)) as? [XMLElement])? @@ -116,10 +115,10 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { let relElement = results?.first if let url = update.releaseNotesURL { if nil == relElement { - item.addChild(XMLElement.element(withName: SUAppcastElementReleaseNotesLink, stringValue: url.absoluteString) as! XMLElement); + item.addChild(XMLElement.element(withName: SUAppcastElementReleaseNotesLink, stringValue: url.absoluteString) as! XMLElement) } } else if let childIndex = relElement?.index { - item.removeChild(at: childIndex); + item.removeChild(at: childIndex) } let languageNotesNodes = ((try? item.nodes(forXPath: releaseNotesXpath)) as? [XMLElement])? @@ -134,42 +133,42 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { let localizedNode = XMLNode.element(withName: SUAppcastElementReleaseNotesLink, children: [XMLNode.text(withStringValue: url.lastPathComponent) as! XMLNode], attributes: [XMLNode.attribute(withName: SUXMLLanguage, - stringValue: language) as! XMLNode]) + stringValue: language) as! XMLNode, ]) item.addChild(localizedNode as! XMLNode) } } - var enclosure = findElement(name: "enclosure", parent: item); + var enclosure = findElement(name: "enclosure", parent: item) if nil == enclosure { - enclosure = XMLElement.element(withName: "enclosure") as? XMLElement; - item.addChild(enclosure!); + enclosure = XMLElement.element(withName: "enclosure") as? XMLElement + item.addChild(enclosure!) } guard let archiveURL = update.archiveURL?.absoluteString else { - throw makeError(code: .appcastError, "Bad archive name or feed URL"); - }; + throw makeError(code: .appcastError, "Bad archive name or feed URL") + } var attributes = [ XMLNode.attribute(withName: "url", stringValue: archiveURL) as! XMLNode, XMLNode.attribute(withName: SUAppcastAttributeVersion, uri: sparkleNS, stringValue: update.version) as! XMLNode, XMLNode.attribute(withName: SUAppcastAttributeShortVersionString, uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, XMLNode.attribute(withName: "length", stringValue: String(update.fileSize)) as! XMLNode, XMLNode.attribute(withName: "type", stringValue: update.mimeType) as! XMLNode, - ]; + ] if let sig = update.edSignature { - attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode); + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } if let sig = update.dsaSignature { - attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode); + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } - enclosure!.attributes = attributes; + enclosure!.attributes = attributes if update.deltas.count > 0 { - var deltas = findElement(name: SUAppcastElementDeltas, parent: item); + var deltas = findElement(name: SUAppcastElementDeltas, parent: item) if nil == deltas { - deltas = XMLElement.element(withName: SUAppcastElementDeltas, uri: sparkleNS) as? XMLElement; - item.addChild(deltas!); + deltas = XMLElement.element(withName: SUAppcastElementDeltas, uri: sparkleNS) as? XMLElement + item.addChild(deltas!) } else { - deltas!.setChildren([]); + deltas!.setChildren([]) } for delta in update.deltas { var attributes = [ @@ -179,20 +178,20 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { XMLNode.attribute(withName: SUAppcastAttributeDeltaFrom, uri: sparkleNS, stringValue: delta.fromVersion) as! XMLNode, XMLNode.attribute(withName: "length", stringValue: String(delta.fileSize)) as! XMLNode, XMLNode.attribute(withName: "type", stringValue: "application/octet-stream") as! XMLNode, - ]; + ] if let sig = delta.edSignature { - attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode); + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } if let sig = delta.dsaSignature { - attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode); + attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } - deltas!.addChild(XMLNode.element(withName: "enclosure", children: nil, attributes: attributes) as! XMLElement); + deltas!.addChild(XMLNode.element(withName: "enclosure", children: nil, attributes: attributes) as! XMLElement) } } } - let options: XMLNode.Options = [.nodeCompactEmptyElement, .nodePrettyPrint]; - let docData = doc.xmlData(options:options); - let _ = try XMLDocument(data: docData, options:XMLNode.Options()); // Verify that it was generated correctly, which does not always happen! - try docData.write(to: appcastDestPath); + let options: XMLNode.Options = [.nodeCompactEmptyElement, .nodePrettyPrint] + let docData = doc.xmlData(options: options) + _ = try XMLDocument(data: docData, options: XMLNode.Options()); // Verify that it was generated correctly, which does not always happen! + try docData.write(to: appcastDestPath) } diff --git a/generate_appcast/Signatures.swift b/generate_appcast/Signatures.swift index e7f3adab..10cafed5 100644 --- a/generate_appcast/Signatures.swift +++ b/generate_appcast/Signatures.swift @@ -6,109 +6,109 @@ import Foundation struct PrivateKeys { - var privateDSAKey: SecKey?; - var privateEdKey: Data?; - var publicEdKey: Data?; + var privateDSAKey: SecKey? + var privateEdKey: Data? + var publicEdKey: Data? init(privateDSAKey: SecKey?, privateEdKey: Data?, publicEdKey: Data?) { - self.privateDSAKey = privateDSAKey; - self.privateEdKey = privateEdKey; - self.publicEdKey = publicEdKey; + self.privateDSAKey = privateDSAKey + self.privateEdKey = privateEdKey + self.publicEdKey = publicEdKey } } func loadPrivateDSAKey(at privateKeyURL: URL) throws -> SecKey { - let data = try Data(contentsOf: privateKeyURL); + let data = try Data(contentsOf: privateKeyURL) - var cfitems: CFArray? = nil; - var format = SecExternalFormat.formatOpenSSL; - var type = SecExternalItemType.itemTypePrivateKey; + var cfitems: CFArray? + var format = SecExternalFormat.formatOpenSSL + var type = SecExternalItemType.itemTypePrivateKey - let status = SecItemImport(data as CFData, nil, &format, &type, SecItemImportExportFlags(rawValue: UInt32(0)), nil, nil, &cfitems); - if (status != errSecSuccess || cfitems == nil) { - print("Private DSA key file", privateKeyURL.path, "exists, but it could not be read. SecItemImport error", status); - throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil); + let status = SecItemImport(data as CFData, nil, &format, &type, SecItemImportExportFlags(rawValue: UInt32(0)), nil, nil, &cfitems) + if status != errSecSuccess || cfitems == nil { + print("Private DSA key file", privateKeyURL.path, "exists, but it could not be read. SecItemImport error", status) + throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil) } - if (format != SecExternalFormat.formatOpenSSL || type != SecExternalItemType.itemTypePrivateKey) { - throw makeError(code: .signatureError, "Not an OpensSSL private key \(format) \(type)"); + if format != SecExternalFormat.formatOpenSSL || type != SecExternalItemType.itemTypePrivateKey { + throw makeError(code: .signatureError, "Not an OpensSSL private key \(format) \(type)") } - return (cfitems! as NSArray)[0] as! SecKey; + return (cfitems! as NSArray)[0] as! SecKey } func loadPrivateDSAKey(named keyName: String, fromKeychainAt keychainURL: URL) throws -> SecKey { - var keychain: SecKeychain? = nil - + var keychain: SecKeychain? + guard SecKeychainOpen(keychainURL.path, &keychain) == errSecSuccess, keychain != nil else { throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil) } - + let query: [CFString: CFTypeRef] = [ kSecClass: kSecClassKey, kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrLabel: keyName as CFString, kSecMatchLimit: kSecMatchLimitOne, kSecUseKeychain: keychain!, - kSecReturnRef: kCFBooleanTrue + kSecReturnRef: kCFBooleanTrue, ] - - var item: CFTypeRef? = nil + + var item: CFTypeRef? guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, item != nil else { throw NSError(domain: SUSparkleErrorDomain, code: Int(OSStatus(SUError.signatureError.rawValue)), userInfo: nil) } - + return item! as! SecKey } func dsaSignature(path: URL, privateDSAKey: SecKey) throws -> String { - var error: Unmanaged?; + var error: Unmanaged? - let stream = InputStream(fileAtPath:path.path)!; - let dataReadTransform = SecTransformCreateReadTransformWithReadStream(stream); + let stream = InputStream(fileAtPath: path.path)! + let dataReadTransform = SecTransformCreateReadTransformWithReadStream(stream) - let dataDigestTransform = SecDigestTransformCreate(kSecDigestSHA1, 20, nil); + let dataDigestTransform = SecDigestTransformCreate(kSecDigestSHA1, 20, nil) guard let dataSignTransform = SecSignTransformCreate(privateDSAKey, &error) else { - print("can't use the key"); - throw error!.takeRetainedValue(); + print("can't use the key") + throw error!.takeRetainedValue() } - let group = SecTransformCreateGroupTransform(); - SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error); - if (error != nil) { - throw error!.takeRetainedValue(); + let group = SecTransformCreateGroupTransform() + SecTransformConnectTransforms(dataReadTransform, kSecTransformOutputAttributeName, dataDigestTransform, kSecTransformInputAttributeName, group, &error) + if error != nil { + throw error!.takeRetainedValue() } - SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataSignTransform, kSecTransformInputAttributeName, group, &error); - if (error != nil) { - throw error!.takeRetainedValue(); + SecTransformConnectTransforms(dataDigestTransform, kSecTransformOutputAttributeName, dataSignTransform, kSecTransformInputAttributeName, group, &error) + if error != nil { + throw error!.takeRetainedValue() } - let result = SecTransformExecute(group, &error); - if (error != nil) { - throw error!.takeRetainedValue(); + let result = SecTransformExecute(group, &error) + if error != nil { + throw error!.takeRetainedValue() } guard let resultData = result as? Data else { - throw makeError(code: .signatureError, "SecTransformExecute returned non-data"); + throw makeError(code: .signatureError, "SecTransformExecute returned non-data") } - return resultData.base64EncodedString(); + return resultData.base64EncodedString() } func edSignature(path: URL, publicEdKey: Data, privateEdKey: Data) throws -> String { assert(publicEdKey.count == 32) assert(privateEdKey.count == 64) - let data = try Data.init(contentsOf: path, options: .mappedIfSafe); - let len = data.count; - var output = Data(count: 64); + let data = try Data.init(contentsOf: path, options: .mappedIfSafe) + let len = data.count + var output = Data(count: 64) output.withUnsafeMutableBytes({ (output: UnsafeMutablePointer) in data.withUnsafeBytes({ (data: UnsafePointer) in publicEdKey.withUnsafeBytes({ (publicEdKey: UnsafePointer) in privateEdKey.withUnsafeBytes({ (privateEdKey: UnsafePointer) in ed25519_sign(output, data, len, publicEdKey, privateEdKey) - }); - }); + }) + }) }) - }); - return output.base64EncodedString(); + }) + return output.base64EncodedString() } diff --git a/generate_appcast/URL+Hashing.swift b/generate_appcast/URL+Hashing.swift index 9f18532d..d3bcc18e 100644 --- a/generate_appcast/URL+Hashing.swift +++ b/generate_appcast/URL+Hashing.swift @@ -24,7 +24,7 @@ extension FileHandle { guard data.count > 0 else { break } - let _ = data.withUnsafeBytes { + _ = data.withUnsafeBytes { CC_SHA256_Update(&context, $0.baseAddress, numericCast($0.count)) } } diff --git a/generate_appcast/Unarchive.swift b/generate_appcast/Unarchive.swift index 53a6b868..16bcc33a 100644 --- a/generate_appcast/Unarchive.swift +++ b/generate_appcast/Unarchive.swift @@ -5,59 +5,59 @@ import Foundation -func unarchive(itemPath:URL, archiveDestDir: URL, callback: @escaping (Error?) -> Void) { - let fileManager = FileManager.default; - let tempDir = archiveDestDir.appendingPathExtension("tmp"); - let itemCopy = tempDir.appendingPathComponent(itemPath.lastPathComponent); +func unarchive(itemPath: URL, archiveDestDir: URL, callback: @escaping (Error?) -> Void) { + let fileManager = FileManager.default + let tempDir = archiveDestDir.appendingPathExtension("tmp") + let itemCopy = tempDir.appendingPathComponent(itemPath.lastPathComponent) - _ = try? fileManager.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: [:]); + _ = try? fileManager.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: [:]) do { do { - try fileManager.linkItem(at: itemPath, to: itemCopy); + try fileManager.linkItem(at: itemPath, to: itemCopy) } catch { - try fileManager.copyItem(at: itemPath, to: itemCopy); + try fileManager.copyItem(at: itemPath, to: itemCopy) } - if let unarchiver = SUUnarchiver.unarchiver(forPath: itemCopy.path, updatingHostBundlePath:nil, decryptionPassword:nil) { + if let unarchiver = SUUnarchiver.unarchiver(forPath: itemCopy.path, updatingHostBundlePath: nil, decryptionPassword: nil) { unarchiver.unarchive(completionBlock: { (error: Error?) in if error != nil { - callback(error); - return; + callback(error) + return } - _ = try? fileManager.removeItem(at: itemCopy); + _ = try? fileManager.removeItem(at: itemCopy) do { - try fileManager.moveItem(at: tempDir, to: archiveDestDir); - callback(nil); + try fileManager.moveItem(at: tempDir, to: archiveDestDir) + callback(nil) } catch { - callback(error); + callback(error) } }, progressBlock: nil) } else { - _ = try? fileManager.removeItem(at: itemCopy); - callback(makeError(code: .unarchivingError, "Not a supported archive format: \(itemCopy)")); + _ = try? fileManager.removeItem(at: itemCopy) + callback(makeError(code: .unarchivingError, "Not a supported archive format: \(itemCopy)")) } } catch { - _ = try? fileManager.removeItem(at: tempDir); - callback(error); + _ = try? fileManager.removeItem(at: tempDir) + callback(error) } } func unarchiveUpdates(archivesSourceDir: URL, archivesDestDir: URL, verbose: Bool) throws -> [ArchiveItem] { if verbose { - print("Unarchiving to temp directory", archivesDestDir.path); + print("Unarchiving to temp directory", archivesDestDir.path) } - let group = DispatchGroup(); + let group = DispatchGroup() - let fileManager = FileManager.default; + let fileManager = FileManager.default - var unarchived:[ArchiveItem] = []; + var unarchived: [ArchiveItem] = [] - let dir = try fileManager.contentsOfDirectory(atPath: archivesSourceDir.path); - var running = 0; + let dir = try fileManager.contentsOfDirectory(atPath: archivesSourceDir.path) + var running = 0 for item in dir.filter({ !$0.hasPrefix(".") && !$0.hasSuffix(".delta") && !$0.hasSuffix(".xml") && !$0.hasSuffix(".html") }) { - let itemPath = archivesSourceDir.appendingPathComponent(item); + let itemPath = archivesSourceDir.appendingPathComponent(item) let archiveDestDir: URL if let hash = itemPath.sha256String() { @@ -66,50 +66,50 @@ func unarchiveUpdates(archivesSourceDir: URL, archivesDestDir: URL, verbose: Boo archiveDestDir = archivesDestDir.appendingPathComponent(itemPath.lastPathComponent) } - var isDir:ObjCBool = false; - if (fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir) && isDir.boolValue) { - continue; + var isDir: ObjCBool = false + if fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir) && isDir.boolValue { + continue } let addItem = { do { - let item = try ArchiveItem(fromArchive: itemPath, unarchivedDir: archiveDestDir); + let item = try ArchiveItem(fromArchive: itemPath, unarchivedDir: archiveDestDir) if verbose { - print("Found archive", item); + print("Found archive", item) } - objc_sync_enter(unarchived); - unarchived.append(item); - objc_sync_exit(unarchived); + objc_sync_enter(unarchived) + unarchived.append(item) + objc_sync_exit(unarchived) } catch { if verbose { - print("Skipped", item, error); + print("Skipped", item, error) } } } if fileManager.fileExists(atPath: archiveDestDir.path) { - addItem(); + addItem() } else { - group.enter(); + group.enter() unarchive(itemPath: itemPath, archiveDestDir: archiveDestDir) { (error: Error?) in if let error = error { - print("Could not unarchive", itemPath.path, error); + print("Could not unarchive", itemPath.path, error) } else { - addItem(); + addItem() } - group.leave(); + group.leave() } } // Crude limit of concurrency - running += 1; + running += 1 if running >= 8 { - running = 0; - group.wait(); + running = 0 + group.wait() } } - group.wait(); + group.wait() - return unarchived; + return unarchived } diff --git a/generate_appcast/main.swift b/generate_appcast/main.swift index 33c0a7ec..299ee275 100644 --- a/generate_appcast/main.swift +++ b/generate_appcast/main.swift @@ -8,10 +8,10 @@ import Foundation -var verbose = false; +var verbose = false func printUsage() { - let command = URL(fileURLWithPath: CommandLine.arguments.first!).lastPathComponent; + let command = URL(fileURLWithPath: CommandLine.arguments.first!).lastPathComponent print("Generate appcast from a directory of Sparkle update archives\n", "Usage:\n", " \(command) \n", @@ -26,7 +26,7 @@ func printUsage() { } func printHelp() { - let command = URL(fileURLWithPath: CommandLine.arguments.first!).lastPathComponent; + let command = URL(fileURLWithPath: CommandLine.arguments.first!).lastPathComponent print( "Usage: \(command) [OPTIONS] [ARCHIVES_FOLDER]\n", "Options:\n", @@ -39,9 +39,9 @@ func printHelp() { } func loadPrivateKeys(_ privateDSAKey: SecKey?, _ privateEdString: String?) -> PrivateKeys { - var privateEdKey: Data?; - var publicEdKey: Data?; - var item: CFTypeRef?; + var privateEdKey: Data? + var publicEdKey: Data? + var item: CFTypeRef? var keys: Data? // private + public key is provided as argument @@ -49,7 +49,7 @@ func loadPrivateKeys(_ privateDSAKey: SecKey?, _ privateEdString: String?) -> Pr if privateEdString.count == 128, let data = Data(base64Encoded: privateEdString) { keys = data } else { - print("Warning: Private key not found in the argument. Please provide a valid key."); + print("Warning: Private key not found in the argument. Please provide a valid key.") } } // get keys from kechain instead @@ -60,19 +60,19 @@ func loadPrivateKeys(_ privateDSAKey: SecKey?, _ privateEdString: String?) -> Pr kSecAttrAccount as String: "ed25519", kSecAttrProtocol as String: kSecAttrProtocolSSH, kSecReturnData as String: kCFBooleanTrue, - ] as CFDictionary, &item); + ] as CFDictionary, &item) if res == errSecSuccess, let encoded = item as? Data, let data = Data(base64Encoded: encoded) { keys = data } else { - print("Warning: Private key not found in the Keychain (\(res)). Please run the generate_keys tool"); + print("Warning: Private key not found in the Keychain (\(res)). Please run the generate_keys tool") } } if let keys = keys { - privateEdKey = keys[0..<64]; - publicEdKey = keys[64...]; + privateEdKey = keys[0..<64] + publicEdKey = keys[64...] } - return PrivateKeys(privateDSAKey: privateDSAKey, privateEdKey: privateEdKey, publicEdKey: publicEdKey); + return PrivateKeys(privateDSAKey: privateDSAKey, privateEdKey: privateEdKey, publicEdKey: publicEdKey) } /** @@ -84,18 +84,18 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, printHelp() exit(1) } - + // make a mutable copy of the argument list var arguments = argumentList // remove the first element since this is the path to executable which we don't need arguments.removeFirst() - + // define the variables for the possible argument values - var privateDSAKey: SecKey? = nil - var privateEdString: String? = nil - var downloadUrlPrefix: URL? = nil + var privateDSAKey: SecKey? + var privateEdString: String? + var downloadUrlPrefix: URL? var archivesSourceDir: URL - + // check if the private dsa key option is present if let privateDSAKeyOptionIndex = arguments.firstIndex(of: "-f") { // check that when accessing the value of the option we don't get out of bounds @@ -103,7 +103,7 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, print("Too few arguments were given") exit(1) } - + // get the private DSA key let privateKeyUrl = URL(fileURLWithPath: arguments[privateDSAKeyOptionIndex + 1]) do { @@ -112,12 +112,12 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, print("Unable to load DSA private key from", privateKeyUrl.path, "\n", error) exit(1) } - + // remove the already parsed arguments arguments.remove(at: privateDSAKeyOptionIndex) arguments.remove(at: privateDSAKeyOptionIndex + 1) } - + // check if the private dsa sould be loaded using the keyname and the name of the keychain if let keyNameOptionIndex = arguments.firstIndex(of: "-n"), let keychainNameOptionIndex = arguments.firstIndex(of: "-k") { // check that when accessing one of the values of the options we don't get out of bounds @@ -125,7 +125,7 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, print("Too few arguments were given") exit(1) } - + // get the keyname and the keychain url to load the private DSA key let keyName: String = arguments[keyNameOptionIndex + 1] let keychainUrl: URL = URL(fileURLWithPath: arguments[keychainNameOptionIndex + 1]) @@ -135,14 +135,14 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, print("Unable to load DSA private key '\(keyName)' from keychain at", keychainUrl.path, "\n", error) exit(1) } - + // remove the already parsed arguments arguments.remove(at: keyNameOptionIndex + 1) arguments.remove(at: keyNameOptionIndex) arguments.remove(at: arguments.firstIndex(of: "-k")! + 1) arguments.remove(at: keychainNameOptionIndex) } - + // check if the private EdDSA key string was given as an argument if let privateEdDSAKeyOptionIndex = arguments.firstIndex(of: "-s") { // check that when accessing the value of the option we don't get out of bounds @@ -150,15 +150,15 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, print("Too few arguments were given") exit(1) } - + // get the private EdDSA key string privateEdString = arguments[privateEdDSAKeyOptionIndex + 1] - + // remove the already parsed argument arguments.remove(at: privateEdDSAKeyOptionIndex + 1) arguments.remove(at: privateEdDSAKeyOptionIndex) } - + // check if a prefix for the download url of the archives was given if let downloadUrlPrefixOptionIndex = arguments.firstIndex(of: "--download-url-prefix") { // check that when accessing the value of the option we don't get out of bounds @@ -166,15 +166,15 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, print("Too few arguments were given") exit(1) } - + // get the download url prefix downloadUrlPrefix = URL(string: arguments[downloadUrlPrefixOptionIndex + 1]) - + // remove the parsed argument arguments.remove(at: downloadUrlPrefixOptionIndex + 1) arguments.remove(at: downloadUrlPrefixOptionIndex) } - + // now that all command line options have been removed from the arguments array // there should only be the path to the private DSA key (if provided) path to the archives dir left if arguments.count == 2 { @@ -187,36 +187,36 @@ func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, print("Unable to load DSA private key from", privateKeyUrl.path, "\n", error) exit(1) } - + // remove the parsed path to the DSA key arguments.removeFirst() } // now only the archives source dir is left archivesSourceDir = URL(fileURLWithPath: arguments[0], isDirectory: true) - + return (privateDSAKey, privateEdString, downloadUrlPrefix, archivesSourceDir) } func main() { - let args = CommandLine.arguments; + let args = CommandLine.arguments if args.count < 2 { printUsage() exit(1) } - - var privateDSAKey: SecKey? = nil; - var privateEdString: String? = nil; - var downloadUrlPrefix: URL? = nil; + + var privateDSAKey: SecKey? + var privateEdString: String? + var downloadUrlPrefix: URL? var archivesSourceDir: URL - + (privateDSAKey, privateEdString, downloadUrlPrefix, archivesSourceDir) = parseCommandLineOptions(argumentList: args) - + let keys = loadPrivateKeys(privateDSAKey, privateEdString) do { - let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, keys: keys, verbose:verbose); - + let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, keys: keys, verbose: verbose) + // if a download url prefix was provided set it for each archive item if downloadUrlPrefix != nil { for (_, archiveItems) in allUpdates { @@ -225,21 +225,21 @@ func main() { } } } - + for (appcastFile, updates) in allUpdates { - let appcastDestPath = URL(fileURLWithPath: appcastFile, relativeTo: archivesSourceDir); - try writeAppcast(appcastDestPath:appcastDestPath, updates:updates); - print("Written", appcastDestPath.path, "based on", updates.count, "updates"); + let appcastDestPath = URL(fileURLWithPath: appcastFile, relativeTo: archivesSourceDir) + try writeAppcast(appcastDestPath: appcastDestPath, updates: updates) + print("Written", appcastDestPath.path, "based on", updates.count, "updates") } } catch { - print("Error generating appcast from directory", archivesSourceDir.path, "\n", error); - exit(1); + print("Error generating appcast from directory", archivesSourceDir.path, "\n", error) + exit(1) } } DispatchQueue.global().async(execute: { - main(); - CFRunLoopStop(CFRunLoopGetMain()); -}); + main() + CFRunLoopStop(CFRunLoopGetMain()) +}) -CFRunLoopRun(); +CFRunLoopRun() diff --git a/generate_keys/main.swift b/generate_keys/main.swift index 6aa89e8f..e6f84b75 100644 --- a/generate_keys/main.swift +++ b/generate_keys/main.swift @@ -10,52 +10,49 @@ import Foundation import Security func findPublicKey() -> Data? { - var item: CFTypeRef?; + var item: CFTypeRef? let res = SecItemCopyMatching([ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "https://sparkle-project.org", kSecAttrAccount as String: "ed25519", kSecAttrProtocol as String: kSecAttrProtocolSSH, kSecReturnData as String: kCFBooleanTrue, - ] as CFDictionary, &item); + ] as CFDictionary, &item) if res == errSecSuccess, let encoded = item as? Data, let keys = Data(base64Encoded: encoded) { - print("OK! Read the existing key saved in the Keychain."); + print("OK! Read the existing key saved in the Keychain.") return keys[64...] - } - else if res == errSecItemNotFound { - return nil; - } - else if res == errSecAuthFailed { - print("\nERROR! Access denied. Can't check existing keys in the keychain."); - print("Go to Keychain Access.app, lock the login keychain, then unlock it again."); - } - else if res == errSecUserCanceled { - print("\nABORTED! You've cancelled the request to read the key from the Keychain. Please run the tool again."); + } else if res == errSecItemNotFound { + return nil + } else if res == errSecAuthFailed { + print("\nERROR! Access denied. Can't check existing keys in the keychain.") + print("Go to Keychain Access.app, lock the login keychain, then unlock it again.") + } else if res == errSecUserCanceled { + print("\nABORTED! You've cancelled the request to read the key from the Keychain. Please run the tool again.") } else if res == errSecInteractionNotAllowed { - print("\nERROR! The operating system has blocked access to the Keychain."); + print("\nERROR! The operating system has blocked access to the Keychain.") } else { - print("\nERROR! Unable to access existing item in the Keychain", res, "(you can look it up at osstatus.com)"); + print("\nERROR! Unable to access existing item in the Keychain", res, "(you can look it up at osstatus.com)") } exit(1) } func generateKeyPair() -> Data { - var seed = Data(count: 32); - var publicEdKey = Data(count: 32); - var privateEdKey = Data(count: 64); + var seed = Data(count: 32) + var publicEdKey = Data(count: 32) + var privateEdKey = Data(count: 64) if !seed.withUnsafeMutableBytes { (seed: UnsafeMutablePointer) in 0 == ed25519_create_seed(seed)} { - print("\nERROR: Unable to initialize random seed"); + print("\nERROR: Unable to initialize random seed") exit(1) } seed.withUnsafeBytes({(seed: UnsafePointer) in publicEdKey.withUnsafeMutableBytes({(publicEdKey: UnsafeMutablePointer) in privateEdKey.withUnsafeMutableBytes({(privateEdKey: UnsafeMutablePointer) in - ed25519_create_keypair(publicEdKey, privateEdKey, seed); - }); - }); - }); + ed25519_create_keypair(publicEdKey, privateEdKey, seed) + }) + }) + }) let bothKeys = privateEdKey + publicEdKey; // public key can't be derived from the private one let query = [ @@ -71,24 +68,23 @@ func generateKeyPair() -> Data { kSecAttrLabel as String: "Private key for signing Sparkle updates", kSecAttrComment as String: "Public key (SUPublicEDKey value) for this key is:\n\n\(publicEdKey.base64EncodedString())", kSecAttrDescription as String: "private key", - ] as CFDictionary; - let res = SecItemAdd(query, nil); + ] as CFDictionary + let res = SecItemAdd(query, nil) if res == errSecSuccess { - print("OK! A new key has been generated and saved in the Keychain."); - } - else if res == errSecDuplicateItem { - print("\nERROR: You already have a previously generated key in the Keychain"); + print("OK! A new key has been generated and saved in the Keychain.") + } else if res == errSecDuplicateItem { + print("\nERROR: You already have a previously generated key in the Keychain") } else if res == errSecAuthFailed { - print("\nERROR: System denied access to the Keychain. Unable to save the new key"); - print("Go to Keychain Access.app, lock the login keychain, then unlock it again."); + print("\nERROR: System denied access to the Keychain. Unable to save the new key") + print("Go to Keychain Access.app, lock the login keychain, then unlock it again.") } else { - print("\nERROR: The key could not be saved to the Keychain. error: \(res) (you can look it up at osstatus.com)"); + print("\nERROR: The key could not be saved to the Keychain. error: \(res) (you can look it up at osstatus.com)") } - exit(1); + exit(1) } print("This tool uses macOS Keychain to store the Sparkle private key.") print("If the Keychain prompts you for permission, please allow it.") -let pubKey = findPublicKey() ?? generateKeyPair(); +let pubKey = findPublicKey() ?? generateKeyPair() print("\nIn your app's Info.plist set SUPublicEDKey to:\n\(pubKey.base64EncodedString())\n") diff --git a/sign_update/main.swift b/sign_update/main.swift index 76e67a21..ffa3eb5a 100644 --- a/sign_update/main.swift +++ b/sign_update/main.swift @@ -18,30 +18,27 @@ func parseKeysFromString(_ string: String) -> (Data, Data) { return (keys[0..<64], keys[64...]) } func findKeys() -> (Data, Data) { - var item: CFTypeRef?; + var item: CFTypeRef? let res = SecItemCopyMatching([ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "https://sparkle-project.org", kSecAttrAccount as String: "ed25519", kSecAttrProtocol as String: kSecAttrProtocolSSH, kSecReturnData as String: kCFBooleanTrue, - ] as CFDictionary, &item); + ] as CFDictionary, &item) if res == errSecSuccess, let encoded = item as? Data, let keys = Data(base64Encoded: encoded) { return (keys[0..<64], keys[64..<(64+32)]) - } - else if res == errSecItemNotFound { - print("ERROR! Signing key not found. Please run generate_keys tool first."); - } - else if res == errSecAuthFailed { - print("ERROR! Access denied. Can't get keys from the keychain."); - print("Go to Keychain Access.app, lock the login keychain, then unlock it again."); - } - else if res == errSecUserCanceled { - print("ABORTED! You've cancelled the request to read the key from the Keychain. Please run the tool again."); + } else if res == errSecItemNotFound { + print("ERROR! Signing key not found. Please run generate_keys tool first.") + } else if res == errSecAuthFailed { + print("ERROR! Access denied. Can't get keys from the keychain.") + print("Go to Keychain Access.app, lock the login keychain, then unlock it again.") + } else if res == errSecUserCanceled { + print("ABORTED! You've cancelled the request to read the key from the Keychain. Please run the tool again.") } else if res == errSecInteractionNotAllowed { - print("ERROR! The operating system has blocked access to the Keychain."); + print("ERROR! The operating system has blocked access to the Keychain.") } else { - print("ERROR! Unable to access required key in the Keychain", res, "(you can look it up at osstatus.com)"); + print("ERROR! Unable to access required key in the Keychain", res, "(you can look it up at osstatus.com)") } exit(1) } @@ -49,24 +46,24 @@ func findKeys() -> (Data, Data) { func edSignature(data: Data, publicEdKey: Data, privateEdKey: Data) -> String { assert(publicEdKey.count == 32) assert(privateEdKey.count == 64) - let len = data.count; - var output = Data(count: 64); + let len = data.count + var output = Data(count: 64) output.withUnsafeMutableBytes({ (output: UnsafeMutablePointer) in data.withUnsafeBytes({ (data: UnsafePointer) in publicEdKey.withUnsafeBytes({ (publicEdKey: UnsafePointer) in privateEdKey.withUnsafeBytes({ (privateEdKey: UnsafePointer) in ed25519_sign(output, data, len, publicEdKey, privateEdKey) - }); - }); + }) + }) }) - }); - return output.base64EncodedString(); + }) + return output.base64EncodedString() } -let args = CommandLine.arguments; +let args = CommandLine.arguments if args.count != 2 && !(args.count == 4 && args[1] == "-s") { print("Usage: \n") - print("\t1. \(args[0]) \n\tPrivate EdDSA (ed25519) key is automatically read from the Keychain.\n"); + print("\t1. \(args[0]) \n\tPrivate EdDSA (ed25519) key is automatically read from the Keychain.\n") print("\t2 \(args[0]) -s \n\tThe key's length is 128 that includes private and public key.\n") exit(1) } @@ -74,9 +71,9 @@ let (priv, pub) = args.count == 2 ? findKeys() : parseKeysFromString(args[2]) let filePath = args.count == 2 ? args[1] : args[3] do { - let data = try Data.init(contentsOf: URL.init(fileURLWithPath: filePath), options: .mappedIfSafe); - let sig = edSignature(data:data , publicEdKey: pub, privateEdKey: priv); - print("sparkle:edSignature=\"\(sig)\" length=\"\(data.count)\""); + let data = try Data.init(contentsOf: URL.init(fileURLWithPath: filePath), options: .mappedIfSafe) + let sig = edSignature(data: data, publicEdKey: pub, privateEdKey: priv) + print("sparkle:edSignature=\"\(sig)\" length=\"\(data.count)\"") } catch { print("ERROR: ", error) } From e9ab9d09a5d52f53a1be1de4d523f45d6f91aa2a Mon Sep 17 00:00:00 2001 From: Rajiv Shah Date: Mon, 25 May 2020 17:23:20 -0400 Subject: [PATCH 3/4] Relax rules a bit --- .swiftlint.yml | 11 +++++++++++ Tests/SUUnarchiverTest.swift | 1 + generate_appcast/ArchiveItem.swift | 1 + 3 files changed, 13 insertions(+) diff --git a/.swiftlint.yml b/.swiftlint.yml index bf68de16..1bbdd813 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -3,7 +3,18 @@ excluded: disabled_rules: - opening_brace - empty_parentheses_with_trailing_closure + - function_body_length + - line_length + - cyclomatic_complexity + - large_tuple # Rule-specific config trailing_comma: mandatory_comma: true +force_try: + severity: warning +force_cast: + severity: warning +identifier_name: + min_length: + warning: 2 diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index c198c523..37c85870 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -47,6 +47,7 @@ class SUUnarchiverTest: XCTestCase }, progressBlock: nil) } + // swiftlint:disable function_parameter_count func unarchiveTestSuccessAppWithExtension(_ archiveExtension: String, appName: String, tempDirectoryURL: URL, tempArchiveURL: URL, archiveResourceURL: URL, password: String?, testExpectation: XCTestExpectation) { let fileManager = FileManager.default diff --git a/generate_appcast/ArchiveItem.swift b/generate_appcast/ArchiveItem.swift index f86ce470..ba7726f3 100644 --- a/generate_appcast/ArchiveItem.swift +++ b/generate_appcast/ArchiveItem.swift @@ -34,6 +34,7 @@ class DeltaUpdate { class ArchiveItem: CustomStringConvertible { let version: String + // swiftlint:disable identifier_name let _shortVersion: String? let minimumSystemVersion: String let archivePath: URL From 0090aa227b35e37d0a73cf59b99a8a3c370c228f Mon Sep 17 00:00:00 2001 From: Rajiv Shah Date: Mon, 25 May 2020 17:29:30 -0400 Subject: [PATCH 4/4] Allow force tries and force casts in tests --- Tests/.swiftlint.yml | 4 ++++ UITests/.swiftlint.yml | 4 ++++ 2 files changed, 8 insertions(+) create mode 100644 Tests/.swiftlint.yml create mode 100644 UITests/.swiftlint.yml diff --git a/Tests/.swiftlint.yml b/Tests/.swiftlint.yml new file mode 100644 index 00000000..e8ecab25 --- /dev/null +++ b/Tests/.swiftlint.yml @@ -0,0 +1,4 @@ +# Inherits from top level config +disabled_rules: + - force_try + - force_cast diff --git a/UITests/.swiftlint.yml b/UITests/.swiftlint.yml new file mode 100644 index 00000000..e8ecab25 --- /dev/null +++ b/UITests/.swiftlint.yml @@ -0,0 +1,4 @@ +# Inherits from top level config +disabled_rules: + - force_try + - force_cast