From 06629310e22c68ea1a8c833848ea87c3a6e8acc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sun, 22 Jan 2017 18:40:39 +0000 Subject: [PATCH 01/39] Updated changelog --- CHANGELOG | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 0683644b..4ef29c87 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,16 @@ +# 1.17.0 + + * Added Touch Bar support (Bi11) + * Upgraded SULog to use logging APIs that Apple provides built-in (Zorg) + * Skip buttons are disabled if the update is marked as critical (Kornel Lesiński) + * Backround updates ask OS for lower-priority networking (Kornel Lesiński) + * Refactorings to sync with upcoming 2.0 + * Added kqueue based termination listener (Zorg) + * Added AppKit prevention guards to modules that shouldn't import it (Zorg) + * Added Obj-C generics where applicable (Zorg) + * Made SUBundleIcon & SUApplicationInfo take SUHost, not NSBundle (Zorg) + * Improved -[SUHost objectForInfoDictionaryKey:] (Zorg) + # 1.16.0 * Guided package installs are now the default for updating packages (Zorg) From c0d45952a9487066eff8239780b78a2092b3b028 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Mon, 23 Jan 2017 01:20:46 +0000 Subject: [PATCH 02/39] Removed unimportant changelog entry --- CHANGELOG | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index 0683644b..76961860 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -7,7 +7,6 @@ * Made manual check resume pending automatic updates instead of starting a new update (Kornel Lesiński) * Started using `length` value from RSS if HTTP doesn't give one (Zorg) * Hidden automatic updates checkbox for information only updates (Bi11) - * Fixed UI update scheduler not prompting for install & relaunch (Zorg) * Added progressbar for DMG and binary delta extraction (Kornel Lesiński) * Fixed showing of download status if we attempt a 2nd download (Zorg) * Refactorings to sync with upcoming 2.0 From c61767f501385b2891e769cdb8da52e2e57ec32c Mon Sep 17 00:00:00 2001 From: Zorg Date: Sun, 22 Jan 2017 22:02:45 -0500 Subject: [PATCH 03/39] Don't remove the temporary unarchive directory in unit tests This should fix a potential bug where the unit tests try to unarchive a file that does not exist. --- Tests/SUUnarchiverTest.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index dcd6028a..3ce04f5b 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -16,10 +16,10 @@ class SUUnarchiverTest: XCTestCase 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) - defer { - try! fileManager.removeItem(at: tempDirectoryURL) - } let unarchivedSuccessExpectation = super.expectation(description: "Unarchived Success (format: \(archiveExtension))") let unarchivedFailureExpectation = super.expectation(description: "Unarchived Failure (format: \(archiveExtension))") From e4821e045493597085fca0a8a1f0b004dfde5b07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 24 Jan 2017 13:29:30 +0000 Subject: [PATCH 04/39] Ability to report installation progress --- Sparkle/Autoupdate/Autoupdate.m | 10 ++++++++-- Sparkle/SUGuidedPackageInstaller.m | 2 +- Sparkle/SUInstallerProtocol.h | 2 +- Sparkle/SUPackageInstaller.m | 2 +- Sparkle/SUPlainInstaller.m | 6 +++--- Tests/SUInstallerTest.m | 2 +- 6 files changed, 15 insertions(+), 9 deletions(-) diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 0849ba0d..44cf3a59 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -136,7 +136,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; self.statusController = [[SUStatusController alloc] initWithHost:host]; [self.statusController setButtonTitle:SULocalizedString(@"Cancel Update", @"") target:nil action:Nil isDefault:NO]; [self.statusController beginActionWithTitle:SULocalizedString(@"Installing update...", @"") - maxProgressValue: 0 statusText: @""]; + maxProgressValue:100 statusText: @""]; [self.statusController showWindow:self]; } @@ -151,8 +151,14 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; return; } + void(^progressBlock)(double) = ^(double progress){ + dispatch_async(dispatch_get_main_queue(), ^(){ + self.statusController.progressValue = progress * 100.0; + }); + }; + NSError *finalInstallationError = nil; - if (![installer performFinalInstallation:&finalInstallationError]) { + if (![installer performFinalInstallationProgressBlock:progressBlock error:&finalInstallationError]) { NSError *underlyingError = [finalInstallationError.userInfo objectForKey:NSUnderlyingErrorKey]; dispatch_async(dispatch_get_main_queue(), ^{ if (underlyingError == nil || underlyingError.code != SUInstallationCancelledError) { diff --git a/Sparkle/SUGuidedPackageInstaller.m b/Sparkle/SUGuidedPackageInstaller.m index cea993a2..bd753f1c 100644 --- a/Sparkle/SUGuidedPackageInstaller.m +++ b/Sparkle/SUGuidedPackageInstaller.m @@ -42,7 +42,7 @@ return YES; } -- (BOOL)performFinalInstallation:(NSError * __autoreleasing *)error +- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))progressBlock error:(NSError * __autoreleasing *)error { SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:self.fileOperationToolPath]; diff --git a/Sparkle/SUInstallerProtocol.h b/Sparkle/SUInstallerProtocol.h index 4e07bbd2..75312c47 100644 --- a/Sparkle/SUInstallerProtocol.h +++ b/Sparkle/SUInstallerProtocol.h @@ -21,7 +21,7 @@ NS_ASSUME_NONNULL_BEGIN // Any installation work after the user application has been terminated. This is where the final installation work can be done. // After this stage is done, the user application may be relaunched. // Should be able to be called from non-main thread -- (BOOL)performFinalInstallation:(NSError **)error; +- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError **)error; // Indicates whether or not this installer can install the update silently in the background, without hindering the user // Should be thread safe diff --git a/Sparkle/SUPackageInstaller.m b/Sparkle/SUPackageInstaller.m index 92654742..251a0561 100644 --- a/Sparkle/SUPackageInstaller.m +++ b/Sparkle/SUPackageInstaller.m @@ -49,7 +49,7 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open"; return YES; } -- (BOOL)performFinalInstallation:(NSError * __autoreleasing *)error +- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))__unused cb error:(NSError *__autoreleasing*)error { // Run installer using the "open" command to ensure it is launched in front of current application. // -W = wait until the app has quit. diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index 81ee5cfd..74a480b1 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -61,7 +61,7 @@ return trimmedVersion.length > 0 ? trimmedVersion : nil; } -- (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath error:(NSError * __autoreleasing *)error +- (BOOL)performInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host fileOperationToolPath:(NSString *)fileOperationToolPath progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error { if (installationURL == nil || newURL == nil) { // this really shouldn't happen but just in case @@ -207,9 +207,9 @@ return YES; } -- (BOOL)performFinalInstallation:(NSError * __autoreleasing *)error +- (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError *__autoreleasing*)error { - return [self performInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host fileOperationToolPath:self.fileOperationToolPath error:error]; + return [self performInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host fileOperationToolPath:self.fileOperationToolPath progressBlock:cb error:error]; } - (BOOL)canInstallSilently diff --git a/Tests/SUInstallerTest.m b/Tests/SUInstallerTest.m index f5790a72..c750c042 100644 --- a/Tests/SUInstallerTest.m +++ b/Tests/SUInstallerTest.m @@ -71,7 +71,7 @@ } NSError *finalInstallationError = nil; - if (![installer performFinalInstallation:&finalInstallationError]) { + if (![installer performFinalInstallationProgressBlock:nil error:&finalInstallationError]) { XCTFail(@"Failed to perform final installation with underlying error = %@ ; error = %@", [finalInstallationError.userInfo objectForKey:NSUnderlyingErrorKey], finalInstallationError); } From 81e71844d6c5eafbed0909bee99eab053e167ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 24 Jan 2017 13:30:46 +0000 Subject: [PATCH 05/39] Report plain install progress --- Sparkle/SUPlainInstaller.m | 39 +++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index 74a480b1..2f326767 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -71,7 +71,9 @@ } return NO; } - + + progress(1/10.0); + SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath]; // Create a temporary directory for our new app that resides on our destination's volume @@ -82,7 +84,9 @@ SULog(SULogLevelError, @"Failed to make new temp directory"); return NO; } - + + progress(2/10.0); + // Move the new app to our temporary directory NSString *newURLLastPathComponent = newURL.lastPathComponent; NSURL *newTempURL = [tempNewDirectoryURL URLByAppendingPathComponent:newURLLastPathComponent]; @@ -91,7 +95,9 @@ [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; return NO; } - + + progress(3/10.0); + // Release our new app from quarantine, fix its owner and group IDs, and update its modification time while it's at our temporary destination // We must leave moving the app to its destination as the final step in installing it, so that // it's not possible our new app can be left in an incomplete state at the final destination @@ -101,7 +107,9 @@ // Not big enough of a deal to fail the entire installation SULog(SULogLevelError, @"Failed to release quarantine at %@ with error %@", newTempURL.path, quarantineError); } - + + progress(4/10.0); + NSURL *oldURL = [NSURL fileURLWithPath:host.bundlePath]; if (oldURL == nil) { // this really shouldn't happen but just in case @@ -119,11 +127,16 @@ return NO; } + + progress(5/10.0); + if (![fileManager updateModificationAndAccessTimeOfItemAtURL:newTempURL error:error]) { // Not a fatal error, but a pretty unfortunate one SULog(SULogLevelError, @"Failed to update modification and access time of new app at %@", newTempURL.path); } - + + progress(6/10.0); + // Decide on a destination name we should use for the older app when we move it around the file system NSString *oldDestinationName = nil; if (SPARKLE_APPEND_VERSION_NUMBER) { @@ -145,7 +158,9 @@ [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; return NO; } - + + progress(7/10.0); + // Move the old app to the temporary directory NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension]; if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) { @@ -157,7 +172,9 @@ return NO; } - + + progress(8/10.0); + // Move the new app to its final destination if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) { SULog(SULogLevelError, @"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path); @@ -171,14 +188,18 @@ return NO; } - + + progress(9/10.0); + // From here on out, we don't really need to bring up authorization if we haven't done so prior SUFileManager *constrainedFileManager = [fileManager fileManagerByPreservingAuthorizationRights]; // Cleanup [constrainedFileManager removeItemAtURL:tempOldDirectoryURL error:NULL]; [constrainedFileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; - + + progress(10/10.0); + return YES; } From 2a644672ca7939c50466507f28d4ee9f349edc6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 24 Jan 2017 13:45:11 +0000 Subject: [PATCH 06/39] Report installer progress --- Sparkle/SUFileManager.h | 3 ++- Sparkle/SUFileManager.m | 41 +++++++++++++++++++++++++++--- Sparkle/SUGuidedPackageInstaller.m | 2 +- fileop/fileop.m | 8 +++--- 4 files changed, 46 insertions(+), 8 deletions(-) diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index 9434566b..817bad9d 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -146,6 +146,7 @@ NS_ASSUME_NONNULL_BEGIN /** * Runs an installer package (pkg) in a headless mode using /usr/sbin/installer * @param packageURL A URL pointing to the package to execute. The item at this URL must exist. + * @param progressBlock Callback that takes double value (0..1 range) notifying how far the installation has progressed * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. * @return YES if the installer ran the package successfully, otherwise NO with a populated error object * @@ -153,7 +154,7 @@ NS_ASSUME_NONNULL_BEGIN * an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization. * An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code. */ -- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError *_Nullable*_Nullable)error; +- (BOOL)executePackageAtURL:(NSURL *)packageURL progressBlock:(nullable void(^)(double))progressBlock error:(NSError *_Nullable*_Nullable)error; NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 98800e3a..5be0ae03 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -143,7 +143,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return YES; } -- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error +- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error { + return [self _authorizeAndExecuteCommand:command sourcePath:sourcePath destinationPath:destinationPath lineCallback:nil error:error]; +} + +- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath lineCallback:(void(^)(NSString*))lineCallback error:(NSError * __autoreleasing *)error { NSError *acquireError = nil; if (![self _acquireAuthorizationWithError:&acquireError]) { @@ -183,6 +187,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return NO; } + if (lineCallback) { + NSFileHandle *pipeHandle = [[NSFileHandle alloc] initWithFileDescriptor:fileno(pipe) closeOnDealloc:NO]; + [self parseLines:pipeHandle lineCallback:lineCallback]; + } + pid_t childPid = (int32_t)CFSwapInt32LittleToHost(pidData); int status = 0; @@ -203,6 +212,28 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return YES; } +- (void)parseLines:(NSFileHandle *)pipeHandle lineCallback:(void(^)(NSString *))lineCallback { + __block NSMutableData *line = [NSMutableData new]; + pipeHandle.readabilityHandler = ^(NSFileHandle *handle){ + NSData *data = handle.availableData; + NSUInteger length = data.length; + if (!length) { + return; + } + const char *bytes = data.bytes; + for(NSUInteger i = 0; i < length; i++) { + if (bytes[i] == '\n') { + NSData *dataToEOL = [data subdataWithRange:NSMakeRange(0, i)]; + [line appendData:dataToEOL]; + NSString *fullLine = [[NSString alloc] initWithData:line encoding:NSUTF8StringEncoding]; + lineCallback(fullLine); + line = [[data subdataWithRange:NSMakeRange(i+1, length-i-1)] mutableCopy]; + break; + } + } + }; +} + - (void)dealloc { if (_auth != NULL) { @@ -923,7 +954,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } // Unlike other methods, authorization is required to execute this method successfully -- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError * __autoreleasing *)error +- (BOOL)executePackageAtURL:(NSURL *)packageURL progressBlock:(void(^)(double))progressBlock error:(NSError * __autoreleasing *)error { if (![self _itemExistsAtURL:packageURL]) { if (error != NULL) { @@ -941,7 +972,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { } NSError *executeError = nil; - BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL error:&executeError]; + BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL lineCallback:^(NSString *line){ + if ([line hasPrefix:@"installer:%"]) { + progressBlock([[line substringFromIndex:11] doubleValue]/100.0); + } + } error:&executeError]; if (!success && error != NULL) { NSString* errorMessage = @"Failed to execute package installer."; diff --git a/Sparkle/SUGuidedPackageInstaller.m b/Sparkle/SUGuidedPackageInstaller.m index bd753f1c..9c8e6e50 100644 --- a/Sparkle/SUGuidedPackageInstaller.m +++ b/Sparkle/SUGuidedPackageInstaller.m @@ -46,7 +46,7 @@ { SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:self.fileOperationToolPath]; - return [fileManager executePackageAtURL:[NSURL fileURLWithPath:self.packagePath] error:error]; + return [fileManager executePackageAtURL:[NSURL fileURLWithPath:self.packagePath] progressBlock:progressBlock error:error]; } - (BOOL)canInstallSilently diff --git a/fileop/fileop.m b/fileop/fileop.m index 9bb54411..397ccb79 100644 --- a/fileop/fileop.m +++ b/fileop/fileop.m @@ -131,10 +131,12 @@ int main(int argc, const char *argv[]) NSTask *task = [[NSTask alloc] init]; task.launchPath = installerPath; - task.arguments = @[@"-pkg", filepath, @"-target", @"/"]; - // Output won't show up anyway, so we may as well ignore it + task.arguments = @[@"-verboseR", + @"-pkg", filepath, + @"-target", @"/"]; task.standardError = [NSPipe pipe]; - task.standardOutput = [NSPipe pipe]; + // Pass through verbose output from the installer, so the caller can parse it + task.standardOutput = [NSFileHandle fileHandleWithStandardOutput]; @try { [task launch]; From 0fd0331464cb601a191ac77998d6d81a3bdcf51d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Fri, 27 Jan 2017 18:04:43 +0000 Subject: [PATCH 07/39] Typo --- CHANGELOG | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index 266281f0..971762dc 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,7 +3,7 @@ * Added Touch Bar support (Bi11) * Upgraded SULog to use logging APIs that Apple provides built-in (Zorg) * Skip buttons are disabled if the update is marked as critical (Kornel Lesiński) - * Backround updates ask OS for lower-priority networking (Kornel Lesiński) + * Background updates ask OS for lower-priority networking (Kornel Lesiński) * Refactorings to sync with upcoming 2.0 * Added kqueue based termination listener (Zorg) * Added AppKit prevention guards to modules that shouldn't import it (Zorg) From 14c543ccb35fc8f6ae0abaf55f2edbcfb56602cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Fri, 27 Jan 2017 18:05:23 +0000 Subject: [PATCH 08/39] Test with non-ASCII names --- Tests/SUBinaryDeltaTest.m | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Tests/SUBinaryDeltaTest.m b/Tests/SUBinaryDeltaTest.m index 7978fa5c..544be1ff 100644 --- a/Tests/SUBinaryDeltaTest.m +++ b/Tests/SUBinaryDeltaTest.m @@ -24,8 +24,8 @@ typedef void (^SUDeltaHandler)(NSFileManager *fileManager, NSString *sourceDirec - (void)testTemporaryDirectory { - NSString *tmp1 = temporaryDirectory(@"Sparkle"); - NSString *tmp2 = temporaryDirectory(@"Sparkle"); + NSString *tmp1 = temporaryDirectory(@"Sparklęエンジン"); + NSString *tmp2 = temporaryDirectory(@"Sparklęエンジン"); NSLog(@"Temporary directories: %@, %@", tmp1, tmp2); XCTAssertNotEqualObjects(tmp1, tmp2); XCTAssert(YES, @"Pass"); @@ -33,8 +33,8 @@ typedef void (^SUDeltaHandler)(NSFileManager *fileManager, NSString *sourceDirec - (void)testTemporaryFile { - NSString *tmp1 = temporaryFilename(@"Sparkle"); - NSString *tmp2 = temporaryFilename(@"Sparkle"); + NSString *tmp1 = temporaryFilename(@"Sparklęエンジン"); + NSString *tmp2 = temporaryFilename(@"Sparklęエンジン"); NSLog(@"Temporary files: %@, %@", tmp1, tmp2); XCTAssertNotEqualObjects(tmp1, tmp2); XCTAssert(YES, @"Pass"); @@ -42,12 +42,12 @@ typedef void (^SUDeltaHandler)(NSFileManager *fileManager, NSString *sourceDirec - (BOOL)createAndApplyPatchUsingVersion:(SUBinaryDeltaMajorVersion)majorVersion beforeDiffHandler:(SUDeltaHandler)beforeDiffHandler afterDiffHandler:(SUDeltaHandler)afterDiffHandler { - NSString *sourceDirectory = temporaryDirectory(@"Sparkle_temp1"); - NSString *destinationDirectory = temporaryDirectory(@"Sparkle_temp2"); - - NSString *diffFile = temporaryFilename(@"Sparkle_diff"); - NSString *patchDirectory = temporaryDirectory(@"Sparkle_patch"); - + NSString *sourceDirectory = temporaryDirectory(@"Spąrkle_temp1エンジン"); + NSString *destinationDirectory = temporaryDirectory(@"Spąrkle_temp2エンジン"); + + NSString *diffFile = temporaryFilename(@"Spąrkle_diffエンジン"); + NSString *patchDirectory = temporaryDirectory(@"Spąrkle_patchエンジン"); + XCTAssertNotNil(sourceDirectory); XCTAssertNotNil(destinationDirectory); XCTAssertNotNil(diffFile); @@ -120,9 +120,9 @@ typedef void (^SUDeltaHandler)(NSFileManager *fileManager, NSString *sourceDirec { [self createAndApplyPatchWithHandler:^(NSFileManager *__unused fileManager, NSString *sourceDirectory, NSString *destinationDirectory) { NSData *emptyData = [NSData data]; - NSString *sourceFile = [sourceDirectory stringByAppendingPathComponent:@"A"]; - NSString *destinationFile = [destinationDirectory stringByAppendingPathComponent:@"A"]; - + NSString *sourceFile = [sourceDirectory stringByAppendingPathComponent:@"AĄエンジン"]; + NSString *destinationFile = [destinationDirectory stringByAppendingPathComponent:@"AĄエンジン"]; + XCTAssertTrue([emptyData writeToFile:sourceFile atomically:YES]); XCTAssertTrue([emptyData writeToFile:destinationFile atomically:YES]); From 0a869e87bf88e53cc8f0f1c46629e98d7fe5220c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Fri, 27 Jan 2017 18:34:56 +0000 Subject: [PATCH 09/39] Make normalizedInstallationPathForHost also normalize Unicode --- Sparkle/SUInstaller.m | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Sparkle/SUInstaller.m b/Sparkle/SUInstaller.m index 8a9d8f38..23d8c6e8 100644 --- a/Sparkle/SUInstaller.m +++ b/Sparkle/SUInstaller.m @@ -154,8 +154,10 @@ assert(bundle != nil); NSString *normalizedAppPath = [[[bundle bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleNameKey], [[bundle bundlePath] pathExtension]]]; - - return normalizedAppPath; + + // Roundtrip string through fileSystemRepresentation to ensure it uses filesystem's Unicode normalization + // rather than arbitrary Unicode form from Info.plist - #1017 + return [NSString stringWithUTF8String:[normalizedAppPath fileSystemRepresentation]]; } @end From ed16c5c2a08bc1db16c1f7261f90d3fc77013bfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Fri, 27 Jan 2017 18:37:35 +0000 Subject: [PATCH 10/39] Use the same fileSystemRepresentation function for both parts of the path --- Sparkle/SUBinaryDeltaCommon.m | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Sparkle/SUBinaryDeltaCommon.m b/Sparkle/SUBinaryDeltaCommon.m index 42e9d6c0..9d10208e 100644 --- a/Sparkle/SUBinaryDeltaCommon.m +++ b/Sparkle/SUBinaryDeltaCommon.m @@ -163,6 +163,9 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion) CC_SHA1_CTX hashContext; CC_SHA1_Init(&hashContext); + // Ensure the path uses filesystem-specific Unicode normalization #1017 + NSString *normalizedPath = stringWithFileSystemRepresentation(pathBuffer); + FTSENT *ent = 0; while ((ent = fts_read(fts))) { if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) @@ -171,8 +174,8 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion) if (ent->fts_info == FTS_D && !MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) { continue; } - - NSString *relativePath = pathRelativeToDirectory(path, stringWithFileSystemRepresentation(ent->fts_path)); + + NSString *relativePath = pathRelativeToDirectory(normalizedPath, stringWithFileSystemRepresentation(ent->fts_path)); if (relativePath.length == 0) continue; From 21214e8623cdc3c064a5c9fdf5e31323a47c8767 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sat, 28 Jan 2017 11:08:53 +0000 Subject: [PATCH 11/39] Simplify minor delta version down to int + minor version bump --- Sparkle/SUBinaryDeltaApply.m | 6 +++--- Sparkle/SUBinaryDeltaCommon.h | 11 +---------- Sparkle/SUBinaryDeltaCommon.m | 8 ++++---- Sparkle/SUBinaryDeltaTool.m | 6 +++--- 4 files changed, 11 insertions(+), 20 deletions(-) diff --git a/Sparkle/SUBinaryDeltaApply.m b/Sparkle/SUBinaryDeltaApply.m index ea93b2be..a42bd0ee 100644 --- a/Sparkle/SUBinaryDeltaApply.m +++ b/Sparkle/SUBinaryDeltaApply.m @@ -39,7 +39,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION; - SUBinaryDeltaMinorVersion minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION; + int minorDiffVersion = 0; NSString *expectedBeforeHashv1 = nil; NSString *expectedAfterHashv1 = nil; @@ -62,8 +62,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi // available in version 2.0 or later xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value); if (value) - minorDiffVersion = (SUBinaryDeltaMinorVersion)[@(value) intValue]; - + minorDiffVersion = [@(value) intValue]; + // available in version 2.0 or later xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_KEY, &value); if (value) diff --git a/Sparkle/SUBinaryDeltaCommon.h b/Sparkle/SUBinaryDeltaCommon.h index 3e7db6c6..c1e80812 100644 --- a/Sparkle/SUBinaryDeltaCommon.h +++ b/Sparkle/SUBinaryDeltaCommon.h @@ -57,16 +57,7 @@ typedef NS_ENUM(uint16_t, SUBinaryDeltaMajorVersion) SUBeigeMajorVersion = 2 }; -// Only keep track of the latest minor version for each major version -typedef NS_ENUM(uint16_t, SUBinaryDeltaMinorVersion) -{ - SUAzureMinorVersion = 1, - SUBeigeMinorVersion = 1, -}; - #define FIRST_DELTA_DIFF_MAJOR_VERSION SUAzureMajorVersion -#define FIRST_DELTA_DIFF_MINOR_VERSION ((SUBinaryDeltaMinorVersion)0) - #define LATEST_DELTA_DIFF_MAJOR_VERSION SUBeigeMajorVersion extern int compareFiles(const FTSENT **a, const FTSENT **b); @@ -80,5 +71,5 @@ extern NSString *pathRelativeToDirectory(NSString *directory, NSString *path); NSString *temporaryFilename(NSString *base); NSString *temporaryDirectory(NSString *base); NSString *stringWithFileSystemRepresentation(const char*); -SUBinaryDeltaMinorVersion latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion); +int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion); #endif diff --git a/Sparkle/SUBinaryDeltaCommon.m b/Sparkle/SUBinaryDeltaCommon.m index 9d10208e..e396ed05 100644 --- a/Sparkle/SUBinaryDeltaCommon.m +++ b/Sparkle/SUBinaryDeltaCommon.m @@ -39,15 +39,15 @@ NSString *stringWithFileSystemRepresentation(const char *input) { return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:input length:strlen(input)]; } -SUBinaryDeltaMinorVersion latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion) +int latestMinorVersionForMajorVersion(SUBinaryDeltaMajorVersion majorVersion) { switch (majorVersion) { case SUAzureMajorVersion: - return SUAzureMinorVersion; + return 1; case SUBeigeMajorVersion: - return SUBeigeMinorVersion; + return 2; } - return (SUBinaryDeltaMinorVersion)0; + return 0; } NSString *temporaryFilename(NSString *base) diff --git a/Sparkle/SUBinaryDeltaTool.m b/Sparkle/SUBinaryDeltaTool.m index fae14ed1..573bf4aa 100644 --- a/Sparkle/SUBinaryDeltaTool.m +++ b/Sparkle/SUBinaryDeltaTool.m @@ -188,10 +188,10 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args) fprintf(stderr, "Unable to open patch %s\n", [patchFile fileSystemRepresentation]); return NO; } - + SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION; - SUBinaryDeltaMinorVersion minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION; - + int minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION; + xar_subdoc_t subdoc; for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) { if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) { From 67b1e08a4506b57ac8bf873694d4025b5c1d90b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sat, 28 Jan 2017 11:16:45 +0000 Subject: [PATCH 12/39] Delta minor version fix --- Sparkle/SUBinaryDeltaCreate.m | 6 +++--- Sparkle/SUBinaryDeltaTool.m | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Sparkle/SUBinaryDeltaCreate.m b/Sparkle/SUBinaryDeltaCreate.m index b0dfa3ef..c9a436b6 100644 --- a/Sparkle/SUBinaryDeltaCreate.m +++ b/Sparkle/SUBinaryDeltaCreate.m @@ -230,9 +230,9 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF assert(destination); assert(patchFile); assert(majorVersion >= FIRST_DELTA_DIFF_MAJOR_VERSION && majorVersion <= LATEST_DELTA_DIFF_MAJOR_VERSION); - - SUBinaryDeltaMinorVersion minorVersion = latestMinorVersionForMajorVersion(majorVersion); - + + int minorVersion = latestMinorVersionForMajorVersion(majorVersion); + NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary]; char pathBuffer[PATH_MAX] = {0}; diff --git a/Sparkle/SUBinaryDeltaTool.m b/Sparkle/SUBinaryDeltaTool.m index 573bf4aa..b130ec6a 100644 --- a/Sparkle/SUBinaryDeltaTool.m +++ b/Sparkle/SUBinaryDeltaTool.m @@ -190,7 +190,7 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args) } SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION; - int minorDiffVersion = FIRST_DELTA_DIFF_MINOR_VERSION; + int minorDiffVersion = 0; xar_subdoc_t subdoc; for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) { @@ -205,7 +205,7 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args) // available in version 2.0 or later xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value); if (value) - minorDiffVersion = (SUBinaryDeltaMinorVersion)[@(value) intValue]; + minorDiffVersion = [@(value) intValue]; } } From 155816b609a623310f48b34019318118e97c49bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sat, 28 Jan 2017 11:35:48 +0000 Subject: [PATCH 13/39] Formatting --- Sparkle/SUBinaryDeltaApply.m | 55 +++++++------- Sparkle/SUBinaryDeltaCommon.m | 26 +++---- Sparkle/SUBinaryDeltaCreate.m | 134 +++++++++++++++++----------------- Sparkle/SUBinaryDeltaTool.m | 58 +++++++-------- 4 files changed, 133 insertions(+), 140 deletions(-) diff --git a/Sparkle/SUBinaryDeltaApply.m b/Sparkle/SUBinaryDeltaApply.m index a42bd0ee..90e7b8bd 100644 --- a/Sparkle/SUBinaryDeltaApply.m +++ b/Sparkle/SUBinaryDeltaApply.m @@ -15,20 +15,19 @@ #include #include - #include "AppKitPrevention.h" static BOOL applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFilePath, NSString *destinationFilePath) { NSString *patchFile = temporaryFilename(@"apply-binary-delta"); xar_extract_tofile(x, file, [patchFile fileSystemRepresentation]); - const char *argv[] = {"/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation]}; + const char *argv[] = { "/usr/bin/bspatch", [sourceFilePath fileSystemRepresentation], [destinationFilePath fileSystemRepresentation], [patchFile fileSystemRepresentation] }; BOOL success = (bspatch(4, argv) == 0); unlink([patchFile fileSystemRepresentation]); return success; } -BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError * __autoreleasing *error) +BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError *__autoreleasing *error) { xar_t x = xar_open([patchFile fileSystemRepresentation], READ); if (!x) { @@ -37,28 +36,28 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } return NO; } - + SUBinaryDeltaMajorVersion majorDiffVersion = FIRST_DELTA_DIFF_MAJOR_VERSION; int minorDiffVersion = 0; NSString *expectedBeforeHashv1 = nil; NSString *expectedAfterHashv1 = nil; - + NSString *expectedNewBeforeHash = nil; NSString *expectedNewAfterHash = nil; - + progressCallback(0/6.0); xar_subdoc_t subdoc; for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) { if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) { const char *value = 0; - + // available in version 2.0 or later xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value); if (value) majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue]; - + // available in version 2.0 or later xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value); if (value) @@ -68,40 +67,40 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_KEY, &value); if (value) expectedNewBeforeHash = @(value); - + // available in version 2.0 or later xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_KEY, &value); if (value) expectedNewAfterHash = @(value); - + // only available in version 1.0 xar_subdoc_prop_get(subdoc, BEFORE_TREE_SHA1_OLD_KEY, &value); if (value) expectedBeforeHashv1 = @(value); - + // only available in version 1.0 xar_subdoc_prop_get(subdoc, AFTER_TREE_SHA1_OLD_KEY, &value); if (value) expectedAfterHashv1 = @(value); } } - + if (majorDiffVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Unable to identify diff-version %u in delta. Giving up.", majorDiffVersion] }]; } return NO; } - + if (majorDiffVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"A later version is needed to apply this patch (on major version %u, but patch requests version %u).", LATEST_DELTA_DIFF_MAJOR_VERSION, majorDiffVersion] }]; } return NO; } - + BOOL usesNewTreeHash = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion); - + NSString *expectedBeforeHash = usesNewTreeHash ? expectedNewBeforeHash : expectedBeforeHashv1; NSString *expectedAfterHash = usesNewTreeHash ? expectedNewAfterHash : expectedAfterHashv1; @@ -116,7 +115,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi fprintf(stderr, "Applying version %u.%u patch...\n", majorDiffVersion, minorDiffVersion); fprintf(stderr, "Verifying source..."); } - + progressCallback(1/6.0); NSString *beforeHash = hashOfTreeWithVersion(source, majorDiffVersion); @@ -143,7 +142,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi if (verbose) { fprintf(stderr, "\nCopying files..."); } - + progressCallback(2/6.0); if (!removeTree(destination)) { @@ -167,7 +166,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } return NO; } - + progressCallback(4/6.0); BOOL hasExtractKeyAvailable = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion); @@ -186,10 +185,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi // Don't use -[NSFileManager fileExistsAtPath:] because it will follow symbolic links BOOL fileExisted = verbose && [fileManager attributesOfItemAtPath:destinationFilePath error:nil]; BOOL removedFile = NO; - + const char *value; - if (!xar_prop_get(file, DELETE_KEY, &value) || - (!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) { + if (!xar_prop_get(file, DELETE_KEY, &value) || (!hasExtractKeyAvailable && !xar_prop_get(file, DELETE_THEN_EXTRACT_OLD_KEY, &value))) { if (!removeTree(destinationFilePath)) { if (verbose) { fprintf(stderr, "\n"); @@ -205,7 +203,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } continue; } - + removedFile = YES; } @@ -219,13 +217,12 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } return NO; } - + if (verbose) { fprintf(stderr, "\n🔨 %s %s", VERBOSE_PATCHED, [path fileSystemRepresentation]); } - } else if ((hasExtractKeyAvailable && !xar_prop_get(file, EXTRACT_KEY, &value)) || - (!hasExtractKeyAvailable && xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value))) { // extract and permission modifications don't coexist - + } else if ((hasExtractKeyAvailable && !xar_prop_get(file, EXTRACT_KEY, &value)) || (!hasExtractKeyAvailable && xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value))) { // extract and permission modifications don't coexist + if (xar_extract_tofile(x, file, [destinationFilePath fileSystemRepresentation]) != 0) { if (verbose) { fprintf(stderr, "\n"); @@ -235,7 +232,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } return NO; } - + if (verbose) { if (fileExisted) { fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [path fileSystemRepresentation]); @@ -246,7 +243,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } else if (verbose && removedFile) { fprintf(stderr, "\n❌ %s %s", VERBOSE_DELETED, [path fileSystemRepresentation]); } - + if (!xar_prop_get(file, MODIFY_PERMISSIONS_KEY, &value)) { mode_t mode = (mode_t)[[NSString stringWithUTF8String:value] intValue]; if (!modifyPermissions(destinationFilePath, mode)) { @@ -258,7 +255,7 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } return NO; } - + if (verbose) { fprintf(stderr, "\n👮 %s %s (0%o)", VERBOSE_MODIFIED, [path fileSystemRepresentation], mode); } diff --git a/Sparkle/SUBinaryDeltaCommon.m b/Sparkle/SUBinaryDeltaCommon.m index e396ed05..b5731cbe 100644 --- a/Sparkle/SUBinaryDeltaCommon.m +++ b/Sparkle/SUBinaryDeltaCommon.m @@ -18,7 +18,6 @@ #include #include - #include "AppKitPrevention.h" int compareFiles(const FTSENT **a, const FTSENT **b) @@ -35,7 +34,8 @@ NSString *pathRelativeToDirectory(NSString *directory, NSString *path) return path; } -NSString *stringWithFileSystemRepresentation(const char *input) { +NSString *stringWithFileSystemRepresentation(const char *input) +{ return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:input length:strlen(input)]; } @@ -76,18 +76,18 @@ NSString *temporaryDirectory(NSString *base) NSString *template = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.XXXXXXXXXX", base]]; NSMutableData *data = [NSMutableData data]; [data appendBytes:template.fileSystemRepresentation length:strlen(template.fileSystemRepresentation) + 1]; - + char *buffer = data.mutableBytes; char *templateResult = mkdtemp(buffer); if (templateResult == NULL) { perror("mkdtemp"); return nil; } - + return stringWithFileSystemRepresentation(templateResult); } -static void _hashOfBuffer(unsigned char *hash, const char* buffer, ssize_t bufferLength) +static void _hashOfBuffer(unsigned char *hash, const char *buffer, ssize_t bufferLength) { assert(bufferLength >= 0 && bufferLength <= UINT32_MAX); CC_SHA1_CTX hashContext; @@ -96,7 +96,7 @@ static void _hashOfBuffer(unsigned char *hash, const char* buffer, ssize_t buffe CC_SHA1_Final(hash, &hashContext); } -static BOOL _hashOfFileContents(unsigned char* hash, FTSENT *ent) +static BOOL _hashOfFileContents(unsigned char *hash, FTSENT *ent) { if (ent->fts_info == FTS_SL) { char linkDestination[MAXPATHLEN + 1]; @@ -119,12 +119,12 @@ static BOOL _hashOfFileContents(unsigned char* hash, FTSENT *ent) _hashOfBuffer(hash, NULL, 0); } else { void *buffer = mmap(0, (size_t)fileSize, PROT_READ, MAP_FILE | MAP_PRIVATE, fileDescriptor, 0); - if (buffer == (void*)-1) { + if (buffer == (void *)-1) { close(fileDescriptor); perror("mmap"); return NO; } - + _hashOfBuffer(hash, buffer, fileSize); munmap(buffer, (size_t)fileSize); } @@ -148,12 +148,12 @@ NSData *hashOfFileContents(FTSENT *ent) NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion) { - char pathBuffer[PATH_MAX] = {0}; + char pathBuffer[PATH_MAX] = { 0 }; if (![path getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) { return nil; } - char * const sourcePaths[] = {pathBuffer, 0}; + char *const sourcePaths[] = { pathBuffer, 0 }; FTS *fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles); if (!fts) { perror("fts_open"); @@ -170,7 +170,7 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion) while ((ent = fts_read(fts))) { if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) continue; - + if (ent->fts_info == FTS_D && !MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) { continue; } @@ -187,12 +187,12 @@ NSString *hashOfTreeWithVersion(NSString *path, uint16_t majorVersion) const char *relativePathBytes = [relativePath fileSystemRepresentation]; CC_SHA1_Update(&hashContext, relativePathBytes, (CC_LONG)strlen(relativePathBytes)); - + if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) { uint16_t mode = ent->fts_statp->st_mode; uint16_t type = ent->fts_info; uint16_t permissions = mode & PERMISSION_FLAGS; - + CC_SHA1_Update(&hashContext, &type, sizeof(type)); CC_SHA1_Update(&hashContext, &permissions, sizeof(permissions)); } diff --git a/Sparkle/SUBinaryDeltaCreate.m b/Sparkle/SUBinaryDeltaCreate.m index c9a436b6..2f3b3fdf 100644 --- a/Sparkle/SUBinaryDeltaCreate.m +++ b/Sparkle/SUBinaryDeltaCreate.m @@ -21,7 +21,6 @@ #include #include - #include "AppKitPrevention.h" extern int bsdiff(int argc, const char **argv); @@ -59,7 +58,7 @@ extern int bsdiff(int argc, const char **argv); - (void)main { NSString *temporaryFile = temporaryFilename(@"BinaryDelta"); - const char *argv[] = {"/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation]}; + const char *argv[] = { "/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] }; int result = bsdiff(4, argv); if (!result) self.resultPath = temporaryFile; @@ -78,14 +77,17 @@ static NSDictionary *infoForFile(FTSENT *ent) if (!hash) { return nil; } - + off_t size = (ent->fts_info != FTS_D) ? ent->fts_statp->st_size : 0; - + assert(ent->fts_statp != NULL); - + mode_t permissions = ent->fts_statp->st_mode & PERMISSION_FLAGS; - - return @{INFO_HASH_KEY: hash, INFO_TYPE_KEY: @(ent->fts_info), INFO_PERMISSIONS_KEY : @(permissions), INFO_SIZE_KEY: @(size)}; + + return @{ INFO_HASH_KEY: hash, + INFO_TYPE_KEY: @(ent->fts_info), + INFO_PERMISSIONS_KEY: @(permissions), + INFO_SIZE_KEY: @(size) }; } static bool aclExists(const FTSENT *ent) @@ -94,7 +96,7 @@ static bool aclExists(const FTSENT *ent) if (ent->fts_info == FTS_SL) { return NO; } - + acl_t acl = acl_get_link_np(ent->fts_path, ACL_TYPE_EXTENDED); if (acl != NULL) { acl_entry_t entry; @@ -112,28 +114,26 @@ static bool codeSignatureExtendedAttributeExists(const FTSENT *ent) if (listSize == -1) { return false; } - + char *buffer = malloc((size_t)listSize); assert(buffer != NULL); - + ssize_t sizeBack = listxattr(ent->fts_path, buffer, (size_t)listSize, options); assert(sizeBack == listSize); - + size_t startCharacterIndex = 0; for (size_t characterIndex = 0; characterIndex < (size_t)listSize; characterIndex++) { if (buffer[characterIndex] == '\0') { char *attribute = &buffer[startCharacterIndex]; size_t length = characterIndex - startCharacterIndex; - if (strncmp(APPLE_CODE_SIGN_XATTR_CODE_DIRECTORY_KEY, attribute, length) == 0 || - strncmp(APPLE_CODE_SIGN_XATTR_CODE_REQUIREMENTS_KEY, attribute, length) == 0 || - strncmp(APPLE_CODE_SIGN_XATTR_CODE_SIGNATURE_KEY, attribute, length) == 0) { + if (strncmp(APPLE_CODE_SIGN_XATTR_CODE_DIRECTORY_KEY, attribute, length) == 0 || strncmp(APPLE_CODE_SIGN_XATTR_CODE_REQUIREMENTS_KEY, attribute, length) == 0 || strncmp(APPLE_CODE_SIGN_XATTR_CODE_SIGNATURE_KEY, attribute, length) == 0) { free(buffer); return true; } startCharacterIndex = characterIndex + 1; } } - + free(buffer); return false; } @@ -141,7 +141,7 @@ static bool codeSignatureExtendedAttributeExists(const FTSENT *ent) static NSString *absolutePath(NSString *path) { NSURL *url = [[NSURL alloc] initFileURLWithPath:path]; - return [[url absoluteURL] path]; + return [[url absoluteURL] path]; } static NSString *temporaryPatchFile(NSString *patchFile) @@ -154,7 +154,7 @@ static NSString *temporaryPatchFile(NSString *patchFile) #define MIN_FILE_SIZE_FOR_CREATING_DELTA 4096 -static BOOL shouldSkipDeltaCompression(NSDictionary* originalInfo, NSDictionary *newInfo) +static BOOL shouldSkipDeltaCompression(NSDictionary *originalInfo, NSDictionary *newInfo) { unsigned long long fileSize = [newInfo[INFO_SIZE_KEY] unsignedLongLongValue]; if (fileSize < MIN_FILE_SIZE_FOR_CREATING_DELTA) { @@ -168,7 +168,7 @@ static BOOL shouldSkipDeltaCompression(NSDictionary* originalInfo, NSDictionary if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) { return YES; } - + if ([originalInfo[INFO_HASH_KEY] isEqual:newInfo[INFO_HASH_KEY]]) { // this is possible if just the permissions have changed return YES; @@ -177,7 +177,7 @@ static BOOL shouldSkipDeltaCompression(NSDictionary* originalInfo, NSDictionary return NO; } -static BOOL shouldDeleteThenExtract(NSDictionary* originalInfo, NSDictionary *newInfo) +static BOOL shouldDeleteThenExtract(NSDictionary *originalInfo, NSDictionary *newInfo) { if (!originalInfo) { return NO; @@ -195,15 +195,15 @@ static BOOL shouldSkipExtracting(NSDictionary *originalInfo, NSDictionary *newIn if (!originalInfo) { return NO; } - + if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) { return NO; } - + if (![originalInfo[INFO_HASH_KEY] isEqual:newInfo[INFO_HASH_KEY]]) { return NO; } - + return YES; } @@ -212,19 +212,19 @@ static BOOL shouldChangePermissions(NSDictionary *originalInfo, NSDictionary *ne if (!originalInfo) { return NO; } - + if ([originalInfo[INFO_TYPE_KEY] unsignedShortValue] != [newInfo[INFO_TYPE_KEY] unsignedShortValue]) { return NO; } - + if ([originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue] == [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]) { return NO; } - + return YES; } -BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError * __autoreleasing *error) +BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, SUBinaryDeltaMajorVersion majorVersion, BOOL verbose, NSError *__autoreleasing *error) { assert(source); assert(destination); @@ -235,7 +235,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF NSMutableDictionary *originalTreeState = [NSMutableDictionary dictionary]; - char pathBuffer[PATH_MAX] = {0}; + char pathBuffer[PATH_MAX] = { 0 }; if (![source getFileSystemRepresentation:pathBuffer maxLength:sizeof(pathBuffer)]) { if (error != NULL) { *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to retrieve file system path representation from source %@", source] }]; @@ -243,7 +243,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF return NO; } - char *sourcePaths[] = {pathBuffer, 0}; + char *sourcePaths[] = { pathBuffer, 0 }; FTS *fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles); if (!fts) { if (error != NULL) { @@ -256,7 +256,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF fprintf(stderr, "Creating version %u.%u patch...\n", majorVersion, minorVersion); fprintf(stderr, "Processing %s...", [source fileSystemRepresentation]); } - + FTSENT *ent = 0; while ((ent = fts_read(fts))) { if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) { @@ -279,7 +279,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF return NO; } originalTreeState[key] = info; - + if (aclExists(ent)) { if (verbose) { fprintf(stderr, "\n"); @@ -289,7 +289,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + if (codeSignatureExtendedAttributeExists(ent)) { if (verbose) { fprintf(stderr, "\n"); @@ -301,7 +301,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } } fts_close(fts); - + NSString *beforeHash = hashOfTreeWithVersion(source, majorVersion); if (!beforeHash) { @@ -315,8 +315,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } NSMutableDictionary *newTreeState = [NSMutableDictionary dictionary]; - for (NSString *key in originalTreeState) - { + for (NSString *key in originalTreeState) { newTreeState[key] = [NSNull null]; } @@ -334,7 +333,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + sourcePaths[0] = pathBuffer; fts = fts_open(sourcePaths, FTS_PHYSICAL | FTS_NOCHDIR, compareFiles); if (!fts) { @@ -344,7 +343,6 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF return NO; } - while ((ent = fts_read(fts))) { if (ent->fts_info != FTS_F && ent->fts_info != FTS_SL && ent->fts_info != FTS_D) { continue; @@ -365,13 +363,13 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + // We should validate permissions and ACLs even if we don't store the info in the diff in the case of ACLs, // or in the case of permissions if the patch version is 1 - + // We should also not allow files with code signed extended attributes since Apple doesn't recommend inserting these // inside an application, and since we don't preserve extended attribitutes anyway - + mode_t permissions = [info[INFO_PERMISSIONS_KEY] unsignedShortValue]; if (!IS_VALID_PERMISSIONS(permissions)) { if (verbose) { @@ -382,7 +380,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + if (aclExists(ent)) { if (verbose) { fprintf(stderr, "\n"); @@ -392,7 +390,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + if (codeSignatureExtendedAttributeExists(ent)) { if (verbose) { fprintf(stderr, "\n"); @@ -402,14 +400,14 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + NSDictionary *oldInfo = originalTreeState[key]; if ([info isEqual:oldInfo]) { [newTreeState removeObjectForKey:key]; } else { newTreeState[key] = info; - + if (oldInfo && [oldInfo[INFO_TYPE_KEY] unsignedShortValue] == FTS_D && [info[INFO_TYPE_KEY] unsignedShortValue] != FTS_D) { NSArray *parentPathComponents = key.pathComponents; @@ -435,7 +433,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + if (verbose) { fprintf(stderr, "\nGenerating delta..."); } @@ -451,20 +449,18 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + xar_opt_set(x, XAR_OPT_COMPRESSION, "bzip2"); - + xar_subdoc_t attributes = xar_subdoc_new(x, BINARY_DELTA_ATTRIBUTES_KEY); - + xar_subdoc_prop_set(attributes, MAJOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", majorVersion] UTF8String]); xar_subdoc_prop_set(attributes, MINOR_DIFF_VERSION_KEY, [[NSString stringWithFormat:@"%u", minorVersion] UTF8String]); - + // Version 1 patches don't have a major or minor version field, so we need to differentiate between the hash keys - const char *beforeHashKey = - MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? BEFORE_TREE_SHA1_KEY : BEFORE_TREE_SHA1_OLD_KEY; - const char *afterHashKey = - MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? AFTER_TREE_SHA1_KEY : AFTER_TREE_SHA1_OLD_KEY; - + const char *beforeHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? BEFORE_TREE_SHA1_KEY : BEFORE_TREE_SHA1_OLD_KEY; + const char *afterHashKey = MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion) ? AFTER_TREE_SHA1_KEY : AFTER_TREE_SHA1_OLD_KEY; + xar_subdoc_prop_set(attributes, beforeHashKey, [beforeHash UTF8String]); xar_subdoc_prop_set(attributes, afterHashKey, [afterHash UTF8String]); @@ -474,21 +470,21 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF // Sort the keys by preferring the ones from the original tree to appear first // We want to enforce deleting before extracting in the case paths differ only by case NSArray *keys = [[newTreeState allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) { - NSComparisonResult insensitiveCompareResult = [key1 caseInsensitiveCompare:key2]; - if (insensitiveCompareResult != NSOrderedSame) { - return insensitiveCompareResult; - } + NSComparisonResult insensitiveCompareResult = [key1 caseInsensitiveCompare:key2]; + if (insensitiveCompareResult != NSOrderedSame) { + return insensitiveCompareResult; + } - return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending; + return originalTreeState[key1] ? NSOrderedAscending : NSOrderedDescending; }]; - for (NSString* key in keys) { + for (NSString *key in keys) { id value = [newTreeState valueForKey:key]; if ([value isEqual:[NSNull null]]) { xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1); assert(newFile); xar_prop_set(newFile, DELETE_KEY, "true"); - + if (verbose) { fprintf(stderr, "\n❌ %s %s", VERBOSE_REMOVED, [key fileSystemRepresentation]); } @@ -503,7 +499,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF xar_file_t newFile = xar_add_frombuffer(x, 0, [key fileSystemRepresentation], (char *)"", 1); assert(newFile); xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]] UTF8String]); - + if (verbose) { fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [key fileSystemRepresentation], [originalInfo[INFO_PERMISSIONS_KEY] unsignedShortValue], [newInfo[INFO_PERMISSIONS_KEY] unsignedShortValue]); } @@ -512,7 +508,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF NSString *path = [destination stringByAppendingPathComponent:key]; xar_file_t newFile = xar_add_frompath(x, 0, [key fileSystemRepresentation], [path fileSystemRepresentation]); assert(newFile); - + if (shouldDeleteThenExtract(originalInfo, newInfo)) { if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) { xar_prop_set(newFile, DELETE_KEY, "true"); @@ -520,11 +516,11 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF xar_prop_set(newFile, DELETE_THEN_EXTRACT_OLD_KEY, "true"); } } - + if (MAJOR_VERSION_IS_AT_LEAST(majorVersion, SUBeigeMajorVersion)) { xar_prop_set(newFile, EXTRACT_KEY, "true"); } - + if (verbose) { if (originalInfo) { fprintf(stderr, "\n✏️ %s %s", VERBOSE_UPDATED, [key fileSystemRepresentation]); @@ -557,19 +553,19 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF } return NO; } - + if (verbose) { fprintf(stderr, "\n🔨 %s %s", VERBOSE_DIFFED, [[operation relativePath] fileSystemRepresentation]); } - + xar_file_t newFile = xar_add_frompath(x, 0, [[operation relativePath] fileSystemRepresentation], [resultPath fileSystemRepresentation]); assert(newFile); xar_prop_set(newFile, BINARY_DELTA_KEY, "true"); unlink([resultPath fileSystemRepresentation]); - + if (operation.permissions) { xar_prop_set(newFile, MODIFY_PERMISSIONS_KEY, [[NSString stringWithFormat:@"%u", [operation.permissions unsignedShortValue]] UTF8String]); - + if (verbose) { fprintf(stderr, "\n👮 %s %s (0%o -> 0%o)", VERBOSE_MODIFIED, [[operation relativePath] fileSystemRepresentation], operation.oldPermissions.unsignedShortValue, operation.permissions.unsignedShortValue); } @@ -581,7 +577,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF unlink([patchFile fileSystemRepresentation]); link([temporaryFile fileSystemRepresentation], [patchFile fileSystemRepresentation]); unlink([temporaryFile fileSystemRepresentation]); - + if (verbose) { fprintf(stderr, "\nDone!\n"); } diff --git a/Sparkle/SUBinaryDeltaTool.m b/Sparkle/SUBinaryDeltaTool.m index b130ec6a..64b06162 100644 --- a/Sparkle/SUBinaryDeltaTool.m +++ b/Sparkle/SUBinaryDeltaTool.m @@ -36,7 +36,7 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args) printUsage(programName); return NO; } - + NSUInteger numberOflagsFound = 0; NSUInteger verboseIndex = [args indexOfObject:VERBOSE_FLAG]; NSUInteger versionIndex = NSNotFound; @@ -46,22 +46,22 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args) break; } } - + if (verboseIndex != NSNotFound) { ++numberOflagsFound; } if (versionIndex != NSNotFound) { ++numberOflagsFound; } - + if (args.count - numberOflagsFound < 3) { printUsage(programName); return NO; } - + BOOL verbose = (verboseIndex != NSNotFound); NSString *versionField = (versionIndex != NSNotFound) ? args[versionIndex] : nil; - + NSArray *versionComponents = nil; if (versionField) { versionComponents = [versionField componentsSeparatedByString:@"="]; @@ -70,17 +70,17 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args) return NO; } } - + SUBinaryDeltaMajorVersion patchVersion = !versionComponents ? LATEST_DELTA_DIFF_MAJOR_VERSION : (SUBinaryDeltaMajorVersion)[[versionComponents[1] componentsSeparatedByString:@"."][0] intValue]; // ignore minor version if provided - + if (patchVersion < FIRST_DELTA_DIFF_MAJOR_VERSION) { fprintf(stderr, "Version provided (%u) is not valid\n", patchVersion); return NO; } - + if (patchVersion > LATEST_DELTA_DIFF_MAJOR_VERSION) { fprintf(stderr, "This program is too old to create a version %u patch, or the version number provided is invalid\n", patchVersion); return NO; @@ -92,12 +92,12 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args) [fileArgs addObject:argument]; } } - + if (fileArgs.count != 3) { printUsage(programName); return NO; } - + NSString *sourcePath = fileArgs[0]; NSString *destPath = fileArgs[1]; NSString *patchPath = fileArgs[2]; @@ -108,19 +108,19 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args) fprintf(stderr, "Error: before-tree must be a directory\n"); return NO; } - + if (![[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory] || !isDirectory) { printUsage(programName); fprintf(stderr, "Error: after-tree must be a directory\n"); return NO; } - + NSError *createDiffError = nil; if (!createBinaryDelta(sourcePath, destPath, patchPath, patchVersion, verbose, &createDiffError)) { fprintf(stderr, "%s\n", [createDiffError.localizedDescription UTF8String]); return NO; } - + return YES; } @@ -130,45 +130,45 @@ static BOOL runApplyCommand(NSString *programName, NSArray *args) printUsage(programName); return NO; } - + BOOL verbose = [args containsObject:VERBOSE_FLAG]; - + if (args.count == 4 && !verbose) { printUsage(programName); return NO; } - + NSMutableArray *fileArgs = [NSMutableArray array]; for (NSString *argument in args) { if (![argument isEqualToString:VERBOSE_FLAG]) { [fileArgs addObject:argument]; } } - + if (fileArgs.count != 3) { printUsage(programName); return NO; } - + BOOL isDirectory; if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) { printUsage(programName); fprintf(stderr, "Error: before-tree must be a directory\n"); return NO; } - + if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[2] isDirectory:&isDirectory] || isDirectory) { printUsage(programName); fprintf(stderr, "Error: patch-file must be a file %d\n", isDirectory); return NO; } - + NSError *applyDiffError = nil; if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, ^(__unused double x){}, &applyDiffError)) { fprintf(stderr, "%s\n", [applyDiffError.localizedDescription UTF8String]); return NO; } - + return YES; } @@ -178,7 +178,7 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args) printUsage(programName); return NO; } - + if (args.count == 0) { fprintf(stdout, "%u.%u\n", LATEST_DELTA_DIFF_MAJOR_VERSION, latestMinorVersionForMajorVersion(LATEST_DELTA_DIFF_MAJOR_VERSION)); } else { @@ -196,22 +196,22 @@ static BOOL runVersionCommand(NSString *programName, NSArray *args) for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) { if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) { const char *value = 0; - + // available in version 2.0 or later xar_subdoc_prop_get(subdoc, MAJOR_DIFF_VERSION_KEY, &value); if (value) majorDiffVersion = (SUBinaryDeltaMajorVersion)[@(value) intValue]; - + // available in version 2.0 or later xar_subdoc_prop_get(subdoc, MINOR_DIFF_VERSION_KEY, &value); if (value) minorDiffVersion = [@(value) intValue]; } } - + fprintf(stdout, "%u.%u\n", majorDiffVersion, minorDiffVersion); } - + return YES; } @@ -220,7 +220,7 @@ int main(int __unused argc, char __unused *argv[]) @autoreleasepool { NSArray *args = [[NSProcessInfo processInfo] arguments]; NSString *programName = [args[0] lastPathComponent]; - + if (args.count < 2) { printUsage(programName); return 1; @@ -228,7 +228,7 @@ int main(int __unused argc, char __unused *argv[]) NSString *command = args[1]; NSArray *commandArguments = [args subarrayWithRange:NSMakeRange(2, args.count - 2)]; - + BOOL result; if ([command isEqualToString:CREATE_COMMAND]) { result = runCreateCommand(programName, commandArguments); @@ -240,7 +240,7 @@ int main(int __unused argc, char __unused *argv[]) result = NO; printUsage(programName); } - + return result ? 0 : 1; } } From 03abfe273983df712856bd1fb737c7d70329dc36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sat, 28 Jan 2017 12:10:03 +0000 Subject: [PATCH 14/39] Fix #1020 --- generate_appcast/ArchiveItem.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generate_appcast/ArchiveItem.swift b/generate_appcast/ArchiveItem.swift index 73533d8c..2152bcd2 100644 --- a/generate_appcast/ArchiveItem.swift +++ b/generate_appcast/ArchiveItem.swift @@ -65,7 +65,7 @@ class ArchiveItem: CustomStringConvertible { throw makeError(code: .unarchivingError, "Too many apps in \(unarchivedDir.path) \(apps)"); } - let appPath = items[0]; + let appPath = apps[0]; guard let infoPlist = NSDictionary(contentsOf: appPath.appendingPathComponent("Contents/Info.plist")) else { throw makeError(code: .unarchivingError, "No plist \(appPath.path)"); } From dc1d83e90443d1c8810a0a142ba6e5fb050a6234 Mon Sep 17 00:00:00 2001 From: Zorg Date: Wed, 1 Feb 2017 23:56:17 -0500 Subject: [PATCH 15/39] Add my name to LICENSE --- LICENSE | 1 + 1 file changed, 1 insertion(+) diff --git a/LICENSE b/LICENSE index f4020f8d..1e9b1c6e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ Copyright (c) 2006-2013 Andy Matuschak. Copyright (c) 2009-2013 Elgato Systems GmbH. Copyright (c) 2011-2014 Kornel Lesiński. +Copyright (c) 2015-2017 Mayur Pawashe. Copyright (c) 2014 C.W. Betts. Copyright (c) 2014 Petroules Corporation. Copyright (c) 2014 Big Nerd Ranch. From 1f98f9eb36402273fb7aa445da91ad0d4b6dee7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Va=CC=81clav=20Slavi=CC=81k?= Date: Sun, 5 Feb 2017 18:29:22 +0100 Subject: [PATCH 16/39] Don't touch Info.plist unless git version changes PlistBuddy always touches its output file, even if the value written is identical to the value already there. In such case, Xcode sees Info.plist as modified, therefore sees the entire target as modified and re-runs potentially expensive operations like copying frameworks or signing. Avoid unnecessary build operations by checking the previous CFBundleShortVersionString if Info.plist already exists and only updating it if necessary. --- Configurations/set-git-version-info.sh | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Configurations/set-git-version-info.sh b/Configurations/set-git-version-info.sh index f1f31624..2f2a0860 100755 --- a/Configurations/set-git-version-info.sh +++ b/Configurations/set-git-version-info.sh @@ -30,5 +30,11 @@ fi # and use it to set the CFBundleShortVersionString value export PATH="$PATH:/usr/libexec" -PlistBuddy -c "Set :CFBundleShortVersionString '$version'" \ - "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH" + +if [ -f "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH" ] ; then + oldversion=$(PlistBuddy -c "Print :CFBundleShortVersionString" "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH") +fi +if [ "$version" != "$oldversion" ] ; then + PlistBuddy -c "Set :CFBundleShortVersionString '$version'" \ + "$BUILT_PRODUCTS_DIR/$INFOPLIST_PATH" +fi From d27c12f1fc06b71388aa18539bff49a2ed7a7deb Mon Sep 17 00:00:00 2001 From: BR Lingo Date: Mon, 6 Feb 2017 01:15:22 -0500 Subject: [PATCH 17/39] Update Sparkle.strings Terminology consistency update. --- Sparkle/pt_BR.lproj/Sparkle.strings | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sparkle/pt_BR.lproj/Sparkle.strings b/Sparkle/pt_BR.lproj/Sparkle.strings index 0a18525d..a21c76aa 100755 --- a/Sparkle/pt_BR.lproj/Sparkle.strings +++ b/Sparkle/pt_BR.lproj/Sparkle.strings @@ -1,6 +1,6 @@ -"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ foi transferido e está pronto para uso! Deseja instalar e reiniciar o %1$@ agora?"; +"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ foi transferido e está pronto para uso! Deseja instalar e rabrir o %1$@ agora?"; -"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ não pode ser atualizado enquanto for executado a partir de um volume somente de leitura, como uma imagem de disco ou CD/DVD. Mova o %1$@ para a pasta Aplicativos, reinicie-o e tente novamente."; +"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ não pode ser atualizado enquanto for executado a partir de um volume somente de leitura, como uma imagem de disco ou CD/DVD. Mova o %1$@ para a pasta Aplicativos, rabra-o e tente novamente."; "%@ %@ is currently the newest version available." = "%1$@ %2$@ é a versão mais recente disponível."; From 9318b9f896b63cd6078d48c58c62bc7b547d99b6 Mon Sep 17 00:00:00 2001 From: BR Lingo Date: Mon, 6 Feb 2017 01:18:26 -0500 Subject: [PATCH 18/39] Update Sparkle.strings Terminology consistency update. --- Sparkle/pt_BR.lproj/Sparkle.strings | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sparkle/pt_BR.lproj/Sparkle.strings b/Sparkle/pt_BR.lproj/Sparkle.strings index a21c76aa..a39ebe5a 100755 --- a/Sparkle/pt_BR.lproj/Sparkle.strings +++ b/Sparkle/pt_BR.lproj/Sparkle.strings @@ -1,6 +1,6 @@ -"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ foi transferido e está pronto para uso! Deseja instalar e rabrir o %1$@ agora?"; +"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ foi transferido e está pronto para uso! Deseja instalar e reabrir o %1$@ agora?"; -"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ não pode ser atualizado enquanto for executado a partir de um volume somente de leitura, como uma imagem de disco ou CD/DVD. Mova o %1$@ para a pasta Aplicativos, rabra-o e tente novamente."; +"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ não pode ser atualizado enquanto for executado a partir de um volume somente de leitura, como uma imagem de disco ou CD/DVD. Mova o %1$@ para a pasta Aplicativos, reabra-o e tente novamente."; "%@ %@ is currently the newest version available." = "%1$@ %2$@ é a versão mais recente disponível."; From 9a07c5125e82918bffafefbc9788e12a6a568d83 Mon Sep 17 00:00:00 2001 From: Zorg Date: Mon, 6 Feb 2017 08:20:48 -0500 Subject: [PATCH 19/39] Detect and fail if any two-way dependencies exist in the project While this may or may not be perfect, this should improve code quality by preventing new code that is introduced that creates tight coupling. This test is performed when make test is executed. I avoided retrieving objc_dep in a way that make test would require an internet connection. I also added the executable bit to the objc_dep script, and a source.txt file indicating where the source came from. --- Makefile | 1 + objc_dep/README.md | 108 ++++++++++++++++++ objc_dep/objc_dep.py | 265 +++++++++++++++++++++++++++++++++++++++++++ objc_dep/source.txt | 3 + 4 files changed, 377 insertions(+) create mode 100644 objc_dep/README.md create mode 100755 objc_dep/objc_dep.py create mode 100644 objc_dep/source.txt diff --git a/Makefile b/Makefile index 2a866944..aa89d64f 100644 --- a/Makefile +++ b/Makefile @@ -21,6 +21,7 @@ build: test: xcodebuild -scheme Distribution -configuration Debug test + ./objc_dep/objc_dep.py -t . uitest: xcodebuild -scheme UITests -configuration Debug test diff --git a/objc_dep/README.md b/objc_dep/README.md new file mode 100644 index 00000000..6ed3c2f4 --- /dev/null +++ b/objc_dep/README.md @@ -0,0 +1,108 @@ +- 2013-04-17 merged changes from mikkelee who [added](https://github.com/nst/objc_dep/pull/6) to use a single bidirectional arrow for two-way dependencies +- 2013-02-21 merged changes from jomnius who [added](https://github.com/nst/objc_dep/pull/4) a parameter to exclude directories names by regex +- 2012-05-11 merged changes from jonreid who [added](https://github.com/nst/objc_dep/pull/3) a parameter to exclude class names by regex +- 2012-01-11 merged changes from jomnius who [added](https://github.com/nst/objc_dep/pull/1) support for C projects and better handling of categories +- read [Object graph dependency analysis](http://samuelgoodwin.tumblr.com/post/18345393597/object-graph-dependency-analysis) by Samuel Goodwin +- see also jominus blog post [Dependency Graph Tool for iOS Projects](http://jomnius.blogspot.com/2012/01/dependency-graph-tool-for-ios-projects.html) +- yet another use case on vigorouscoding.com [Better get it right the first time](http://www.vigorouscoding.com/2011/12/better-get-it-right-the-first-time/) + +# License + + BSD 3-Clause License + + Copyright (c) 2012-2013, Nicolas Seriot All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the Nicolas Seriot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Refactoring by graphing class dependencies + +### Code design and loose coupling + +As developers, we all love clean code, but the fact is that most of the time we're dealing with bad code. It may be recent or legacy code, written by ourselves or by other developers. We can recognize bad code because [code](http://en.wikipedia.org/wiki/Code_smell) [smells](http://www.codinghorror.com/blog/2006/05/code-smells.html). In other words, some heuristics raise questions about code quality. Among thoses we can name dead code, which I already wrote about [here](http://seriot.ch/blog.php?article=20080728) and [here](http://seriot.ch/blog.php?article=20100301), and tight coupling. + +Tight coupling describes a system where many components depend on many other components. A tightly coupled code base stinks, the coupling points out that some classes assume too many responsibilities or that a responsability is spread over several classes, rather than having its own class. The opposite, loose coupling, shows a better design which promotes single-responsibility and separation of concerns. Loose coupling makes the code easier to test and maintain. + +In Objective-C, reducing coupling generally involves [delegates](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html) and [notifications](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html%23//apple_ref/doc/uid/10000043i). + +### Graphing class dependencies + +So how do we achieve loose coupling in our own code? Well, at first, we need to get a better idea on the current coupling. Let us define class dependency: _class A depends on B if class A imports class B header_. With such a definition, we can draw a graph of dependencies between classes by considering the Objective-C `#import` directives in each class. We assume here that the files are named according to the classes they contain. + +I wrote [objc_dep.py](https://github.com/nst/objc_dep), a Python script which extracts imports from Objective-C source code. The output can then be displayed in [GraphViz](http://www.graphviz.org/) or [OmniGraffle](http://www.omnigroup.com/products/omnigraffle/). You can then see an oriented graph of dependencies between classes. Note that we could also compute metrics on coupling, but it's not the point here. + +### Sample usage + +How do we get from the dependencies graph to a better design? There's no determinist algorithm and it depends on your project. Let us apply the script on [FSWalker](http://code.google.com/p/fswalker/), a small iPhone file browser I wrote a long time ago. + +#### 1. Generate the graph + + $ python objc_dep.py /path/to/FSWalker > fswalker.dot + +#### 2. Open it in OmniGraffle + +At this point, we see classes as nodes and dependencies as directed edges. + + + +#### 3. Remove categories + +We can safely remove Objective-C [categories](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCategories.html) from the graph, since referencing categories from many places is not an issue from a design point of view. + + + +#### 4. Group related classes + +Next, we can move the vertices around, try to group classes with a common responsibility into clusters. + + + +#### 5. Study strange dependencies + +The graph now gives a pretty good overview of the overall code structure. The controller objects have been colored in pink, the model objects in yellow and the network part in blue. The graph allows to sport strange dependencies and question the code design. We can see at first glance that FSWalkerAppDelegate has too many dependencies. Specifically we consider: + +a) unreferenced classes or clusters + +This is probably dead code, which can be removed. + +Ok, there are no unreferenced classes here, although you will probably find some in bigger projects. + +b) two-ways references + +Maybe one class should not reference another directly, but reference a protocol implemented by the other class instead. + +We have two examples of two-ways references here, between HTTPServer and HTTPConnection, and also between RootViewController and FSWalkerAppDelegate. The former is part of [CocoaHTTPServer](http://code.google.com/p/cocoahttpserver/) and is not a design issue in our project. However, the latter is an issue. By looking at the code, we will notice that RootViewController doesn't actually use FSWalkerAppDelegate. The import can thus be safely removed. + +c) weird references + +Some of the import directives may simply be unnecessary, or reveal design issues. + +There is no good reason why FSWalkerAppDelegate would reference FSItem, nor InfoPanelController. Code inspection will reveal that DetailViewController and InfoPanelController should not be referenced by FSWalkerAppDelegate but RootViewController instead. So, here is the final graph. The architecture of FSWalker may still be improved, but you get the idea... + + + +### Real world usage + +Here is the kind of chart you can expect with a 100 classes project. + + + +#### Using options + +`% python objc_dep.py /path/to/repo -x "(^Internal|secret)" -i subdir1 subdir2 > graph.dot` + +Will exclude files with names that begin with "Internal", or contain the word "secret". Additionally all files in folders named subdir1 and subdir2 are ignored. + +### Possible improvements + +The Cocoa framework enforces the [MVC paradigm](http://developer.apple.com/technologies/mac/cocoa.html), which states (to be short) that model objects and graphical objects should be clearly separated by controller objects. The script could probably be improved by drawing classes which depend on Foundation and classes which depend on AppKit/UIKit with different colors. + +### Conclusion + +I have found [objc_dep.py](https://github.com/nst/objc_dep) to be definitely useful on small projects as well as bigger ones. It helped me in getting a clear view of code base structure. Spotting strange dependencies allowed me to ask good questions which led to design simplifications. Such a tool could even be integrated into Apple development tools. + +Interestingly, the last chart is quite close to the mental representation I have of the code architecture. It reminds me a discussion I had 15 years ago with a friend who was a champion chess player who could play several "blind" chess games simultaneously. He explained then that he saw a blurry chessboard in his head and could move around the pieces as with a small 3D camera. Focusing on a specific piece would then raise awareness of opportunities and risks - dependencies - for this piece. As a side effect, writing this script made me realize that software engineering is pretty similar to chess in this way. diff --git a/objc_dep/objc_dep.py b/objc_dep/objc_dep.py new file mode 100755 index 00000000..b95fe806 --- /dev/null +++ b/objc_dep/objc_dep.py @@ -0,0 +1,265 @@ +#!/usr/bin/python + +# Nicolas Seriot +# 2011-01-06 -> 2011-12-16 +# https://github.com/nst/objc_dep/ + +""" +Input: path of an Objective-C project + +Output: import dependencies Graphviz format, unless --test is passed in which case outputs a successful exit status of 0 if no two-way dependencies are found + +Typical usage: $ python objc_dep.py /path/to/project [-x regex] [-i subfolder [subfolder ...]] > graph.dot + +The .dot file can be opened with Graphviz or OmniGraffle. + +- red arrows: .pch imports +- blue arrows: two ways imports +""" + +import sys +import os +from sets import Set +import re +from os.path import basename +import argparse + +local_regex_import = re.compile("^\s*#(?:import|include)\s+\"(?P\S*)(?P\.(?:h|hpp|hh))?\"") +system_regex_import = re.compile("^\s*#(?:import|include)\s+[\"<](?P\S*)(?P\.(?:h|hpp|hh))?[\">]") +objc_extensions = ['.h', '.hh', '.hpp', '.m', '.mm', '.c', '.cc', '.cpp'] + +def gen_filenames_imported_in_file(path, regex_exclude, system, extensions): + for line in open(path): + results = re.search(system_regex_import, line) if system else re.search(local_regex_import, line) + if results: + filename = results.group('filename') + extension = results.group('extension') if results.group('extension') else "" + if regex_exclude is not None and regex_exclude.search(filename + extension): + continue + yield (filename + extension) if extension else filename + +def dependencies_in_project(path, ext, exclude, ignore, system, extensions): + d = {} + + regex_exclude = None + if exclude: + regex_exclude = re.compile(exclude) + + for root, dirs, files in os.walk(path): + + if ignore: + for subfolder in ignore: + if subfolder in dirs: + dirs.remove(subfolder) + + objc_files = (f for f in files if f.endswith(ext)) + + for f in objc_files: + + filename = f if extensions else os.path.splitext(f)[0] + if regex_exclude is not None and regex_exclude.search(filename): + continue + + if filename not in d: + d[filename] = Set() + + path = os.path.join(root, f) + + for imported_filename in gen_filenames_imported_in_file(path, regex_exclude, system, extensions): + if imported_filename != filename and '+' not in imported_filename and '+' not in filename: + imported_filename = imported_filename if extensions else os.path.splitext(imported_filename)[0] + d[filename].add(imported_filename) + + return d + +def dependencies_in_project_with_file_extensions(path, exts, exclude, ignore, system, extensions, root_class): + + d = {} + + for ext in exts: + d2 = dependencies_in_project(path, ext, exclude, ignore, system, extensions) + for (k, v) in d2.iteritems(): + if not k in d: + d[k] = Set() + d[k] = d[k].union(v) + + if root_class: + def parse_requirements(tree, root, known_deps=[]): + next_deps = list(tree[root]) + new_deps = [] + + for dep in next_deps: + if dep not in known_deps and dep in tree: + new_deps += parse_requirements(tree, dep, known_deps + next_deps) + + return (new_deps + next_deps) + + requirements = set(parse_requirements(d, root_class)) + + return { k: d[k] for k in requirements if k in d} + + return d + +def two_ways_dependencies(d): + + two_ways = Set() + + # d is {'a1':[b1, b2], 'a2':[b1, b3, b4], ...} + + for a, l in d.iteritems(): + for b in l: + if b in d and a in d[b]: + if (a, b) in two_ways or (b, a) in two_ways: + continue + if a != b: + two_ways.add((a, b)) + + return two_ways + +def untraversed_files(d): + + dead_ends = Set() + + for file_a, file_a_dependencies in d.iteritems(): + for file_b in file_a_dependencies: + if not file_b in dead_ends and not file_b in d: + dead_ends.add(file_b) + + return dead_ends + +def category_files(d): + d2 = {} + l = [] + + for k, v in d.iteritems(): + if not v and '+' in k: + l.append(k) + else: + d2[k] = v + + return l, d2 + +def referenced_classes_from_dict(d): + d2 = {} + + for k, deps in d.iteritems(): + for x in deps: + d2.setdefault(x, Set()) + d2[x].add(k) + + return d2 + +def print_frequencies_chart(d): + + lengths = map(lambda x:len(x), d.itervalues()) + if not lengths: return + max_length = max(lengths) + + for i in range(0, max_length+1): + s = "%2d | %s\n" % (i, '*'*lengths.count(i)) + sys.stderr.write(s) + + sys.stderr.write("\n") + + l = [Set() for i in range(max_length+1)] + for k, v in d.iteritems(): + l[len(v)].add(k) + + for i in range(0, max_length+1): + s = "%2d | %s\n" % (i, ", ".join(sorted(list(l[i])))) + sys.stderr.write(s) + +def dependencies_in_dot_format(path, exclude, ignore, system, extensions, root_class): + + d = dependencies_in_project_with_file_extensions(path, objc_extensions, exclude, ignore, system, extensions, root_class) + + two_ways_set = two_ways_dependencies(d) + untraversed_set = untraversed_files(d) + + category_list, d = category_files(d) + + pch_set = dependencies_in_project(path, '.pch', exclude, ignore, system, extensions) + + # + + sys.stderr.write("# number of imports\n\n") + print_frequencies_chart(d) + + sys.stderr.write("\n# times the class is imported\n\n") + d2 = referenced_classes_from_dict(d) + print_frequencies_chart(d2) + + # + + l = [] + l.append("digraph G {") + l.append("\tnode [shape=box];") + + for k, deps in d.iteritems(): + if deps: + deps.discard(k) + + if len(deps) == 0: + l.append("\t\"%s\" -> {};" % (k)) + + for k2 in deps: + if not ((k, k2) in two_ways_set or (k2, k) in two_ways_set): + l.append("\t\"%s\" -> \"%s\";" % (k, k2)) + + l.append("\t") + for (k, v) in pch_set.iteritems(): + l.append("\t\"%s\" [color=red];" % k) + for x in v: + l.append("\t\"%s\" -> \"%s\" [color=red];" % (k, x)) + + l.append("\t") + l.append("\tedge [color=blue, dir=both];") + + for (k, k2) in two_ways_set: + l.append("\t\"%s\" -> \"%s\";" % (k, k2)) + + for k in untraversed_set: + l.append("\t\"%s\" [color=gray, style=dashed, fontcolor=gray]" % k) + + if category_list: + l.append("\t") + l.append("\tedge [color=black];") + l.append("\tnode [shape=plaintext];") + l.append("\t\"Categories\" [label=\"%s\"];" % "\\n".join(category_list)) + + if ignore: + l.append("\t") + l.append("\tnode [shape=box, color=blue];") + l.append("\t\"Ignored\" [label=\"%s\"];" % "\\n".join(ignore)) + + l.append("}\n") + return '\n'.join(l) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("-x", "--exclude", nargs='?', default='' ,help="regular expression of substrings to exclude from module names") + parser.add_argument("-i", "--ignore", nargs='*', help="list of subfolder names to ignore") + parser.add_argument("-s", "--system", action='store_true', default=False, help="include system dependencies") + parser.add_argument("-e", "--extensions", action='store_true', default=False, help="print file extensions") + parser.add_argument("-r", "--root", default='', help="Class to use as root of dependency graph") + parser.add_argument("-t", "--test", action='store_true', default=False, help="Exit with a success status of 0 if no two-way dependencies exist or failure otherwise, instead of outputting a graph") + parser.add_argument("project_path", help="path to folder hierarchy containing Objective-C files") + args= parser.parse_args() + + if not args.test: + print dependencies_in_dot_format(args.project_path, args.exclude, args.ignore, args.system, args.extensions, args.root) + else: + # Test if two-way dependencies exist. If none do, then exit on success (0), otherwise exit on failure (1) + d = dependencies_in_project_with_file_extensions(args.project_path, objc_extensions, args.exclude, args.ignore, args.system, args.extensions, args.root) + two_ways_set = two_ways_dependencies(d) + + if len(two_ways_set) == 0: + sys.exit(0) + else: + sys.stderr.write("Error: Found two way dependencies:\n") + for (k, k2) in two_ways_set: + sys.stderr.write("%s <-> %s\n" % (k, k2)) + sys.exit(1) + +if __name__=='__main__': + main() diff --git a/objc_dep/source.txt b/objc_dep/source.txt new file mode 100644 index 00000000..28399ce0 --- /dev/null +++ b/objc_dep/source.txt @@ -0,0 +1,3 @@ +Source: https://github.com/nst/objc_dep/ +License: See README.md +Commit: c73b097d8de0fbca8b9468cf25aaef398d66c68f From c0d46405087bf45c21a0f2bd940c7792672bf967 Mon Sep 17 00:00:00 2001 From: Brett Walker Date: Wed, 8 Feb 2017 22:40:37 +0100 Subject: [PATCH 20/39] percent encode the filename used in the delta url --- generate_appcast/FeedXML.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generate_appcast/FeedXML.swift b/generate_appcast/FeedXML.swift index 5dbc8d0b..f6b10800 100644 --- a/generate_appcast/FeedXML.swift +++ b/generate_appcast/FeedXML.swift @@ -142,7 +142,7 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { } for delta in update.deltas { var attributes = [ - XMLNode.attribute(withName: "url", stringValue: URL(string: delta.archivePath.lastPathComponent, relativeTo: update.archiveURL)!.absoluteString) as! XMLNode, + XMLNode.attribute(withName: "url", stringValue: URL(string: delta.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed)!, relativeTo: update.archiveURL)!.absoluteString) as! XMLNode, XMLNode.attribute(withName: "sparkle:version", uri: sparkleNS, stringValue: update.version) as! XMLNode, XMLNode.attribute(withName: "sparkle:deltaFrom", uri: sparkleNS, stringValue: delta.fromVersion) as! XMLNode, XMLNode.attribute(withName: "length", stringValue: String(delta.fileSize)) as! XMLNode, From f43c83688d61caca0a737ef69ce5b73acbb77d59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Thu, 9 Feb 2017 00:04:10 +0000 Subject: [PATCH 21/39] Changelog --- CHANGELOG | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 971762dc..d2d44059 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,6 +10,13 @@ * Added Obj-C generics where applicable (Zorg) * Made SUBundleIcon & SUApplicationInfo take SUHost, not NSBundle (Zorg) * Improved -[SUHost objectForInfoDictionaryKey:] (Zorg) + * Detect and fail if any two-way dependencies exist in the project (Zorg) + * generate_appcast: + * fixed handling of multiple directories in an archive + * percent encode the filename used in the delta url (Brett Walker) + * Update Sparkle.strings (BR Lingo) + * Improved handling of non-ASCII names in delta archives (Kornel Lesiński) + * Don't touch Info.plist unless git version changes (Václav Slavík) # 1.16.0 From 5210e1d3acf7bb57ff25d301d18cf9ec963123ab Mon Sep 17 00:00:00 2001 From: Brett Walker Date: Fri, 10 Feb 2017 16:53:30 +0100 Subject: [PATCH 22/39] added `sparkle:shortVersionString` to the enclosure, #1032 --- generate_appcast/FeedXML.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/generate_appcast/FeedXML.swift b/generate_appcast/FeedXML.swift index f6b10800..4492a999 100644 --- a/generate_appcast/FeedXML.swift +++ b/generate_appcast/FeedXML.swift @@ -123,6 +123,7 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { var attributes = [ XMLNode.attribute(withName: "url", stringValue: archiveURL) as! XMLNode, XMLNode.attribute(withName: "sparkle:version", uri: sparkleNS, stringValue: update.version) as! XMLNode, + XMLNode.attribute(withName: "sparkle:shortVersionString", 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, ]; @@ -144,6 +145,7 @@ func writeAppcast(appcastDestPath: URL, updates: [ArchiveItem]) throws { var attributes = [ XMLNode.attribute(withName: "url", stringValue: URL(string: delta.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed)!, relativeTo: update.archiveURL)!.absoluteString) as! XMLNode, XMLNode.attribute(withName: "sparkle:version", uri: sparkleNS, stringValue: update.version) as! XMLNode, + XMLNode.attribute(withName: "sparkle:shortVersionString", uri: sparkleNS, stringValue: update.shortVersion) as! XMLNode, XMLNode.attribute(withName: "sparkle:deltaFrom", 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, From 40347c0d435f28dd12080b7bb104c3a26c8a867f Mon Sep 17 00:00:00 2001 From: George Nachman Date: Mon, 13 Feb 2017 19:38:49 -0800 Subject: [PATCH 23/39] Disable the keyboard shortcut for the install button for scheduled updates to avoid accidental installs. --- Sparkle/SUScheduledUpdateDriver.m | 4 ++++ Sparkle/SUUIBasedUpdateDriver.m | 14 +++++++++++--- Sparkle/SUUpdateAlert.h | 1 + Sparkle/SUUpdateAlert.m | 3 +++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Sparkle/SUScheduledUpdateDriver.m b/Sparkle/SUScheduledUpdateDriver.m index fcd1c853..18f4826c 100644 --- a/Sparkle/SUScheduledUpdateDriver.m +++ b/Sparkle/SUScheduledUpdateDriver.m @@ -56,4 +56,8 @@ } } +- (BOOL)shouldDisableKeyboardShortcutForInstallButton { + return YES; +} + @end diff --git a/Sparkle/SUUIBasedUpdateDriver.m b/Sparkle/SUUIBasedUpdateDriver.m index e0f5cb90..5e1de6f3 100644 --- a/Sparkle/SUUIBasedUpdateDriver.m +++ b/Sparkle/SUUIBasedUpdateDriver.m @@ -85,12 +85,20 @@ } // Only show the update alert if the app is active; otherwise, we'll wait until it is. - if ([NSApp isActive]) - [[self.updateAlert window] makeKeyAndOrderFront:self]; - else + if ([NSApp isActive]) { + NSWindow *window = [self.updateAlert window]; + if ([self shouldDisableKeyboardShortcutForInstallButton]) { + [self.updateAlert disableKeyboardShortcutForInstallButton]; + } + [window makeKeyAndOrderFront:self]; + } else [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; } +- (BOOL)shouldDisableKeyboardShortcutForInstallButton { + return NO; +} + - (void)didNotFindUpdate { id updater = self.updater; diff --git a/Sparkle/SUUpdateAlert.h b/Sparkle/SUUpdateAlert.h index 30b04540..1c6ccd47 100644 --- a/Sparkle/SUUpdateAlert.h +++ b/Sparkle/SUUpdateAlert.h @@ -31,6 +31,7 @@ typedef NS_ENUM(NSInteger, SUUpdateAlertChoice) { - (IBAction)installUpdate:sender; - (IBAction)skipThisVersion:sender; - (IBAction)remindMeLater:sender; +- (void)disableKeyboardShortcutForInstallButton; @end diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index 0a674f4d..3b345ba5 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -93,6 +93,9 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } +- (void)disableKeyboardShortcutForInstallButton { + self.installButton.keyEquivalent = @""; +} - (void)endWithSelection:(SUUpdateAlertChoice)choice { From 83195a802e87eba2893971803ed67dc1027bbd12 Mon Sep 17 00:00:00 2001 From: fujisoft Date: Mon, 20 Feb 2017 00:50:36 +0900 Subject: [PATCH 24/39] Fix pt_BR translations "Translation Error Correction" It must have a faithful consistency to the translation terminologies of Apple Inc. --- Sparkle/pt_BR.lproj/Sparkle.strings | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Sparkle/pt_BR.lproj/Sparkle.strings b/Sparkle/pt_BR.lproj/Sparkle.strings index a39ebe5a..6e54df44 100755 --- a/Sparkle/pt_BR.lproj/Sparkle.strings +++ b/Sparkle/pt_BR.lproj/Sparkle.strings @@ -1,14 +1,14 @@ -"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ foi transferido e está pronto para uso! Deseja instalar e reabrir o %1$@ agora?"; +"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?" = "%1$@ %2$@ foi transferido e está pronto para uso! Você gostaria de instalar e recarregar o %1$@ agora?"; -"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ não pode ser atualizado enquanto for executado a partir de um volume somente de leitura, como uma imagem de disco ou CD/DVD. Mova o %1$@ para a pasta Aplicativos, reabra-o e tente novamente."; +"%1$@ can't be updated when it's running from a read-only volume like a disk image or an optical drive. Move %1$@ to your Applications folder, relaunch it from there, and try again." = "%1$@ não pode ser atualizado enquanto for executado de um volume somente de leitura, como uma imagem de disco ou CD/DVD. Mova o %1$@ para a pasta Aplicativos, recarregue-o e tente novamente."; "%@ %@ is currently the newest version available." = "%1$@ %2$@ é a versão mais recente disponível."; /* Description text for SUUpdateAlert when the update is downloadable. */ -"%@ %@ is now available--you have %@. Would you like to download it now?" = "%1$@ %2$@ está disponível – sua versão é %3$@. Deseja transferi-lo agora?"; +"%@ %@ is now available--you have %@. Would you like to download it now?" = "%1$@ %2$@ está disponível – sua versão é %3$@. Você gostaria de transferi-lo agora?"; /* Description text for SUUpdateAlert when the update informational with no download. */ -"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ está disponível – sua versão é %3$@. Deseja saber mais sobre esta atualização na web?"; +"%@ %@ is now available--you have %@. Would you like to learn more about this update on the web?" = "%1$@ %2$@ está disponível – sua versão é %3$@. Você gostaria de saber mais sobre esta atualização na web?"; "%@ downloaded" = "%@ transferidos"; @@ -22,13 +22,13 @@ "An error occurred while downloading the update. Please try again later." = "Ocorreu um erro ao transferir a atualização. Tente novamente mais tarde."; -"An error occurred while extracting the archive. Please try again later." = "Ocorreu um erro ao extrair o arquivo comprimido. Tente novamente mais tarde."; +"An error occurred while extracting the archive. Please try again later." = "Ocorreu um erro ao extrair o arquivo compactado. Tente novamente mais tarde."; "An error occurred while installing the update. Please try again later." = "Ocorreu um erro ao instalar a atualização. Tente novamente mais tarde."; -"An error occurred while parsing the update feed." = "Ocorreu um erro ao analisar o feed de atualização."; +"An error occurred while parsing the update feed." = "Ocorreu um erro ao analisar a alimentação de atualização."; -"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@." = "Ocorreu um erro ao reabrir o %1$@. A nova versão estará disponível da próxima vez que você abrir o %1$@."; +"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@." = "Ocorreu um erro ao recarregar o %1$@. A nova versão estará disponível da próxima vez que você executar o %1$@."; /* the unit for bytes */ "B" = "B"; @@ -37,7 +37,7 @@ "Cancel Update" = "Cancelar Atualização"; -"Checking for updates..." = "Buscando atualizações…"; +"Checking for updates..." = "Verificando atualizações…"; /* Take care not to overflow the status window. */ "Downloading update..." = "Transferindo atualização…"; @@ -48,10 +48,10 @@ /* the unit for gigabytes */ "GB" = "GB"; -"Install and Relaunch" = "Instalar e Reabrir"; +"Install and Relaunch" = "Instalar e Recarregar"; /* Take care not to overflow the status window. */ -"Installing update..." = "Instalando atualização…"; +"Installing update..." = "Instalando a atualização…"; /* the unit for kilobytes */ "KB" = "KB"; @@ -63,7 +63,7 @@ "Ready to Install" = "Pronto para Instalar"; -"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu." = "Deseja que o %1$@ busque atualizações automaticamente? Você pode buscar atualizações manualmente, através do menu %1$@."; +"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu." = "Você gostaria que o %1$@ verifique atualizações automaticamente? Você pode verificar atualizações manualmente, através do menu %1$@."; "Update Error!" = "Erro de Atualização!"; @@ -72,4 +72,3 @@ "You already have the newest version of %@." = "Você já possui a versão mais recente do %@."; "You're up-to-date!" = "Você está atualizado!"; - From 3b04c45ee986adc27bc1ff2d002cb645a670e3f0 Mon Sep 17 00:00:00 2001 From: fujisoft Date: Mon, 20 Feb 2017 19:22:15 +0900 Subject: [PATCH 25/39] Fix pt_BR translations (#1039) * Fix pt_BR translations --- Sparkle/pt_BR.lproj/Sparkle.strings | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sparkle/pt_BR.lproj/Sparkle.strings b/Sparkle/pt_BR.lproj/Sparkle.strings index 6e54df44..0a6a8c48 100755 --- a/Sparkle/pt_BR.lproj/Sparkle.strings +++ b/Sparkle/pt_BR.lproj/Sparkle.strings @@ -37,7 +37,7 @@ "Cancel Update" = "Cancelar Atualização"; -"Checking for updates..." = "Verificando atualizações…"; +"Checking for updates..." = "Buscar atualizações…"; /* Take care not to overflow the status window. */ "Downloading update..." = "Transferindo atualização…"; From e54748ac87377321e6a264e5cc407fdda9ceb1f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sun, 26 Feb 2017 18:01:07 +0000 Subject: [PATCH 26/39] Add more info to auth tool run failure --- Sparkle/SUFileManager.m | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 98800e3a..7b5e3e49 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -166,10 +166,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { FILE *pipe = NULL; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - if (AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe) != errAuthorizationSuccess) { + OSStatus runStatus = AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe); + if (runStatus != errAuthorizationSuccess) { #pragma clang diagnostic pop if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to run authorization tool." }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to run authorization tool %s (%d).", toolPath, (int)runStatus] }]; } return NO; } From 0a94a6ce882078bd3de5c88b97e97ea52785c412 Mon Sep 17 00:00:00 2001 From: 1024jp <1024jp@wolfrosch.com> Date: Tue, 28 Feb 2017 13:54:47 +0900 Subject: [PATCH 27/39] Fix Japanse localization Generalize message to user as the previous setence was more like "Anonymous system profile information is used to help **our company** plan future development work." --- Sparkle/ja.lproj/SUAutomaticUpdateAlert.xib | 14 ++++++++------ Sparkle/ja.lproj/SUUpdatePermissionPrompt.xib | 18 +++++++++--------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/Sparkle/ja.lproj/SUAutomaticUpdateAlert.xib b/Sparkle/ja.lproj/SUAutomaticUpdateAlert.xib index d5ea8ef9..e7087691 100644 --- a/Sparkle/ja.lproj/SUAutomaticUpdateAlert.xib +++ b/Sparkle/ja.lproj/SUAutomaticUpdateAlert.xib @@ -1,7 +1,9 @@ - + - + + + @@ -70,8 +72,8 @@ DQ - -