Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0828897f1b | ||
|
|
ff31a5fcdd | ||
|
|
016cd25fda | ||
|
|
afebefc78a | ||
|
|
3c7916e02e | ||
|
|
8d6063d9a9 | ||
|
|
24c118fa1e | ||
|
|
ff7b9de34f | ||
|
|
5994cf9584 | ||
|
|
518ee666a3 | ||
|
|
73cc6802d3 | ||
|
|
1403a7ad81 | ||
|
|
24d9ef1f86 | ||
|
|
51bd593666 | ||
|
|
44a471b903 | ||
|
|
6e2f4faa3f | ||
|
|
43fd18e4c9 | ||
|
|
d08804ddce | ||
|
|
39a47ac14f | ||
|
|
49148013dc | ||
|
|
15c80b1cbf | ||
|
|
f89762550f | ||
|
|
b224b30a27 | ||
|
|
bfa660b5bc | ||
|
|
3ed1dc26fa | ||
|
|
442e51b89d | ||
|
|
a8b6a9f262 | ||
|
|
05019c8e82 | ||
|
|
d569a6524e | ||
|
|
5c64d501f4 | ||
|
|
ee8c781284 | ||
|
|
d8b1c4b6ca | ||
|
|
3582cdec0b | ||
|
|
ef169d19e9 | ||
|
|
582593dca7 | ||
|
|
ba6df2df14 | ||
|
|
65463d7612 | ||
|
|
1f38d749ea | ||
|
|
c4871aa371 | ||
|
|
f067d6b778 | ||
|
|
2c10c116e9 | ||
|
|
cfc2d55ca9 | ||
|
|
daaf62645e | ||
|
|
f34c02b79b | ||
|
|
5d5f5eaa12 | ||
|
|
40e5ac130e | ||
|
|
e449f18bd3 | ||
|
|
6d4f8a731b | ||
|
|
9debcdcd57 | ||
|
|
4d489e5add | ||
|
|
60f4089f6f | ||
|
|
33d2c31db9 | ||
|
|
267cd56bd6 | ||
|
|
2a4147f3b1 | ||
|
|
fb991f348b | ||
|
|
839f4a9708 | ||
|
|
e142e1bef0 | ||
|
|
14892783cd | ||
|
|
88c65394c1 | ||
|
|
afc0ad0b20 | ||
|
|
0c533da4d7 | ||
|
|
a5f8798ce8 | ||
|
|
ab52a12630 | ||
|
|
954de5d480 | ||
|
|
df71c4d256 | ||
|
|
d73df99d57 | ||
|
|
bfc2652481 | ||
|
|
90f31dd0f8 | ||
|
|
470338574f |
+6
-19
@@ -1,22 +1,9 @@
|
||||
[submodule "External/ReactiveCocoa"]
|
||||
path = External/ReactiveCocoa
|
||||
url = https://github.com/ReactiveCocoa/ReactiveCocoa.git
|
||||
[submodule "External/Mantle"]
|
||||
path = External/Mantle
|
||||
url = https://github.com/MantleFramework/Mantle.git
|
||||
[submodule "External/OHHTTPStubs"]
|
||||
path = External/OHHTTPStubs
|
||||
url = https://github.com/github/OHHTTPStubs
|
||||
[submodule "Carthage.checkout/Nimble"]
|
||||
path = Carthage/Checkouts/Nimble
|
||||
url = https://github.com/Quick/Nimble.git
|
||||
[submodule "Carthage.checkout/ReactiveCocoa"]
|
||||
path = Carthage/Checkouts/ReactiveCocoa
|
||||
url = https://github.com/ReactiveCocoa/ReactiveCocoa.git
|
||||
[submodule "Carthage.checkout/Quick"]
|
||||
path = Carthage/Checkouts/Quick
|
||||
url = https://github.com/Quick/Quick.git
|
||||
[submodule "Carthage.checkout/xcconfigs"]
|
||||
path = Carthage/Checkouts/xcconfigs
|
||||
url = https://github.com/jspahrsummers/xcconfigs.git
|
||||
[submodule "Carthage.checkout/Mantle"]
|
||||
path = Carthage/Checkouts/Mantle
|
||||
url = https://github.com/Mantle/Mantle.git
|
||||
[submodule "Carthage/Checkouts/Nimble"]
|
||||
url = https://github.com/Quick/Nimble.git
|
||||
[submodule "Carthage/Checkouts/Quick"]
|
||||
url = https://github.com/Quick/Quick.git
|
||||
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
osx_image: xcode8.3
|
||||
language: objective-c
|
||||
|
||||
install: script/bootstrap
|
||||
script: script/cibuild
|
||||
notifications:
|
||||
email: false
|
||||
env:
|
||||
global:
|
||||
secure: L4C3hHzXc/sgL35dIz3kjqIzPWnXCHsFOgbOcz0f249zlnegeKHQdChm4HUDtfrbmKLMYQCIvVfcgPeLaHkCSeHqXUihXLT2LglK+0GX3MBbFzde9x1uln2O68hH1tTmBg2O2i4Dtc4D3e+2tVv3XmhQDZt0znIVO6n9YgevDqw=
|
||||
@@ -1,2 +0,0 @@
|
||||
github "Mantle/Mantle" ~> 1.5.3
|
||||
github "ReactiveCocoa/ReactiveCocoa" ~> 2.4.3
|
||||
@@ -1,3 +0,0 @@
|
||||
github "jspahrsummers/xcconfigs" ~> 0.8.1
|
||||
github "Quick/Quick" ~> 1.1.0
|
||||
github "Quick/Nimble" ~> 6.1.0
|
||||
@@ -1,5 +0,0 @@
|
||||
github "Mantle/Mantle" "1.5.8"
|
||||
github "Quick/Nimble" "v6.1.0"
|
||||
github "Quick/Quick" "v1.1.0"
|
||||
github "ReactiveCocoa/ReactiveCocoa" "v2.5"
|
||||
github "jspahrsummers/xcconfigs" "0.8.1"
|
||||
Vendored
-1
Submodule Carthage/Checkouts/Mantle deleted from 78d3966b3c
Vendored
-1
Submodule Carthage/Checkouts/Nimble deleted from e3c1a78af3
Vendored
-1
Submodule Carthage/Checkouts/Quick deleted from e4fa1e85c0
Vendored
-1
Submodule Carthage/Checkouts/ReactiveCocoa deleted from 32364b9040
Vendored
-1
Submodule Carthage/Checkouts/xcconfigs deleted from 99624a6af3
+1
Submodule External/Mantle added at fe3a65987b
+1
Submodule External/ReactiveCocoa added at 16c181bbe8
@@ -6,7 +6,6 @@ and transparent as updates to a website**.
|
||||
Instead of publishing a feed of versions from which your app must select,
|
||||
Squirrel updates to the version your server tells it to. This allows you to
|
||||
intelligently update your clients based on the request you give to Squirrel.
|
||||
The server can remotely drive behaviors like rolling back or phased rollouts.
|
||||
|
||||
Your request can include authentication details, custom headers or a request
|
||||
body so that your server has the context it needs in order to supply the most
|
||||
@@ -40,7 +39,7 @@ If you’re developing Squirrel on its own, then use `Squirrel.xcworkspace`.
|
||||
# Dependencies
|
||||
|
||||
Squirrel depends on [ReactiveCocoa](http://github.com/ReactiveCocoa/ReactiveCocoa)
|
||||
and [Mantle](https://github.com/Mantle/Mantle).
|
||||
and [Mantle](https://github.com/MantleFramework/Mantle).
|
||||
|
||||
If your application is already using ReactiveCocoa, ensure it is using the same
|
||||
version as Squirrel.
|
||||
@@ -114,18 +113,12 @@ To know when an update is ready to be installed, you can subscribe to the
|
||||
}];
|
||||
```
|
||||
|
||||
## Installing Updates
|
||||
If you've been notified of an available update, and don't want to wait for it to
|
||||
be installed automatically, you can terminate the app to begin the installation
|
||||
process immediately.
|
||||
|
||||
While downloaded updates are automatically installed when your application
|
||||
terminates, if don't want to wait you can manually terminate the app to begin
|
||||
the installation process immediately.
|
||||
|
||||
Once an [update available notification](#update-available-notifications) has
|
||||
been received, you may want to present an interface informing the user about
|
||||
the update and offering the ability to install and relaunch.
|
||||
|
||||
To explicitly install a downloaded update and automatically relaunch afterward,
|
||||
subscribe to the `relaunchToInstallUpdate` signal on `SQRLUpdater`:
|
||||
If you want to install a downloaded update and automatically relaunch afterward,
|
||||
`SQRLUpdater` can do that:
|
||||
|
||||
```objc
|
||||
[[self.updater relaunchToInstallUpdate] subscribeError:^(NSError *error) {
|
||||
@@ -159,7 +152,7 @@ to the update request provided:
|
||||
"url": "http://mycompany.com/myapp/releases/myrelease",
|
||||
"name": "My Release Name",
|
||||
"notes": "Theses are some release notes innit",
|
||||
"pub_date": "2013-09-18T12:29:53+01:00"
|
||||
"pub_date": "2013-09-18T12:29:53+01:00",
|
||||
}
|
||||
```
|
||||
|
||||
@@ -176,4 +169,4 @@ appropriate format.
|
||||
|
||||
Squirrel does not provide any GUI components for presenting updates. If you want
|
||||
to indicate updates to the user, make sure to [listen for downloaded
|
||||
updates](#update-available-notifications).
|
||||
updates](#update-notifications).
|
||||
|
||||
+184
-462
File diff suppressed because it is too large
Load Diff
+17
-19
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0510"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -15,50 +15,48 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D014AC0017B97885007D79D0"
|
||||
BuildableName = "ShipIt"
|
||||
BlueprintName = "ShipIt"
|
||||
BuildableName = "shipit-installer"
|
||||
BlueprintName = "ShipIt Installer"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Test"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Test">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BEE179CC00E00158214"
|
||||
BuildableName = "SquirrelTests.xctest"
|
||||
BlueprintName = "SquirrelTests"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D014AC0017B97885007D79D0"
|
||||
BuildableName = "ShipIt"
|
||||
BlueprintName = "ShipIt"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "2.0">
|
||||
LastUpgradeVersion = "0510"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
@@ -22,10 +22,10 @@
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BEE179CC00E00158214"
|
||||
@@ -37,10 +37,10 @@
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "NO">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Test">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
@@ -53,45 +53,16 @@
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BD6179CC00E00158214"
|
||||
BuildableName = "Squirrel.framework"
|
||||
BlueprintName = "Squirrel"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "FORCE_APP_IDENTIFIER"
|
||||
value = "com.github.Squirrel.SquirrelTests"
|
||||
isEnabled = "YES">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugXPCServices = "NO"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BD6179CC00E00158214"
|
||||
BuildableName = "Squirrel.framework"
|
||||
BlueprintName = "Squirrel"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQRLUpdateFromURL"
|
||||
@@ -103,20 +74,11 @@
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Profile"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Profile"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0C22BD6179CC00E00158214"
|
||||
BuildableName = "Squirrel.framework"
|
||||
BlueprintName = "Squirrel"
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0510"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -23,10 +23,10 @@
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Test"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Test">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
@@ -38,21 +38,17 @@
|
||||
ReferencedContainer = "container:Squirrel.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableProductRunnable>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D08D4E0B17B451500012B22D"
|
||||
@@ -65,13 +61,12 @@
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableProductRunnable>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D08D4E0B17B451500012B22D"
|
||||
|
||||
+8
-8
@@ -5,18 +5,18 @@
|
||||
location = "group:Squirrel.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Mantle/Mantle.xcodeproj">
|
||||
location = "group:External/Mantle/Mantle.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa.xcodeproj">
|
||||
location = "group:External/ReactiveCocoa/ReactiveCocoaFramework/ReactiveCocoa.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:External/ReactiveCocoa/external/specta/Specta.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:External/ReactiveCocoa/external/expecta/Expecta.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:External/OHHTTPStubs/OHHTTPStubs/OHHTTPStubs.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Quick/Quick.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Nimble/Nimble.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
|
||||
@@ -14,7 +14,4 @@
|
||||
// Info.plist, or nil if the key is not present.
|
||||
@property (nonatomic, copy, readonly) NSString *sqrl_bundleVersion;
|
||||
|
||||
/// The value of the `kCFBundleExecutableKey` key.
|
||||
@property (nonatomic, copy, readonly) NSString *sqrl_executableName;
|
||||
|
||||
@end
|
||||
|
||||
@@ -14,8 +14,4 @@
|
||||
return [self objectForInfoDictionaryKey:(id)kCFBundleVersionKey];
|
||||
}
|
||||
|
||||
- (NSString *)sqrl_executableName {
|
||||
return [self objectForInfoDictionaryKey:(id)kCFBundleExecutableKey];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <ReactiveCocoa/RACSignal.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
@interface RACSignal (SQRLTransactionExtensions)
|
||||
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
//
|
||||
|
||||
#import "RACSignal+SQRLTransactionExtensions.h"
|
||||
|
||||
#import <ReactiveCocoa/RACDisposable.h>
|
||||
#import <IOKit/pwr_mgt/IOPMLib.h>
|
||||
|
||||
// How long before power assertions time out.
|
||||
|
||||
@@ -7,11 +7,8 @@
|
||||
//
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
#import "EXTScope.h"
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACSubscriber.h>
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Security/Security.h>
|
||||
|
||||
NSString * const SQRLCodeSignatureErrorDomain = @"SQRLCodeSignatureErrorDomain";
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
@@ -29,24 +29,14 @@
|
||||
// on-disk locations for. This must not be nil.
|
||||
- (instancetype)initWithApplicationIdentifier:(NSString *)appIdentifier;
|
||||
|
||||
// Finds or creates a storage folder.
|
||||
// Finds or creates an Application Support folder.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)storageURL;
|
||||
- (RACSignal *)applicationSupportURL;
|
||||
|
||||
// Determines where archived `SQRLShipItState` should be saved.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)shipItStateURL;
|
||||
|
||||
// Determines where ShipIt's stdout log should be saved.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)shipItStdoutURL;
|
||||
|
||||
// Determines where ShipIt's stderr log should be saved.
|
||||
//
|
||||
// Returns a signal which synchronously sends a URL then completes, or errors.
|
||||
- (RACSignal *)shipItStderrURL;
|
||||
|
||||
@end
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
//
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
@implementation SQRLDirectoryManager
|
||||
|
||||
@@ -24,7 +23,7 @@
|
||||
// Should only fallback to when running under otest, where
|
||||
// NSBundle.mainBundle doesn't return useful data.
|
||||
if (identifier == nil) {
|
||||
identifier = NSProcessInfo.processInfo.environment[@"FORCE_APP_IDENTIFIER"];
|
||||
identifier = NSProcessInfo.processInfo.processName;
|
||||
}
|
||||
|
||||
NSAssert(identifier != nil, @"Could not automatically determine the current application's identifier");
|
||||
@@ -47,11 +46,11 @@
|
||||
|
||||
#pragma mark Folder URLs
|
||||
|
||||
- (RACSignal *)storageURL {
|
||||
- (RACSignal *)applicationSupportURL {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSError *error = nil;
|
||||
NSURL *folderURL = [NSFileManager.defaultManager URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
|
||||
NSURL *folderURL = [NSFileManager.defaultManager URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
|
||||
if (folderURL == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
@@ -63,36 +62,18 @@
|
||||
|
||||
return [RACSignal return:folderURL];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -storageURL", self];
|
||||
setNameWithFormat:@"%@ -applicationSupportURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStateURL {
|
||||
return [[[self
|
||||
storageURL]
|
||||
applicationSupportURL]
|
||||
map:^(NSURL *folderURL) {
|
||||
return [folderURL URLByAppendingPathComponent:@"ShipItState.plist"];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStateURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStdoutURL {
|
||||
return [[[self
|
||||
storageURL]
|
||||
map:^(NSURL *folderURL) {
|
||||
return [folderURL URLByAppendingPathComponent:@"ShipIt_stdout.log"];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStdoutURL", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStderrURL {
|
||||
return [[[self
|
||||
storageURL]
|
||||
map:^(NSURL *folderURL) {
|
||||
return [folderURL URLByAppendingPathComponent:@"ShipIt_stderr.log"];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStderrURL", self];
|
||||
}
|
||||
|
||||
#pragma mark NSObject
|
||||
|
||||
- (NSString *)description {
|
||||
|
||||
@@ -40,9 +40,9 @@
|
||||
#pragma mark MTLJSONSerializing
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return @{
|
||||
return [super.JSONKeyPathsByPropertyKey mtl_dictionaryByAddingEntriesFromDictionary:@{
|
||||
@keypath(SQRLDownloadedUpdate.new, bundleURL): NSNull.null
|
||||
};
|
||||
}];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
+25
-106
@@ -7,23 +7,16 @@
|
||||
//
|
||||
|
||||
#import "SQRLInstaller.h"
|
||||
|
||||
#import <libkern/OSAtomic.h>
|
||||
#import "EXTScope.h"
|
||||
#import <ReactiveCocoa/NSEnumerator+RACSequenceAdditions.h>
|
||||
#import <ReactiveCocoa/NSObject+RACPropertySubscribing.h>
|
||||
#import <ReactiveCocoa/RACCommand.h>
|
||||
#import <ReactiveCocoa/RACSequence.h>
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACSubscriber.h>
|
||||
#import <sys/xattr.h>
|
||||
|
||||
#import "NSBundle+SQRLVersionExtensions.h"
|
||||
#import "NSError+SQRLVerbosityExtensions.h"
|
||||
#import "RACSignal+SQRLTransactionExtensions.h"
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import "SQRLTerminationListener.h"
|
||||
#import <libkern/OSAtomic.h>
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <sys/xattr.h>
|
||||
#import "SQRLInstallerOwnedBundle.h"
|
||||
|
||||
NSString * const SQRLInstallerErrorDomain = @"SQRLInstallerErrorDomain";
|
||||
@@ -171,7 +164,7 @@ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
|
||||
return [self abortInstall];
|
||||
}];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@@ -261,49 +254,27 @@ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
setNameWithFormat:@"%@ -acquireTargetBundleURLForRequest: %@", self, request];
|
||||
}
|
||||
|
||||
- (RACSignal *)renameIfNeeded:(SQRLShipItRequest *)request updateBundleURL:(NSURL *)updateBundleURL {
|
||||
if (!request.useUpdateBundleName) return [RACSignal return:request];
|
||||
|
||||
return [[self
|
||||
renamedTargetIfNeededWithTargetURL:request.targetBundleURL sourceURL:updateBundleURL]
|
||||
flattenMap:^(NSURL *newTargetURL) {
|
||||
if ([newTargetURL isEqual:request.targetBundleURL]) return [RACSignal return:request];
|
||||
|
||||
SQRLShipItRequest *updatedRequest = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:request.updateBundleURL targetBundleURL:newTargetURL bundleIdentifier:request.bundleIdentifier launchAfterInstallation:request.launchAfterInstallation useUpdateBundleName:request.useUpdateBundleName];
|
||||
return [[self
|
||||
installItemToURL:newTargetURL fromURL:request.targetBundleURL]
|
||||
concat:[RACSignal return:updatedRequest]];
|
||||
}];
|
||||
}
|
||||
|
||||
- (RACSignal *)installRequest:(SQRLShipItRequest *)request {
|
||||
NSParameterAssert(request != nil);
|
||||
|
||||
return [[[[self
|
||||
prepareAndValidateUpdateBundleURLForRequest:request]
|
||||
flattenMap:^(NSURL *updateBundleURL) {
|
||||
return [[[[self
|
||||
renameIfNeeded:request updateBundleURL:updateBundleURL]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [[self acquireTargetBundleURLForRequest:request] concat:[RACSignal return:request]];
|
||||
}]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [[[[[[self
|
||||
installItemToURL:request.targetBundleURL fromURL:updateBundleURL]
|
||||
concat:[RACSignal return:request.updateBundleURL]]
|
||||
concat:[RACSignal return:updateBundleURL]]
|
||||
concat:[RACSignal defer:^{
|
||||
return [RACSignal return:self.ownedBundle.temporaryURL];
|
||||
}]]
|
||||
flattenMap:^(NSURL *location) {
|
||||
return [[[self
|
||||
deleteOwnedBundleAtURL:location]
|
||||
doError:^(NSError *error) {
|
||||
NSLog(@"Couldn't remove owned bundle at location %@, error %@", location, error.sqrl_verboseDescription);
|
||||
}]
|
||||
catchTo:[RACSignal empty]];
|
||||
return [[[[[[[self
|
||||
acquireTargetBundleURLForRequest:request]
|
||||
concat:[self installItemToURL:request.targetBundleURL fromURL:updateBundleURL]]
|
||||
concat:[RACSignal return:request.updateBundleURL]]
|
||||
concat:[RACSignal return:updateBundleURL]]
|
||||
concat:[RACSignal defer:^{
|
||||
return [RACSignal return:self.ownedBundle.temporaryURL];
|
||||
}]]
|
||||
flattenMap:^(NSURL *location) {
|
||||
return [[[self
|
||||
deleteOwnedBundleAtURL:location]
|
||||
doError:^(NSError *error) {
|
||||
NSLog(@"Couldn't remove owned bundle at location %@, error %@", location, error.sqrl_verboseDescription);
|
||||
}]
|
||||
concat:[RACSignal return:request]];
|
||||
catchTo:[RACSignal empty]];
|
||||
}]
|
||||
doCompleted:^{
|
||||
self.ownedBundle = nil;
|
||||
@@ -401,20 +372,7 @@ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
if (rmdir(temporaryDirectoryURL.path.fileSystemRepresentation) == 0) {
|
||||
return [RACSignal empty];
|
||||
} else {
|
||||
int code = errno;
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
|
||||
const char *desc = strerror(code);
|
||||
if (desc != NULL) {
|
||||
userInfo[NSLocalizedDescriptionKey] = @(desc);
|
||||
} else {
|
||||
userInfo[NSLocalizedDescriptionKey] = NSLocalizedString(@"Unknown POSIX error", @"");
|
||||
}
|
||||
|
||||
userInfo[NSLocalizedFailureReasonErrorKey] = [NSString stringWithFormat:NSLocalizedString(@"Couldn't remove temp dir \"%@\"", @""), temporaryDirectoryURL.path];
|
||||
userInfo[NSURLErrorKey] = temporaryDirectoryURL;
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo]];
|
||||
return [RACSignal error:[NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil]];
|
||||
}
|
||||
}]
|
||||
setNameWithFormat:@"%@ -deleteOwnedBundleAtURL: %@", self, bundleURL];
|
||||
@@ -447,36 +405,6 @@ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
|
||||
#pragma mark Installation
|
||||
|
||||
/// Check if the target should be renamed and provide the renamed URL.
|
||||
///
|
||||
/// targetURL - The URL for the target. Cannot be nil.
|
||||
/// sourceURL - The URL for the source. Cannot be nil.
|
||||
///
|
||||
/// Returns a signal which will send the URL for the renamed target. If a rename
|
||||
/// isn't needed then it will send `targetURL`.
|
||||
- (RACSignal *)renamedTargetIfNeededWithTargetURL:(NSURL *)targetURL sourceURL:(NSURL *)sourceURL {
|
||||
return [RACSignal defer:^{
|
||||
NSBundle *sourceBundle = [NSBundle bundleWithURL:sourceURL];
|
||||
NSString *targetExecutableName = targetURL.lastPathComponent.stringByDeletingPathExtension;
|
||||
NSString *sourceExecutableName = sourceBundle.sqrl_executableName;
|
||||
|
||||
// If they're already the same then we're good.
|
||||
if ([targetExecutableName isEqual:sourceExecutableName]) {
|
||||
return [RACSignal return:targetURL];
|
||||
}
|
||||
|
||||
NSString *newAppName = [sourceExecutableName stringByAppendingPathExtension:@"app"];
|
||||
NSURL *newTargetURL = [targetURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:newAppName];
|
||||
|
||||
// If there's already something there then don't rename to it.
|
||||
if ([NSFileManager.defaultManager fileExistsAtPath:newTargetURL.path]) {
|
||||
return [RACSignal return:targetURL];
|
||||
}
|
||||
|
||||
return [RACSignal return:newTargetURL];
|
||||
}];
|
||||
}
|
||||
|
||||
- (RACSignal *)installItemToURL:(NSURL *)targetURL fromURL:(NSURL *)sourceURL {
|
||||
NSParameterAssert(targetURL != nil);
|
||||
NSParameterAssert(sourceURL != nil);
|
||||
@@ -489,7 +417,7 @@ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
} else {
|
||||
int code = errno;
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
|
||||
|
||||
const char *desc = strerror(code);
|
||||
if (desc != NULL) userInfo[NSLocalizedDescriptionKey] = @(desc);
|
||||
|
||||
@@ -541,16 +469,9 @@ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
// file to begin with.
|
||||
if (code != ENOATTR) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
|
||||
|
||||
const char *desc = strerror(code);
|
||||
if (desc != NULL) {
|
||||
userInfo[NSLocalizedDescriptionKey] = @(desc);
|
||||
} else {
|
||||
userInfo[NSLocalizedDescriptionKey] = NSLocalizedString(@"Unknown POSIX error", @"");
|
||||
}
|
||||
|
||||
userInfo[NSLocalizedFailureReasonErrorKey] = [NSString stringWithFormat:NSLocalizedString(@"Couldn't remove quarantine attribute from \"%@\". This most likely means the file is read-only.", @""), URL.path];
|
||||
userInfo[NSURLErrorKey] = URL;
|
||||
if (desc != NULL) userInfo[NSLocalizedDescriptionKey] = @(desc);
|
||||
|
||||
return [RACSignal error:[NSError errorWithDomain:NSPOSIXErrorDomain code:code userInfo:userInfo]];
|
||||
}
|
||||
@@ -604,9 +525,7 @@ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
|
||||
return NO;
|
||||
}];
|
||||
|
||||
return [[enumerator.rac_sequence.signal
|
||||
startWith:directoryURL]
|
||||
subscribe:subscriber];
|
||||
return [enumerator.rac_sequence.signal subscribe:subscriber];
|
||||
}]
|
||||
flattenMap:^(NSURL *itemURL) {
|
||||
return [[[self
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
#import "SQRLInstallerOwnedBundle.h"
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
#import <ReactiveCocoa/EXTKeyPathCoding.h>
|
||||
|
||||
@implementation SQRLInstallerOwnedBundle
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// SQRLShipItConnection.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-12.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSignal;
|
||||
@class SQRLShipItRequest;
|
||||
|
||||
// The domain for errors originating within SQRLShipItConnection.
|
||||
extern NSString * const SQRLShipItConnectionErrorDomain;
|
||||
|
||||
// The ShipIt service could not be started.
|
||||
extern const NSInteger SQRLShipItConnectionErrorCouldNotStartService;
|
||||
|
||||
// Installing an update requires the coordination of multiple processes,
|
||||
// `SQRLShipItConnection` is responsible for submitting the launchd jobs
|
||||
// required to perform an installation request.
|
||||
//
|
||||
// The multiprocess approach to waiting for termination and installing is
|
||||
// designed to keep uses of AppKit API (i.e. `NSRunningApplication`) out of the
|
||||
// installer process - which may be running in the root bootstrap context - and
|
||||
// put them in a process running in the user bootstrap context. These processes
|
||||
// can then communicate using the file system as a message bus.
|
||||
//
|
||||
// Frustratingly although LaunchServices is daemon and root safe since 10.5, the
|
||||
// LaunchServices API for querying the running applications isn't public
|
||||
// (internally `NSRunningApplication` uses this LaunchServices private API,
|
||||
// though of course this is subject to change and `NSRunningApplication` could
|
||||
// also do other non-root safe things).
|
||||
//
|
||||
// When a user application running Squirrel wants to install an update, Squirrel
|
||||
// submits two launchd jobs, one which will wait for application termination and
|
||||
// write an empty file to the given location when the criteria are met, and the
|
||||
// other which will wait for that file to appear and then perform the install as
|
||||
// before. The "wait for termination" job is always submitted to the user
|
||||
// domain, but the installer job is submitted to a domain based on whether the
|
||||
// install location is writable by the current user.
|
||||
//
|
||||
// To perform the relaunch when the install is complete, it is safe to use the
|
||||
// LaunchServices API from the installer process, the app will be launched in
|
||||
// the user's GUI session.
|
||||
//
|
||||
// From <https://developer.apple.com/library/mac/technotes/tn2083/>
|
||||
//
|
||||
// > If the EUID of the calling process is zero, the application is launched in
|
||||
// > the context of the currently active GUI login session. If there is no
|
||||
// > currently active GUI login session (no one is logged in, or a logged in
|
||||
// > user has fast user switched to the login window), the behavior is
|
||||
// > unspecified (r. 5321293).
|
||||
@interface SQRLShipItConnection : NSObject
|
||||
|
||||
// Returns the label for the ShipIt launchd job.
|
||||
+ (NSString *)shipItInstallerJobLabel;
|
||||
|
||||
// Designated initialiser.
|
||||
//
|
||||
// privileged - Determines which launchd domain to launch the job in.
|
||||
// If YES, ShipIt is launched in the root domain, otherwise it is
|
||||
// launched in the current user’s domain.
|
||||
//
|
||||
// Returns an initialised connection which can be used to start an install.
|
||||
- (instancetype)initWithRootPrivileges:(BOOL)rootPrivileges;
|
||||
|
||||
// Submits the request to the process network which will wait for termination
|
||||
// and then install.
|
||||
//
|
||||
// After sending the request, the update will be attempted when the sending
|
||||
// process terminates.
|
||||
//
|
||||
// request - The install parameters, target bundle, update bundle, whether to
|
||||
// launch when install is complete etc. Must not be nil.
|
||||
//
|
||||
// Returns a signal which will complete, or error, on a background scheduler.
|
||||
- (RACSignal *)sendRequest:(SQRLShipItRequest *)request;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,203 @@
|
||||
//
|
||||
// SQRLShipItConnection.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-12.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLShipItConnection.h"
|
||||
#import "EXTScope.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Security/Security.h>
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
#import <launch.h>
|
||||
#import "SQRLAuthorization.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
NSString * const SQRLShipItConnectionErrorDomain = @"SQRLShipItConnectionErrorDomain";
|
||||
|
||||
const NSInteger SQRLShipItConnectionErrorCouldNotStartService = 1;
|
||||
|
||||
@interface SQRLShipItConnection ()
|
||||
@property (readonly, nonatomic, assign) BOOL privileged;
|
||||
@end
|
||||
|
||||
@implementation SQRLShipItConnection
|
||||
|
||||
+ (NSString *)shipItInstallerJobLabel {
|
||||
NSString *currentAppIdentifier = NSBundle.mainBundle.bundleIdentifier ?: [NSString stringWithFormat:@"%@:%d", NSProcessInfo.processInfo.processName, NSProcessInfo.processInfo.processIdentifier];
|
||||
return [currentAppIdentifier stringByAppendingString:@".ShipIt"];
|
||||
}
|
||||
|
||||
+ (NSMutableDictionary *)jobDictionaryWithLabel:(NSString *)jobLabel executableName:(NSString *)executableName arguments:(NSArray *)arguments {
|
||||
NSParameterAssert(jobLabel != nil);
|
||||
NSParameterAssert(executableName != nil);
|
||||
NSParameterAssert(arguments != nil);
|
||||
|
||||
NSMutableDictionary *jobDict = [NSMutableDictionary dictionary];
|
||||
jobDict[@(LAUNCH_JOBKEY_LABEL)] = jobLabel;
|
||||
jobDict[@(LAUNCH_JOBKEY_NICE)] = @(-1);
|
||||
jobDict[@(LAUNCH_JOBKEY_ENABLETRANSACTIONS)] = @NO;
|
||||
jobDict[@(LAUNCH_JOBKEY_THROTTLEINTERVAL)] = @2;
|
||||
|
||||
NSBundle *squirrelBundle = [NSBundle bundleForClass:self.class];
|
||||
NSAssert(squirrelBundle != nil, @"Could not open Squirrel.framework bundle");
|
||||
|
||||
NSMutableArray *fullArguments = [NSMutableArray arrayWithObject:[squirrelBundle pathForResource:executableName ofType:nil]];
|
||||
[fullArguments addObjectsFromArray:arguments];
|
||||
jobDict[@(LAUNCH_JOBKEY_PROGRAMARGUMENTS)] = fullArguments;
|
||||
|
||||
return jobDict;
|
||||
}
|
||||
|
||||
+ (RACSignal *)shipItInstallerJobDictionary {
|
||||
NSString *jobLabel = self.shipItInstallerJobLabel;
|
||||
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:jobLabel];
|
||||
return [directoryManager applicationSupportURL];
|
||||
}]
|
||||
map:^(NSURL *appSupportURL) {
|
||||
NSMutableArray *arguments = [[NSMutableArray alloc] init];
|
||||
|
||||
// Pass in the service name so ShipIt knows how to broadcast itself.
|
||||
[arguments addObject:jobLabel];
|
||||
|
||||
NSMutableDictionary *jobDict = [self jobDictionaryWithLabel:jobLabel executableName:@"shipit-installer" arguments:arguments];
|
||||
jobDict[@(LAUNCH_JOBKEY_KEEPALIVE)] = @{
|
||||
@(LAUNCH_JOBKEY_KEEPALIVE_SUCCESSFULEXIT): @NO
|
||||
};
|
||||
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDOUTPATH)] = [appSupportURL URLByAppendingPathComponent:@"ShipIt_stdout.log"].path;
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDERRORPATH)] = [appSupportURL URLByAppendingPathComponent:@"ShipIt_stderr.log"].path;
|
||||
|
||||
return jobDict;
|
||||
}]
|
||||
setNameWithFormat:@"+shipItInstallerJobDictionary"];
|
||||
}
|
||||
|
||||
+ (RACSignal *)shipItAuthorization {
|
||||
return [[RACSignal
|
||||
createSignal:^ RACDisposable * (id<RACSubscriber> subscriber) {
|
||||
AuthorizationItem rightItems[] = {
|
||||
{
|
||||
.name = kSMRightModifySystemDaemons,
|
||||
},
|
||||
};
|
||||
|
||||
AuthorizationRights rights = {
|
||||
.count = sizeof(rightItems) / sizeof(*rightItems),
|
||||
.items = rightItems,
|
||||
};
|
||||
|
||||
NSString *prompt = NSLocalizedString(@"An update is ready to install.", @"SQRLShipItConnection, launch shipit, authorization prompt");
|
||||
|
||||
NSString *iconName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleIconFile"];
|
||||
NSString *iconPath = (iconName == nil ? nil : [NSBundle.mainBundle pathForImageResource:iconName]);
|
||||
|
||||
AuthorizationItem environmentItems[] = {
|
||||
{
|
||||
.name = kAuthorizationEnvironmentPrompt,
|
||||
.valueLength = strlen(prompt.UTF8String),
|
||||
.value = (void *)prompt.UTF8String,
|
||||
},
|
||||
{
|
||||
.name = kAuthorizationEnvironmentIcon,
|
||||
.valueLength = (iconPath == nil ? 0 : strlen(iconPath.UTF8String)),
|
||||
.value = (void *)iconPath.UTF8String,
|
||||
},
|
||||
};
|
||||
|
||||
AuthorizationEnvironment environment = {
|
||||
.count = sizeof(environmentItems) / sizeof(*environmentItems),
|
||||
.items = environmentItems,
|
||||
};
|
||||
|
||||
AuthorizationRef authorization = NULL;
|
||||
OSStatus authorizationError = AuthorizationCreate(&rights, &environment, kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights, &authorization);
|
||||
|
||||
if (authorizationError == noErr) {
|
||||
[subscriber sendNext:[[SQRLAuthorization alloc] initWithAuthorization:authorization]];
|
||||
[subscriber sendCompleted];
|
||||
} else {
|
||||
[subscriber sendError:[NSError errorWithDomain:NSOSStatusErrorDomain code:authorizationError userInfo:nil]];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}]
|
||||
setNameWithFormat:@"+shipItAuthorization"];
|
||||
}
|
||||
|
||||
- (instancetype)initWithRootPrivileges:(BOOL)rootPrivileges {
|
||||
self = [self init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
_privileged = rootPrivileges;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (RACSignal *)sendRequest:(SQRLShipItRequest *)request {
|
||||
NSParameterAssert(request != nil);
|
||||
|
||||
return [[[self
|
||||
submitInstallerJobForRequestIfNeeded:request]
|
||||
concat:[RACSignal defer:^{
|
||||
|
||||
}]]
|
||||
setNameWithFormat:@"%@ -sendRequest: %@", self, request];
|
||||
}
|
||||
|
||||
- (RACSignal *)submitInstallerJobForRequestIfNeeded:(SQRLShipItRequest *)request {
|
||||
// TODO implement lazy submission when the job is already loaded in launchd
|
||||
|
||||
CFStringRef domain = NULL; RACSignal *authorization;
|
||||
if (self.privileged) {
|
||||
domain = kSMDomainSystemLaunchd;
|
||||
authorization = self.class.shipItAuthorization;
|
||||
} else {
|
||||
domain = kSMDomainUserLaunchd;
|
||||
authorization = [RACSignal return:nil];
|
||||
}
|
||||
|
||||
return [[[RACSignal
|
||||
zip:@[
|
||||
self.class.shipItInstallerJobDictionary,
|
||||
authorization,
|
||||
] reduce:^(NSDictionary *job, SQRLAuthorization *authorization) {
|
||||
return [self submitJob:job domain:(__bridge id)domain authorization:authorization];
|
||||
}]
|
||||
flatten]
|
||||
setNameWithFormat:@"%@ -submitInstallerJobForRequestIfNeeded: %@", self, request];
|
||||
}
|
||||
|
||||
- (RACSignal *)submitJob:(NSDictionary *)job domain:(NSString *)domain authorization:(SQRLAuthorization *)authorizationValue {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
NSString *jobLabel = job[@(LAUNCH_JOBKEY_LABEL)];
|
||||
|
||||
AuthorizationRef authorization = authorizationValue.authorization;
|
||||
|
||||
CFErrorRef cfError;
|
||||
if (!SMJobRemove((__bridge CFStringRef)domain, (__bridge CFStringRef)jobLabel, authorization, true, &cfError)) {
|
||||
NSError *error = CFBridgingRelease(cfError);
|
||||
cfError = NULL;
|
||||
|
||||
if (![error.domain isEqual:(__bridge id)kSMErrorDomainLaunchd] || error.code != kSMErrorJobNotFound) {
|
||||
NSLog(@"Could not remove previous ShipIt job %@: %@", jobLabel, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!SMJobSubmit((__bridge CFStringRef)domain, (__bridge CFDictionaryRef)job, authorization, &cfError)) {
|
||||
return [RACSignal error:CFBridgingRelease(cfError)];
|
||||
}
|
||||
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -submitJob: %@ domain: %@ authorization: %@", self, job, domain, authorizationValue];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,34 +0,0 @@
|
||||
//
|
||||
// SQRLShipItLauncher.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-12.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
// The domain for errors originating within SQRLShipItLauncher.
|
||||
extern NSString * const SQRLShipItLauncherErrorDomain;
|
||||
|
||||
// The ShipIt service could not be started.
|
||||
extern const NSInteger SQRLShipItLauncherErrorCouldNotStartService;
|
||||
|
||||
// Responsible for launching the ShipIt service to actually install an update.
|
||||
@interface SQRLShipItLauncher : NSObject
|
||||
|
||||
// Returns the label for the ShipIt launchd job.
|
||||
+ (NSString *)shipItJobLabel;
|
||||
|
||||
// Attempts to launch ShipIt.
|
||||
//
|
||||
// privileged - Determines which launchd domain to launch the job in.
|
||||
// If YES, ShipIt is launched in the root domain, otherwise it is
|
||||
// launched in the current user’s domain.
|
||||
//
|
||||
// Returns a signal which will complete, or error, on a background scheduler.
|
||||
+ (RACSignal *)launchPrivileged:(BOOL)privileged;
|
||||
|
||||
@end
|
||||
@@ -1,160 +0,0 @@
|
||||
//
|
||||
// SQRLShipItLauncher.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-12.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLShipItLauncher.h"
|
||||
#import "EXTScope.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Security/Security.h>
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
#import <launch.h>
|
||||
#import "SQRLAuthorization.h"
|
||||
|
||||
NSString * const SQRLShipItLauncherErrorDomain = @"SQRLShipItLauncherErrorDomain";
|
||||
|
||||
const NSInteger SQRLShipItLauncherErrorCouldNotStartService = 1;
|
||||
|
||||
@implementation SQRLShipItLauncher
|
||||
|
||||
+ (NSString *)shipItJobLabel {
|
||||
return [SQRLDirectoryManager.currentApplicationManager.applicationIdentifier stringByAppendingString:@".ShipIt"];
|
||||
}
|
||||
|
||||
+ (RACSignal *)shipItJobDictionary {
|
||||
NSString *jobLabel = self.shipItJobLabel;
|
||||
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:jobLabel];
|
||||
return [RACSignal zip:@[
|
||||
[directoryManager shipItStdoutURL],
|
||||
[directoryManager shipItStderrURL],
|
||||
[directoryManager shipItStateURL]
|
||||
]];
|
||||
}]
|
||||
reduceEach:^(NSURL *stdoutURL, NSURL *stderrURL, NSURL *shipItStateURL) {
|
||||
NSBundle *squirrelBundle = [NSBundle bundleForClass:self.class];
|
||||
NSAssert(squirrelBundle != nil, @"Could not open Squirrel.framework bundle");
|
||||
|
||||
NSMutableDictionary *jobDict = [NSMutableDictionary dictionary];
|
||||
jobDict[@(LAUNCH_JOBKEY_LABEL)] = jobLabel;
|
||||
jobDict[@(LAUNCH_JOBKEY_NICE)] = @(-1);
|
||||
jobDict[@(LAUNCH_JOBKEY_ENABLETRANSACTIONS)] = @NO;
|
||||
jobDict[@(LAUNCH_JOBKEY_THROTTLEINTERVAL)] = @2;
|
||||
jobDict[@(LAUNCH_JOBKEY_KEEPALIVE)] = @{
|
||||
@(LAUNCH_JOBKEY_KEEPALIVE_SUCCESSFULEXIT): @NO
|
||||
};
|
||||
|
||||
jobDict[@(LAUNCH_JOBKEY_MACHSERVICES)] = @{
|
||||
jobLabel: @YES
|
||||
};
|
||||
|
||||
NSMutableArray *arguments = [[NSMutableArray alloc] init];
|
||||
[arguments addObject:[squirrelBundle URLForResource:@"ShipIt" withExtension:nil].path];
|
||||
|
||||
// Pass in the service name so ShipIt knows how to broadcast itself.
|
||||
[arguments addObject:jobLabel];
|
||||
|
||||
// We need to pass the path to ShipIt rather than having ShipIt
|
||||
// calculate the path itself. This is because ShipIt may run as a
|
||||
// different user if it had to escalate to be able to replace the
|
||||
// bundle.
|
||||
[arguments addObject:shipItStateURL.path];
|
||||
|
||||
jobDict[@(LAUNCH_JOBKEY_PROGRAMARGUMENTS)] = arguments;
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDOUTPATH)] = stdoutURL.path;
|
||||
jobDict[@(LAUNCH_JOBKEY_STANDARDERRORPATH)] = stderrURL.path;
|
||||
|
||||
return jobDict;
|
||||
}]
|
||||
setNameWithFormat:@"+shipItJobDictionary"];
|
||||
}
|
||||
|
||||
+ (RACSignal *)shipItAuthorization {
|
||||
return [[RACSignal
|
||||
createSignal:^ RACDisposable * (id<RACSubscriber> subscriber) {
|
||||
AuthorizationItem rightItems[] = {
|
||||
{
|
||||
.name = kSMRightModifySystemDaemons,
|
||||
},
|
||||
};
|
||||
|
||||
AuthorizationRights rights = {
|
||||
.count = sizeof(rightItems) / sizeof(*rightItems),
|
||||
.items = rightItems,
|
||||
};
|
||||
|
||||
NSString *prompt = NSLocalizedString(@"An update is ready to install.", @"SQRLShipItLauncher, launch shipit, authorization prompt");
|
||||
|
||||
NSString *iconName = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleIconFile"];
|
||||
NSString *iconPath = (iconName == nil ? nil : [NSBundle.mainBundle.resourceURL URLByAppendingPathComponent:iconName].path);
|
||||
|
||||
AuthorizationItem environmentItems[] = {
|
||||
{
|
||||
.name = kAuthorizationEnvironmentPrompt,
|
||||
.valueLength = strlen(prompt.UTF8String),
|
||||
.value = (void *)prompt.UTF8String,
|
||||
},
|
||||
{
|
||||
.name = kAuthorizationEnvironmentIcon,
|
||||
.valueLength = iconPath == nil ? 0 : strlen(iconPath.UTF8String),
|
||||
.value = (void *)iconPath.UTF8String,
|
||||
},
|
||||
};
|
||||
|
||||
AuthorizationEnvironment environment = {
|
||||
.count = sizeof(environmentItems) / sizeof(*environmentItems),
|
||||
.items = environmentItems,
|
||||
};
|
||||
|
||||
AuthorizationRef authorization = NULL;
|
||||
OSStatus authorizationError = AuthorizationCreate(&rights, &environment, kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights, &authorization);
|
||||
|
||||
if (authorizationError == noErr) {
|
||||
[subscriber sendNext:[[SQRLAuthorization alloc] initWithAuthorization:authorization]];
|
||||
[subscriber sendCompleted];
|
||||
} else {
|
||||
[subscriber sendError:[NSError errorWithDomain:NSOSStatusErrorDomain code:authorizationError userInfo:nil]];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}]
|
||||
setNameWithFormat:@"+shipItAuthorization"];
|
||||
}
|
||||
|
||||
+ (RACSignal *)launchPrivileged:(BOOL)privileged {
|
||||
return [[[RACSignal
|
||||
zip:@[
|
||||
self.shipItJobDictionary,
|
||||
(privileged ? self.shipItAuthorization : [RACSignal return:nil])
|
||||
] reduce:^(NSDictionary *jobDictionary, SQRLAuthorization *authorizationValue) {
|
||||
CFStringRef domain = (privileged ? kSMDomainSystemLaunchd : kSMDomainUserLaunchd);
|
||||
|
||||
AuthorizationRef authorization = authorizationValue.authorization;
|
||||
|
||||
CFErrorRef cfError;
|
||||
if (!SMJobRemove(domain, (__bridge CFStringRef)self.shipItJobLabel, authorization, true, &cfError)) {
|
||||
NSError *error = CFBridgingRelease(cfError);
|
||||
cfError = NULL;
|
||||
|
||||
if (![error.domain isEqual:(__bridge id)kSMErrorDomainLaunchd] || error.code != kSMErrorJobNotFound) {
|
||||
NSLog(@"Could not remove previous ShipIt job: %@", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!SMJobSubmit(domain, (__bridge CFDictionaryRef)jobDictionary, authorization, &cfError)) {
|
||||
return [RACSignal error:CFBridgingRelease(cfError)];
|
||||
}
|
||||
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
flatten]
|
||||
setNameWithFormat:@"+launchPrivileged: %i", (int)privileged];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -42,24 +42,21 @@ extern NSString * const SQRLShipItRequestPropertyErrorKey;
|
||||
// single update request from the client's perspective.
|
||||
@interface SQRLShipItRequest : MTLModel
|
||||
|
||||
// Reads a `SQRLShipItState` from disk, at the location specified by the given
|
||||
// URL signal.
|
||||
// Reads a `SQRLShipItState` from disk, at the location specified by the URL.
|
||||
//
|
||||
// URLSignal - Determines the file location to read from, the signal should send
|
||||
// an `NSURL` object then complete, or error. This must not be nil.
|
||||
// URL - The file location to read from. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously send a `SQRLShipItRequest` then
|
||||
// complete, or error.
|
||||
+ (RACSignal *)readUsingURL:(RACSignal *)URLSignal;
|
||||
+ (RACSignal *)readFromURL:(NSURL *)URL;
|
||||
|
||||
// Writes the receiver to disk, at the location specified by the given URL
|
||||
// signal.
|
||||
// Reads a `SQRLShipItState` from encoded data.
|
||||
//
|
||||
// URLSignal - Determines the file location to write to. The signal should send
|
||||
// an `NSURL` object then complete, or error. This must not be nil.
|
||||
// data - Serialised request from `serialization`.
|
||||
//
|
||||
// Returns a signal which will synchronously complete or error.
|
||||
- (RACSignal *)writeUsingURL:(RACSignal *)URLSignal;
|
||||
// Returns a signal which decodes the serialisation and sends a
|
||||
// `SQRLShipItRequest` then completes, or errors.
|
||||
+ (RACSignal *)readFromData:(NSData *)data;
|
||||
|
||||
// Designated initialiser.
|
||||
//
|
||||
@@ -73,11 +70,10 @@ extern NSString * const SQRLShipItRequestPropertyErrorKey;
|
||||
// installing. Can be nil.
|
||||
// launchAfterInstallation - Whether the updated application should be launched
|
||||
// after installation.
|
||||
// useUpdateBundleName - Should the target use the update bundle's name?
|
||||
//
|
||||
// Returns a request which can be written to disk for ShipIt to read and
|
||||
// perform.
|
||||
- (instancetype)initWithUpdateBundleURL:(NSURL *)updateBundleURL targetBundleURL:(NSURL *)targetBundleURL bundleIdentifier:(NSString *)bundleIdentifier launchAfterInstallation:(BOOL)launchAfterInstallation useUpdateBundleName:(BOOL)useUpdateBundleName;
|
||||
- (instancetype)initWithUpdateBundleURL:(NSURL *)updateBundleURL targetBundleURL:(NSURL *)targetBundleURL bundleIdentifier:(NSString *)bundleIdentifier launchAfterInstallation:(BOOL)launchAfterInstallation;
|
||||
|
||||
// The URL to the downloaded update's app bundle.
|
||||
@property (nonatomic, copy, readonly) NSURL *updateBundleURL;
|
||||
@@ -94,7 +90,17 @@ extern NSString * const SQRLShipItRequestPropertyErrorKey;
|
||||
// Whether to launch the application after an update is successfully installed.
|
||||
@property (nonatomic, assign, readonly) BOOL launchAfterInstallation;
|
||||
|
||||
// Whether the app should use the update bundle's name.
|
||||
@property (nonatomic, assign, readonly) BOOL useUpdateBundleName;
|
||||
// Writes the receiver's serialization to disk, at the location specified by the
|
||||
// URL.
|
||||
//
|
||||
// URL - The file location to write to. This must not be nil.
|
||||
//
|
||||
// Returns a signal which will synchronously complete or error.
|
||||
- (RACSignal *)writeToURL:(NSURL *)URL;
|
||||
|
||||
// Encode the receiver for saving to disk or sending over IPC.
|
||||
//
|
||||
// Returns a signal which sends a `NSData` then completes, or errors.
|
||||
- (RACSignal *)serialization;
|
||||
|
||||
@end
|
||||
|
||||
@@ -8,8 +8,7 @@
|
||||
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
NSString * const SQRLShipItRequestErrorDomain = @"SQRLShipItRequestErrorDomain";
|
||||
|
||||
@@ -47,13 +46,12 @@ NSString * const SQRLShipItRequestPropertyErrorKey = @"SQRLShipItRequestProperty
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)initWithUpdateBundleURL:(NSURL *)updateBundleURL targetBundleURL:(NSURL *)targetBundleURL bundleIdentifier:(NSString *)bundleIdentifier launchAfterInstallation:(BOOL)launchAfterInstallation useUpdateBundleName:(BOOL)useUpdateBundleName {
|
||||
- (instancetype)initWithUpdateBundleURL:(NSURL *)updateBundleURL targetBundleURL:(NSURL *)targetBundleURL bundleIdentifier:(NSString *)bundleIdentifier launchAfterInstallation:(BOOL)launchAfterInstallation {
|
||||
return [self initWithDictionary:@{
|
||||
@keypath(self.updateBundleURL): updateBundleURL,
|
||||
@keypath(self.targetBundleURL): targetBundleURL,
|
||||
@keypath(self.bundleIdentifier): bundleIdentifier ?: NSNull.null,
|
||||
@keypath(self.launchAfterInstallation): @(launchAfterInstallation),
|
||||
@keypath(self.useUpdateBundleName): @(useUpdateBundleName),
|
||||
} error:NULL];
|
||||
}
|
||||
|
||||
@@ -71,13 +69,13 @@ NSString * const SQRLShipItRequestPropertyErrorKey = @"SQRLShipItRequestProperty
|
||||
return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
|
||||
}
|
||||
|
||||
+ (RACSignal *)readUsingURL:(RACSignal *)URL {
|
||||
+ (RACSignal *)readFromURL:(NSURL *)URL {
|
||||
NSParameterAssert(URL != nil);
|
||||
|
||||
return [[[[URL
|
||||
flattenMap:^(NSURL *stateURL) {
|
||||
return [[[[RACSignal
|
||||
defer:^{
|
||||
NSError *error;
|
||||
NSData *data = [self readFromURL:stateURL error:&error];
|
||||
NSData *data = [self readFromURL:URL error:&error];
|
||||
if (data == nil) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
@@ -132,23 +130,20 @@ NSString * const SQRLShipItRequestPropertyErrorKey = @"SQRLShipItRequestProperty
|
||||
setNameWithFormat:@"+readFromData: <NSData %p>", data];
|
||||
}
|
||||
|
||||
- (RACSignal *)writeUsingURL:(RACSignal *)URL {
|
||||
- (RACSignal *)writeToURL:(NSURL *)URL {
|
||||
NSParameterAssert(URL != nil);
|
||||
|
||||
return [[[[RACSignal
|
||||
zip:@[
|
||||
URL,
|
||||
[self serialization]
|
||||
] reduce:^(NSURL *stateURL, NSData *data) {
|
||||
return [[[[self
|
||||
serialization]
|
||||
flattenMap:^(NSData *data) {
|
||||
NSError *error;
|
||||
BOOL write = [self writeData:data toURL:stateURL error:&error];
|
||||
BOOL write = [self writeData:data toURL:URL error:&error];
|
||||
if (!write) {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
flatten]
|
||||
catch:^(NSError *error) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not write update request", nil),
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
//
|
||||
// SQRLTerminationListener.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-10-04.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
// Waits for the termination of a GUI application.
|
||||
@interface SQRLTerminationListener : NSObject
|
||||
|
||||
// Initializes the receiver to wait for termination of the app at the given
|
||||
// location.
|
||||
//
|
||||
// bundleURL - The URL to the application bundle to watch. This must not be nil.
|
||||
// bundleID - The identifier of the application bundle to watch. This must not
|
||||
// be nil.
|
||||
- (id)initWithURL:(NSURL *)bundleURL bundleIdentifier:(NSString *)bundleID;
|
||||
|
||||
// Lazily waits for termination of all instances of the application identified
|
||||
// at initialization.
|
||||
//
|
||||
// Returns a signal which send an `NSRunningApplication` for each instance of the
|
||||
// application that is being watched (before the instance terminates), then
|
||||
// completes on a background scheduler.
|
||||
- (RACSignal *)waitForTermination;
|
||||
|
||||
@end
|
||||
@@ -1,95 +0,0 @@
|
||||
//
|
||||
// SQRLTerminationListener.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-10-04.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLTerminationListener.h"
|
||||
|
||||
#import "EXTKeyPathCoding.h"
|
||||
#import <ReactiveCocoa/NSArray+RACSequenceAdditions.h>
|
||||
#import <ReactiveCocoa/RACDisposable.h>
|
||||
#import <ReactiveCocoa/RACScheduler.h>
|
||||
#import <ReactiveCocoa/RACSequence.h>
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACSubscriber.h>
|
||||
|
||||
@interface SQRLTerminationListener ()
|
||||
|
||||
@property (nonatomic, copy, readonly) NSURL *bundleURL;
|
||||
@property (nonatomic, copy, readonly) NSString *bundleIdentifier;
|
||||
|
||||
// Waits for the process identified by the given PID to terminate.
|
||||
//
|
||||
// Returns a signal which sends `processIdentifier` as soon as the process is
|
||||
// being monitored, then completes once it exits, all on a background thread.
|
||||
- (RACSignal *)waitForTerminationOfProcessIdentifier:(pid_t)processIdentifier;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SQRLTerminationListener
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
- (id)initWithURL:(NSURL *)bundleURL bundleIdentifier:(NSString *)bundleID {
|
||||
NSParameterAssert(bundleURL != nil);
|
||||
NSParameterAssert(bundleID != nil);
|
||||
|
||||
self = [super init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
_bundleURL = bundleURL.URLByStandardizingPath;
|
||||
_bundleIdentifier = [bundleID copy];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark Termination Listening
|
||||
|
||||
- (RACSignal *)waitForTermination {
|
||||
return [[[[RACSignal
|
||||
defer:^{
|
||||
NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:self.bundleIdentifier];
|
||||
return [apps.rac_sequence signalWithScheduler:RACScheduler.immediateScheduler];
|
||||
}]
|
||||
filter:^(NSRunningApplication *application) {
|
||||
return [application.bundleURL.URLByStandardizingPath isEqual:self.bundleURL];
|
||||
}]
|
||||
flattenMap:^(NSRunningApplication *application) {
|
||||
return [[self
|
||||
waitForTerminationOfProcessIdentifier:application.processIdentifier]
|
||||
mapReplace:application];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -waitForTermination", self];
|
||||
}
|
||||
|
||||
- (RACSignal *)waitForTerminationOfProcessIdentifier:(pid_t)processIdentifier {
|
||||
return [[RACSignal
|
||||
createSignal:^(id<RACSubscriber> subscriber) {
|
||||
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, processIdentifier, DISPATCH_PROC_EXIT, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
|
||||
|
||||
dispatch_source_set_registration_handler(source, ^{
|
||||
[subscriber sendNext:@(processIdentifier)];
|
||||
});
|
||||
|
||||
dispatch_source_set_event_handler(source, ^{
|
||||
[subscriber sendCompleted];
|
||||
});
|
||||
|
||||
dispatch_resume(source);
|
||||
return [RACDisposable disposableWithBlock:^{
|
||||
dispatch_source_cancel(source);
|
||||
}];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -waitForTerminationOfProcessIdentifier: %i", self, (int)processIdentifier];
|
||||
}
|
||||
|
||||
#pragma mark NSObject
|
||||
|
||||
- (NSString *)description {
|
||||
return [NSString stringWithFormat:@"<%@: %p>{ bundleURL: %@, bundleIdentifier: %@ }", self.class, self, self.bundleURL, self.bundleIdentifier];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -74,7 +74,7 @@ NSString * const SQRLUpdateJSONPublicationDateKey = @"pub_date";
|
||||
|
||||
+ (NSValueTransformer *)releaseDateJSONTransformer {
|
||||
// ISO 8601 Time Zone with ':'
|
||||
NSString * const ISO8601DateFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ";
|
||||
NSString * const ISO8601DateFormat = @"yyyy'-'MM'-'DD'T'HH':'mm':'ssZZZZZ";
|
||||
|
||||
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^ NSDate * (NSString *dateString) {
|
||||
if (![dateString isKindOfClass:NSString.class]) return nil;
|
||||
|
||||
@@ -6,9 +6,6 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
|
||||
// Represents the current state of the updater.
|
||||
//
|
||||
// SQRLUpdaterStateIdle - Doing absolutely diddly squat.
|
||||
@@ -23,9 +20,6 @@ typedef enum : NSUInteger {
|
||||
SQRLUpdaterStateAwaitingRelaunch,
|
||||
} SQRLUpdaterState;
|
||||
|
||||
// Block for providing download requests given a download url
|
||||
typedef NSURLRequest * (^SQRLRequestForDownload)(NSURL *);
|
||||
|
||||
// The domain for errors originating within SQRLUpdater.
|
||||
extern NSString * const SQRLUpdaterErrorDomain;
|
||||
|
||||
@@ -95,15 +89,6 @@ extern NSString * const SQRLUpdaterJSONObjectErrorKey;
|
||||
// This property must never be set to nil.
|
||||
@property (atomic, copy) NSURLRequest *updateRequest;
|
||||
|
||||
// The block used for fetching a given download request
|
||||
//
|
||||
// The default value is the argument that was originally passed to
|
||||
// -initWithUpdateRequest:requestForDownload:.
|
||||
//
|
||||
// If initialized with -initWithUpdateRequest: this block will
|
||||
// return a generic NSURLRequest with the provided url.
|
||||
@property (nonatomic, copy) SQRLRequestForDownload requestForDownload;
|
||||
|
||||
// The `SQRLUpdate` subclass to instantiate with the server's response.
|
||||
//
|
||||
// By default, this is `SQRLUpdate` itself, but it can be set to a custom
|
||||
@@ -123,18 +108,6 @@ extern NSString * const SQRLUpdaterJSONObjectErrorKey;
|
||||
// Returns the initialized `SQRLUpdater`.
|
||||
- (id)initWithUpdateRequest:(NSURLRequest *)updateRequest;
|
||||
|
||||
// Initializes an updater that will send the given request to check for updates
|
||||
// and passes a block to provide requests for the update downloads.
|
||||
//
|
||||
// updateRequest - Same as with initWithUpdateRequest
|
||||
// requestForDownload - Once the update url is found for the update download, allow
|
||||
// providing custom requests that can be costomized as desired.
|
||||
// Useful for including `Authorization` headers just like the
|
||||
// updateRequest param.
|
||||
//
|
||||
// Returns the initialized `SQRLUpdater`.
|
||||
- (id)initWithUpdateRequest:(NSURLRequest *)updateRequest requestForDownload:(SQRLRequestForDownload)requestForDownload;
|
||||
|
||||
// Executes `checkForUpdatesCommand` (if enabled) every `interval` seconds.
|
||||
//
|
||||
// The first check will not occur until `interval` seconds have passed.
|
||||
|
||||
+115
-233
@@ -14,13 +14,13 @@
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLDownloadedUpdate.h"
|
||||
#import "SQRLShipItLauncher.h"
|
||||
#import "SQRLShipItConnection.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import "SQRLUpdate.h"
|
||||
#import "SQRLZipArchiver.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <sys/mount.h>
|
||||
|
||||
NSString * const SQRLUpdaterErrorDomain = @"SQRLUpdaterErrorDomain";
|
||||
NSString * const SQRLUpdaterServerDataErrorKey = @"SQRLUpdaterServerDataErrorKey";
|
||||
@@ -33,9 +33,6 @@ const NSInteger SQRLUpdaterErrorInvalidServerResponse = 5;
|
||||
const NSInteger SQRLUpdaterErrorInvalidJSON = 6;
|
||||
const NSInteger SQRLUpdaterErrorInvalidServerBody = 7;
|
||||
|
||||
/// The application's being run on a read-only volume.
|
||||
const NSInteger SQRLUpdaterErrorReadOnlyVolume = 8;
|
||||
|
||||
// The prefix used when creating temporary directories for updates. This will be
|
||||
// followed by a random string of characters.
|
||||
static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
@@ -44,18 +41,22 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
|
||||
@property (atomic, readwrite) SQRLUpdaterState state;
|
||||
|
||||
/// The etag of the currently downloaded update, nil if no update has been
|
||||
/// downloaded.
|
||||
@property (atomic, copy) NSString *etag;
|
||||
|
||||
// The code signature for the running application, used to check updates before
|
||||
// sending them to ShipIt.
|
||||
@property (nonatomic, strong, readonly) SQRLCodeSignature *signature;
|
||||
|
||||
// Lazily launches ShipIt upon first subscription.
|
||||
// When executed with an `SQRLShipItState`, launches ShipIt.
|
||||
@property (nonatomic, strong, readonly) RACCommand *shipItLauncher;
|
||||
|
||||
// Lazily removes outdated temporary directories (used for previous updates)
|
||||
// upon first subscription.
|
||||
//
|
||||
// Sends completed or error.
|
||||
@property (nonatomic, strong, readonly) RACSignal *shipItLauncher;
|
||||
// Pruning directories while an update is pending or in progress will result in
|
||||
// undefined behavior.
|
||||
//
|
||||
// Sends each removed directory then completes, or errors, on an unspecified
|
||||
// thread.
|
||||
@property (nonatomic, strong, readonly) RACSignal *prunedUpdateDirectories;
|
||||
|
||||
// Parses an update model from downloaded data.
|
||||
//
|
||||
@@ -144,19 +145,11 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
}
|
||||
|
||||
- (id)initWithUpdateRequest:(NSURLRequest *)updateRequest {
|
||||
return [self initWithUpdateRequest:updateRequest requestForDownload:^(NSURL *downloadURL) {
|
||||
return [NSURLRequest requestWithURL:downloadURL];
|
||||
}];
|
||||
}
|
||||
|
||||
- (id)initWithUpdateRequest:(NSURLRequest *)updateRequest requestForDownload:(SQRLRequestForDownload)requestForDownload {
|
||||
NSParameterAssert(updateRequest != nil);
|
||||
NSParameterAssert(requestForDownload != nil);
|
||||
|
||||
self = [super init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
_requestForDownload = [requestForDownload copy];
|
||||
_updateRequest = [updateRequest copy];
|
||||
_updateClass = SQRLUpdate.class;
|
||||
|
||||
@@ -175,6 +168,33 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
BOOL updatesDisabled = (getenv("DISABLE_UPDATE_CHECK") != NULL);
|
||||
@weakify(self);
|
||||
|
||||
_prunedUpdateDirectories = [[[[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItConnection.shipItJobLabel];
|
||||
return [directoryManager applicationSupportURL];
|
||||
}]
|
||||
flattenMap:^(NSURL *appSupportURL) {
|
||||
NSFileManager *manager = [[NSFileManager alloc] init];
|
||||
NSDirectoryEnumerator *enumerator = [manager enumeratorAtURL:appSupportURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:^(NSURL *URL, NSError *error) {
|
||||
NSLog(@"Error enumerating item %@ within directory %@: %@", URL, appSupportURL, error);
|
||||
return YES;
|
||||
}];
|
||||
|
||||
return [[enumerator.rac_sequence.signal
|
||||
filter:^(NSURL *enumeratedURL) {
|
||||
NSString *name = enumeratedURL.lastPathComponent;
|
||||
return [name hasPrefix:SQRLUpdaterUniqueTemporaryDirectoryPrefix];
|
||||
}]
|
||||
doNext:^(NSURL *directoryURL) {
|
||||
NSError *error = nil;
|
||||
if (![manager removeItemAtURL:directoryURL error:&error]) {
|
||||
NSLog(@"Error removing old update directory at %@: %@", directoryURL, error.sqrl_verboseDescription);
|
||||
}
|
||||
}];
|
||||
}]
|
||||
replayLazily]
|
||||
setNameWithFormat:@"%@ -prunedUpdateDirectories", self];
|
||||
|
||||
_checkForUpdatesCommand = [[RACCommand alloc] initWithEnabled:[RACSignal return:@(!updatesDisabled)] signalBlock:^(id _) {
|
||||
@strongify(self);
|
||||
NSParameterAssert(self.updateRequest != nil);
|
||||
@@ -183,8 +203,12 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
NSMutableURLRequest *request = [self.updateRequest mutableCopy];
|
||||
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
|
||||
|
||||
return [[[[[[[[self
|
||||
performHousekeeping]
|
||||
// Prune old updates before the first update check.
|
||||
return [[[[[[[[self.prunedUpdateDirectories
|
||||
catch:^(NSError *error) {
|
||||
NSLog(@"Error pruning old updates: %@", error);
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
then:^{
|
||||
self.state = SQRLUpdaterStateCheckingForUpdate;
|
||||
|
||||
@@ -206,16 +230,6 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
if (httpResponse.statusCode == 204 /* No Content */) {
|
||||
return [RACSignal empty];
|
||||
}
|
||||
|
||||
BOOL readOnlyVolume = [self isRunningOnReadOnlyVolume];
|
||||
if (readOnlyVolume) {
|
||||
NSDictionary *errorInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Cannot update while running on a read-only volume", nil),
|
||||
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"The application is on a read-only volume. Please move the application and try again. If you're on macOS Sierra or later, you'll need to move the application out of the Downloads directory. See https://github.com/Squirrel/Squirrel.Mac/issues/182 for more information.", nil),
|
||||
};
|
||||
NSError *error = [NSError errorWithDomain:SQRLUpdaterErrorDomain code:SQRLUpdaterErrorReadOnlyVolume userInfo:errorInfo];
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
}
|
||||
|
||||
return [RACSignal return:bodyData];
|
||||
@@ -242,31 +256,23 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
deliverOn:RACScheduler.mainThreadScheduler];
|
||||
}];
|
||||
|
||||
_shipItLauncher = [[[RACSignal
|
||||
defer:^{
|
||||
@strongify(self);
|
||||
_shipItLauncher = [[RACCommand alloc] initWithSignalBlock:^(SQRLShipItRequest *request) {
|
||||
NSURL *targetURL = request.targetBundleURL;
|
||||
|
||||
NSURL *targetURL = NSRunningApplication.currentApplication.bundleURL;
|
||||
NSNumber *targetWritable = nil;
|
||||
NSError *targetWritableError = nil;
|
||||
BOOL gotWritable = [targetURL getResourceValue:&targetWritable forKey:NSURLIsWritableKey error:&targetWritableError];
|
||||
|
||||
BOOL targetWritable = [self canWriteToURL:targetURL];
|
||||
BOOL parentWritable = [self canWriteToURL:targetURL.URLByDeletingLastPathComponent];
|
||||
return [SQRLShipItLauncher launchPrivileged:!targetWritable || !parentWritable];
|
||||
}]
|
||||
replayLazily]
|
||||
setNameWithFormat:@"shipItLauncher"];
|
||||
// If we can't determine whether it can be written, assume
|
||||
// nonprivileged and wait for another, more canonical error.
|
||||
SQRLShipItConnection *connection = [[SQRLShipItConnection alloc] initWithRootPrivileges:(gotWritable && !targetWritable.boolValue)];
|
||||
|
||||
return [connection sendRequest:request];
|
||||
}];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)canWriteToURL:(NSURL *)fileURL {
|
||||
NSNumber *writable = nil;
|
||||
NSError *writableError = nil;
|
||||
BOOL gotWritable = [fileURL getResourceValue:&writable forKey:NSURLIsWritableKey error:&writableError];
|
||||
// If we can't determine whether it can be written, assume nonprivileged and
|
||||
// wait for another, more canonical error.
|
||||
return !gotWritable || writable.boolValue;
|
||||
}
|
||||
|
||||
#pragma mark Checking for Updates
|
||||
|
||||
- (RACDisposable *)startAutomaticChecksWithInterval:(NSTimeInterval)interval {
|
||||
@@ -333,88 +339,36 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
return [[[self
|
||||
uniqueTemporaryDirectoryForUpdate]
|
||||
flattenMap:^(NSURL *downloadDirectory) {
|
||||
void (^cleanUp)(void) = ^{
|
||||
NSError *error;
|
||||
if (![NSFileManager.defaultManager removeItemAtURL:downloadDirectory error:&error]) {
|
||||
NSLog(@"Error removing temporary download directory at %@: %@", downloadDirectory, error.sqrl_verboseDescription);
|
||||
}
|
||||
};
|
||||
|
||||
return [[[self
|
||||
downloadBundleForUpdate:update intoDirectory:downloadDirectory]
|
||||
flattenMap:^(NSBundle *updateBundle) {
|
||||
// If the bundle is nil it means our conditional GET told us
|
||||
// we already downloaded the update. So just clean up.
|
||||
if (updateBundle == nil) {
|
||||
cleanUp();
|
||||
return [RACSignal empty];
|
||||
}
|
||||
|
||||
return [self verifyAndPrepareUpdate:update fromBundle:updateBundle];
|
||||
}]
|
||||
doError:^(id _) {
|
||||
cleanUp();
|
||||
}];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -downloadAndPrepareUpdate: %@", self, update];
|
||||
}
|
||||
|
||||
- (RACSignal *)unarchiveAndPrepareData:(NSData *)data withName:(NSString *)name intoDirectory:(NSURL *)downloadDirectory {
|
||||
return [[[[[RACSignal
|
||||
defer:^{
|
||||
NSURL *zipOutputURL = [downloadDirectory URLByAppendingPathComponent:name];
|
||||
NSError *error = nil;
|
||||
if ([data writeToURL:zipOutputURL options:NSDataWritingAtomic error:&error]) {
|
||||
return [RACSignal return:zipOutputURL];
|
||||
} else {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
}]
|
||||
doNext:^(NSURL *zipOutputURL) {
|
||||
NSLog(@"Download completed to: %@", zipOutputURL);
|
||||
}]
|
||||
flattenMap:^(NSURL *zipOutputURL) {
|
||||
return [[[[SQRLZipArchiver
|
||||
unzipArchiveAtURL:zipOutputURL intoDirectoryAtURL:downloadDirectory]
|
||||
ignoreValues]
|
||||
concat:[RACSignal return:zipOutputURL]]
|
||||
doCompleted:^{
|
||||
NSError *error = nil;
|
||||
if (![NSFileManager.defaultManager removeItemAtURL:zipOutputURL error:&error]) {
|
||||
NSLog(@"Error removing downloaded archive at %@: %@", zipOutputURL, error.sqrl_verboseDescription);
|
||||
if (![NSFileManager.defaultManager removeItemAtURL:downloadDirectory error:&error]) {
|
||||
NSLog(@"Error removing temporary download directory at %@: %@", downloadDirectory, error.sqrl_verboseDescription);
|
||||
}
|
||||
}];
|
||||
}]
|
||||
flattenMap:^(NSURL *zipOutputURL) {
|
||||
return [self updateBundleMatchingCurrentApplicationInDirectory:downloadDirectory];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -unarchiveAndPrepareData:withName: %@ intoDirectory: %@", self, name, downloadDirectory];
|
||||
setNameWithFormat:@"%@ -downloadAndPrepareUpdate: %@", self, update];
|
||||
}
|
||||
|
||||
- (RACSignal *)downloadBundleForUpdate:(SQRLUpdate *)update intoDirectory:(NSURL *)downloadDirectory {
|
||||
NSParameterAssert(update != nil);
|
||||
NSParameterAssert(downloadDirectory != nil);
|
||||
|
||||
return [[RACSignal
|
||||
return [[[[[RACSignal
|
||||
defer:^{
|
||||
NSURL *zipDownloadURL = update.updateURL;
|
||||
NSMutableURLRequest *zipDownloadRequest = [self.requestForDownload(zipDownloadURL) mutableCopy];
|
||||
|
||||
NSMutableURLRequest *zipDownloadRequest = [NSMutableURLRequest requestWithURL:zipDownloadURL];
|
||||
[zipDownloadRequest setValue:@"application/zip" forHTTPHeaderField:@"Accept"];
|
||||
if (self.etag != nil) {
|
||||
[zipDownloadRequest setValue:self.etag forHTTPHeaderField:@"If-None-Match"];
|
||||
}
|
||||
|
||||
return [[[NSURLConnection
|
||||
return [[[[NSURLConnection
|
||||
rac_sendAsynchronousRequest:zipDownloadRequest]
|
||||
reduceEach:^(NSURLResponse *response, NSData *bodyData) {
|
||||
if ([response isKindOfClass:NSHTTPURLResponse.class]) {
|
||||
NSHTTPURLResponse *httpResponse = (id)response;
|
||||
|
||||
if (httpResponse.statusCode == 304 /* Not Modified */) {
|
||||
return [RACSignal return:nil];
|
||||
}
|
||||
|
||||
if (!(httpResponse.statusCode >= 200 && httpResponse.statusCode <= 299)) {
|
||||
NSDictionary *errorInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Update download failed", nil),
|
||||
@@ -424,13 +378,37 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
NSError *error = [NSError errorWithDomain:SQRLUpdaterErrorDomain code:SQRLUpdaterErrorInvalidServerResponse userInfo:errorInfo];
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
|
||||
self.etag = httpResponse.allHeaderFields[@"ETag"];
|
||||
}
|
||||
|
||||
return [self unarchiveAndPrepareData:bodyData withName:zipDownloadURL.lastPathComponent intoDirectory:downloadDirectory];
|
||||
return [RACSignal return:bodyData];
|
||||
}]
|
||||
flatten];
|
||||
flatten]
|
||||
flattenMap:^(NSData *data) {
|
||||
NSURL *zipOutputURL = [downloadDirectory URLByAppendingPathComponent:zipDownloadURL.lastPathComponent];
|
||||
|
||||
NSError *error = nil;
|
||||
if ([data writeToURL:zipOutputURL options:NSDataWritingAtomic error:&error]) {
|
||||
return [RACSignal return:zipOutputURL];
|
||||
} else {
|
||||
return [RACSignal error:error];
|
||||
}
|
||||
}];
|
||||
}]
|
||||
doNext:^(NSURL *zipOutputURL) {
|
||||
NSLog(@"Download completed to: %@", zipOutputURL);
|
||||
}]
|
||||
flattenMap:^(NSURL *zipOutputURL) {
|
||||
return [[SQRLZipArchiver
|
||||
unzipArchiveAtURL:zipOutputURL intoDirectoryAtURL:downloadDirectory]
|
||||
doCompleted:^{
|
||||
NSError *error = nil;
|
||||
if (![NSFileManager.defaultManager removeItemAtURL:zipOutputURL error:&error]) {
|
||||
NSLog(@"Error removing downloaded archive at %@: %@", zipOutputURL, error.sqrl_verboseDescription);
|
||||
}
|
||||
}];
|
||||
}]
|
||||
then:^{
|
||||
return [self updateBundleMatchingCurrentApplicationInDirectory:downloadDirectory];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -downloadBundleForUpdate: %@ intoDirectory: %@", self, update, downloadDirectory];
|
||||
}
|
||||
@@ -440,11 +418,11 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
- (RACSignal *)uniqueTemporaryDirectoryForUpdate {
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return [directoryManager storageURL];
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItConnection.shipItJobLabel];
|
||||
return [directoryManager applicationSupportURL];
|
||||
}]
|
||||
flattenMap:^(NSURL *storageURL) {
|
||||
NSURL *updateDirectoryTemplate = [storageURL URLByAppendingPathComponent:[SQRLUpdaterUniqueTemporaryDirectoryPrefix stringByAppendingString:@"XXXXXXX"]];
|
||||
flattenMap:^(NSURL *appSupportURL) {
|
||||
NSURL *updateDirectoryTemplate = [appSupportURL URLByAppendingPathComponent:[SQRLUpdaterUniqueTemporaryDirectoryPrefix stringByAppendingString:@"XXXXXXX"]];
|
||||
char *updateDirectoryCString = strdup(updateDirectoryTemplate.path.fileSystemRepresentation);
|
||||
@onExit {
|
||||
free(updateDirectoryCString);
|
||||
@@ -514,106 +492,8 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
}
|
||||
|
||||
- (RACSignal *)shipItStateURL {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return directoryManager.shipItStateURL;
|
||||
}]
|
||||
setNameWithFormat:@"%@ -shipItStateURL", self];
|
||||
}
|
||||
|
||||
/// Is the host app running on a read-only volume?
|
||||
- (BOOL)isRunningOnReadOnlyVolume {
|
||||
struct statfs statfsInfo;
|
||||
NSURL *bundleURL = NSRunningApplication.currentApplication.bundleURL;
|
||||
int result = statfs(bundleURL.fileSystemRepresentation, &statfsInfo);
|
||||
if (result == 0) {
|
||||
return (statfsInfo.f_flags & MNT_RDONLY) != 0;
|
||||
} else {
|
||||
// If we can't even check if the volume is read-only, assume it is.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
- (RACSignal *)performHousekeeping {
|
||||
return [[RACSignal
|
||||
merge:@[ [self pruneUpdateDirectories], [self truncateLogs] ]]
|
||||
catch:^(NSError *error) {
|
||||
NSLog(@"Error doing housekeeping: %@", error);
|
||||
return [RACSignal empty];
|
||||
}];
|
||||
}
|
||||
|
||||
/// Lazily removes outdated temporary directories (used for previous updates)
|
||||
/// upon subscription.
|
||||
///
|
||||
/// Pruning directories while an update is pending or in progress will result in
|
||||
/// undefined behavior.
|
||||
///
|
||||
/// Sends each removed directory then completes, or errors, on an unspecified
|
||||
/// thread.
|
||||
- (RACSignal *)pruneUpdateDirectories {
|
||||
return [[[RACSignal
|
||||
defer:^{
|
||||
// If we already have updates downloaded we don't wanna prune them.
|
||||
if (self.state == SQRLUpdaterStateAwaitingRelaunch) return [RACSignal empty];
|
||||
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return [directoryManager storageURL];
|
||||
}]
|
||||
flattenMap:^(NSURL *storageURL) {
|
||||
NSFileManager *manager = [[NSFileManager alloc] init];
|
||||
NSDirectoryEnumerator *enumerator = [manager enumeratorAtURL:storageURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:^(NSURL *URL, NSError *error) {
|
||||
NSLog(@"Error enumerating item %@ within directory %@: %@", URL, storageURL, error);
|
||||
return YES;
|
||||
}];
|
||||
|
||||
return [[enumerator.rac_sequence.signal
|
||||
filter:^(NSURL *enumeratedURL) {
|
||||
NSString *name = enumeratedURL.lastPathComponent;
|
||||
return [name hasPrefix:SQRLUpdaterUniqueTemporaryDirectoryPrefix];
|
||||
}]
|
||||
doNext:^(NSURL *directoryURL) {
|
||||
NSError *error = nil;
|
||||
if (![manager removeItemAtURL:directoryURL error:&error]) {
|
||||
NSLog(@"Error removing old update directory at %@: %@", directoryURL, error.sqrl_verboseDescription);
|
||||
}
|
||||
}];
|
||||
}]
|
||||
setNameWithFormat:@"%@ -prunedUpdateDirectories", self];
|
||||
}
|
||||
|
||||
|
||||
// Like truncation, but backwards.
|
||||
- (RACSignal *)backwardTruncateFile:(NSURL *)fileURL {
|
||||
return [RACSignal defer:^{
|
||||
static const NSInteger MAX_LENGTH = 1024 * 1024 * 8;
|
||||
|
||||
NSError *error;
|
||||
NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:fileURL error:&error];
|
||||
if (handle == nil) return [RACSignal error:error];
|
||||
|
||||
unsigned long long fileLength = [handle seekToEndOfFile];
|
||||
if (fileLength <= MAX_LENGTH) return [RACSignal empty];
|
||||
|
||||
[handle seekToFileOffset:fileLength - MAX_LENGTH];
|
||||
NSData *mostRecentData = [handle readDataToEndOfFile];
|
||||
[handle truncateFileAtOffset:0];
|
||||
[handle writeData:mostRecentData];
|
||||
|
||||
return [RACSignal empty];
|
||||
}];
|
||||
}
|
||||
|
||||
- (RACSignal *)truncateLogs {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItLauncher.shipItJobLabel];
|
||||
return [RACSignal zip:@[ [directoryManager shipItStdoutURL], [directoryManager shipItStderrURL] ]];
|
||||
}]
|
||||
reduceEach:^(NSURL *stdoutURL, NSURL *stderrURL) {
|
||||
return [RACSignal merge:@[ [self backwardTruncateFile:stdoutURL], [self backwardTruncateFile:stderrURL] ]];
|
||||
}];
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:SQRLShipItConnection.shipItJobLabel];
|
||||
return directoryManager.shipItStateURL;
|
||||
}
|
||||
|
||||
#pragma mark Installing Updates
|
||||
@@ -642,30 +522,32 @@ static NSString * const SQRLUpdaterUniqueTemporaryDirectoryPrefix = @"update.";
|
||||
return [[[[RACSignal
|
||||
defer:^{
|
||||
NSRunningApplication *currentApplication = NSRunningApplication.currentApplication;
|
||||
NSBundle *appBundle = [NSBundle bundleWithURL:currentApplication.bundleURL];
|
||||
// Only use the update bundle's name if the user hasn't renamed the
|
||||
// app themselves.
|
||||
BOOL useUpdateBundleName = [appBundle.sqrl_executableName isEqual:currentApplication.bundleURL.lastPathComponent.stringByDeletingPathExtension];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:update.bundle.bundleURL targetBundleURL:currentApplication.bundleURL bundleIdentifier:currentApplication.bundleIdentifier launchAfterInstallation:NO];
|
||||
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:update.bundle.bundleURL targetBundleURL:currentApplication.bundleURL bundleIdentifier:currentApplication.bundleIdentifier launchAfterInstallation:NO useUpdateBundleName:useUpdateBundleName];
|
||||
return [request writeUsingURL:self.shipItStateURL];
|
||||
return [[self.shipItStateURL
|
||||
flattenMap:^(NSURL *location) {
|
||||
return [request writeToURL:location];
|
||||
}]
|
||||
concat:[RACSignal return:request]];
|
||||
}]
|
||||
then:^{
|
||||
return self.shipItLauncher;
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [self.shipItLauncher execute:request];
|
||||
}]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Preparing update", nil) description:NSLocalizedString(@"An update for %@ is being prepared. Interrupting the process could corrupt the application.", nil), NSRunningApplication.currentApplication.bundleIdentifier]
|
||||
setNameWithFormat:@"%@ -prepareUpdateForInstallation: %@", self, update];
|
||||
}
|
||||
|
||||
- (RACSignal *)relaunchToInstallUpdate {
|
||||
return [[[[[[[[SQRLShipItRequest
|
||||
readUsingURL:self.shipItStateURL]
|
||||
map:^(SQRLShipItRequest *request) {
|
||||
return [[SQRLShipItRequest alloc] initWithUpdateBundleURL:request.updateBundleURL targetBundleURL:request.targetBundleURL bundleIdentifier:request.bundleIdentifier launchAfterInstallation:YES useUpdateBundleName:request.useUpdateBundleName];
|
||||
}]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [[request
|
||||
writeUsingURL:self.shipItStateURL]
|
||||
return [[[[[[self.shipItStateURL
|
||||
flattenMap:^(NSURL *location) {
|
||||
return [[[[SQRLShipItRequest
|
||||
readFromURL:location]
|
||||
map:^(SQRLShipItRequest *request) {
|
||||
return [[SQRLShipItRequest alloc] initWithUpdateBundleURL:request.updateBundleURL targetBundleURL:request.targetBundleURL bundleIdentifier:request.bundleIdentifier launchAfterInstallation:YES];
|
||||
}]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [request writeToURL:location];
|
||||
}]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Preparing to relaunch", nil) description:NSLocalizedString(@"%@ is preparing to relaunch to install an update. Interrupting the process could corrupt the application.", nil), NSRunningApplication.currentApplication.bundleIdentifier];
|
||||
}]
|
||||
deliverOn:RACScheduler.mainThreadScheduler]
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
//
|
||||
// main.m
|
||||
// shipit
|
||||
//
|
||||
// Created by Alan Rogers on 29/07/2013.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#import "EXTScope.h"
|
||||
#import <ReactiveCocoa/RACCommand.h>
|
||||
#import <ReactiveCocoa/RACSignal+Operations.h>
|
||||
#import <ReactiveCocoa/RACScheduler.h>
|
||||
|
||||
#import "NSError+SQRLVerbosityExtensions.h"
|
||||
#import "RACSignal+SQRLTransactionExtensions.h"
|
||||
#import "SQRLInstaller.h"
|
||||
#import "SQRLInstaller+Private.h"
|
||||
#import "SQRLTerminationListener.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
// The maximum number of times ShipIt should run the same installation state, in
|
||||
// an attempt to update.
|
||||
//
|
||||
// If ShipIt is launched in the same state more than this number of times,
|
||||
// updating will abort.
|
||||
static const NSUInteger SQRLShipItMaximumInstallationAttempts = 3;
|
||||
|
||||
// The domain for errors generated here.
|
||||
static NSString * const SQRLShipItErrorDomain = @"SQRLShipItErrorDomain";
|
||||
|
||||
static NSUInteger installationAttempts(NSString *applicationIdentifier) {
|
||||
return CFPreferencesGetAppIntegerValue((__bridge CFStringRef)SQRLShipItInstallationAttemptsKey, (__bridge CFStringRef)applicationIdentifier, NULL);
|
||||
}
|
||||
|
||||
static BOOL setInstallationAttempts(NSString *applicationIdentifier, NSUInteger attempts) {
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLShipItInstallationAttemptsKey, (__bridge CFPropertyListRef)@(attempts), (__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
return CFPreferencesSynchronize((__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
}
|
||||
|
||||
static BOOL clearInstallationAttempts(NSString *applicationIdentifier) {
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLShipItInstallationAttemptsKey, NULL, (__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
return CFPreferencesSynchronize((__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
}
|
||||
|
||||
// Waits for all instances of the target application (as described in the
|
||||
// `request`) to exit, then sends completed.
|
||||
static RACSignal *waitForTerminationIfNecessary(SQRLShipItRequest *request) {
|
||||
return [[RACSignal
|
||||
defer:^{
|
||||
if (request.bundleIdentifier == nil) return [RACSignal empty];
|
||||
|
||||
SQRLTerminationListener *listener = [[SQRLTerminationListener alloc] initWithURL:request.targetBundleURL bundleIdentifier:request.bundleIdentifier];
|
||||
return [listener waitForTermination];
|
||||
}]
|
||||
setNameWithFormat:@"waitForTerminationIfNecessary"];
|
||||
}
|
||||
|
||||
static void installRequest(RACSignal *readRequestSignal, NSString *applicationIdentifier) {
|
||||
[[[[[readRequestSignal
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return waitForTerminationIfNecessary(request);
|
||||
}]
|
||||
ignoreValues]
|
||||
concat:readRequestSignal]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
SQRLInstaller *installer = [[SQRLInstaller alloc] initWithApplicationIdentifier:applicationIdentifier];
|
||||
|
||||
NSUInteger attempt = installationAttempts(applicationIdentifier) + 1;
|
||||
setInstallationAttempts(applicationIdentifier, attempt);
|
||||
|
||||
RACSignal *action;
|
||||
if (attempt > SQRLShipItMaximumInstallationAttempts) {
|
||||
action = [[[[installer.abortInstallationCommand
|
||||
execute:request]
|
||||
initially:^{
|
||||
NSLog(@"Too many attempts to install, aborting update");
|
||||
}]
|
||||
catch:^(NSError *error) {
|
||||
NSLog(@"Error aborting installation: %@", error);
|
||||
|
||||
// Exit successfully so launchd doesn't restart us
|
||||
// again.
|
||||
return [RACSignal empty];
|
||||
}]
|
||||
concat:[RACSignal return:request]];
|
||||
} else {
|
||||
action = [[[[installer.installUpdateCommand
|
||||
execute:request]
|
||||
initially:^{
|
||||
BOOL freshInstall = (attempt == 1);
|
||||
if (freshInstall) {
|
||||
NSLog(@"Beginning installation");
|
||||
} else {
|
||||
NSLog(@"Resuming installation attempt %i", (int)attempt);
|
||||
}
|
||||
}]
|
||||
doCompleted:^{
|
||||
NSLog(@"Installation completed successfully");
|
||||
}]
|
||||
sqrl_addTransactionWithName:NSLocalizedString(@"Updating", nil) description:NSLocalizedString(@"%@ is being updated, and interrupting the process could corrupt the application", nil), request.targetBundleURL.path];
|
||||
}
|
||||
|
||||
// Clear the installation attempts for a successful abort or
|
||||
// install.
|
||||
action = [action doCompleted:^{
|
||||
clearInstallationAttempts(applicationIdentifier);
|
||||
}];
|
||||
|
||||
if (request.launchAfterInstallation) {
|
||||
// Launch regardless of whether installation succeeds or fails.
|
||||
action = [[action
|
||||
deliverOn:RACScheduler.mainThreadScheduler]
|
||||
doNext:^(SQRLShipItRequest *finalRequest) {
|
||||
NSURL *bundleURL = finalRequest.targetBundleURL;
|
||||
if (bundleURL == nil) {
|
||||
NSLog(@"Missing target bundle URL, cannot launch application");
|
||||
return;
|
||||
}
|
||||
|
||||
NSError *error;
|
||||
if (![NSWorkspace.sharedWorkspace launchApplicationAtURL:bundleURL options:NSWorkspaceLaunchDefault configuration:@{} error:&error]) {
|
||||
NSLog(@"Could not launch application at %@: %@", bundleURL, error);
|
||||
return;
|
||||
}
|
||||
|
||||
NSLog(@"Application launched at %@", bundleURL);
|
||||
}];
|
||||
}
|
||||
|
||||
return action;
|
||||
}]
|
||||
subscribeError:^(NSError *error) {
|
||||
NSLog(@"Installation error: %@", error);
|
||||
exit(EXIT_FAILURE);
|
||||
} completed:^{
|
||||
exit(EXIT_SUCCESS);
|
||||
}];
|
||||
}
|
||||
|
||||
int main(int argc, const char * argv[]) {
|
||||
@autoreleasepool {
|
||||
atexit_b(^{
|
||||
NSLog(@"ShipIt quitting");
|
||||
});
|
||||
|
||||
if (argc < 3) {
|
||||
NSLog(@"Missing launchd job label or state path for ShipIt");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
char const *jobLabel = argv[1];
|
||||
const char *statePath = argv[2];
|
||||
NSURL *shipItStateURL = [NSURL fileURLWithPath:@(statePath)];
|
||||
installRequest([SQRLShipItRequest readUsingURL:[RACSignal return:shipItStateURL]], @(jobLabel));
|
||||
|
||||
dispatch_main();
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//
|
||||
// main.m
|
||||
// shipit
|
||||
//
|
||||
// Created by Alan Rogers on 29/07/2013.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import "NSError+SQRLVerbosityExtensions.h"
|
||||
#import "RACSignal+SQRLTransactionExtensions.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLInstaller.h"
|
||||
#import "SQRLInstaller+Private.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
// The domain for errors generated here.
|
||||
static NSString * const SQRLShipItErrorDomain = @"SQRLShipItErrorDomain";
|
||||
|
||||
typedef NS_ENUM(NSInteger, SQRLShipItError) {
|
||||
SQRLShipItErrorUnknownAction,
|
||||
SQRLShipItErrorMissingRequestData,
|
||||
};
|
||||
|
||||
static void reply(xpc_object_t response) {
|
||||
xpc_connection_t connection = xpc_dictionary_get_remote_connection(response);
|
||||
xpc_connection_send_message(connection, response);
|
||||
}
|
||||
|
||||
static void replyWithError(xpc_object_t response, NSError *error) {
|
||||
xpc_dictionary_set_bool(response, "success", false);
|
||||
|
||||
if (error != nil) {
|
||||
xpc_object_t errorDictionary = xpc_dictionary_create(NULL, NULL, 0);
|
||||
xpc_dictionary_set_string(errorDictionary, "domain", error.domain.UTF8String);
|
||||
xpc_dictionary_set_int64(errorDictionary, "code", error.code);
|
||||
xpc_dictionary_set_string(errorDictionary, "description", error.localizedDescription.UTF8String);
|
||||
xpc_dictionary_set_string(errorDictionary, "failureReason", error.localizedFailureReason.UTF8String);
|
||||
xpc_dictionary_set_string(errorDictionary, "recoverySuggestion", error.localizedRecoverySuggestion.UTF8String);
|
||||
xpc_dictionary_set_value(response, "error", errorDictionary);
|
||||
xpc_release(errorDictionary);
|
||||
}
|
||||
|
||||
reply(response);
|
||||
}
|
||||
|
||||
static void replyWithSuccess(xpc_object_t response) {
|
||||
xpc_dictionary_set_bool(response, "success", true);
|
||||
reply(response);
|
||||
}
|
||||
|
||||
// Client requests from peer connections.
|
||||
//
|
||||
// applicationIdentifier - Current process reverse DNS identifier.
|
||||
// request - XPC dictionary request object.
|
||||
//
|
||||
// Returns nothing.
|
||||
static void handleRequest(NSString *applicationIdentifier, xpc_object_t request) {
|
||||
xpc_object_t response = xpc_dictionary_create_reply(request);
|
||||
|
||||
SQRLInstaller *installer = [[SQRLInstaller alloc] initWithApplicationIdentifier:applicationIdentifier];
|
||||
|
||||
char const *action = xpc_dictionary_get_string(request, "action");
|
||||
if (strcmp(action, "install") != 0) {
|
||||
NSDictionary *errorInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Cannot process \"%s\" requests", action],
|
||||
};
|
||||
replyWithError(response, [NSError errorWithDomain:SQRLShipItErrorDomain code:SQRLShipItErrorUnknownAction userInfo:errorInfo]);
|
||||
return;
|
||||
}
|
||||
|
||||
size_t length;
|
||||
void const *requestBytes = xpc_dictionary_get_data(request, "request", &length);
|
||||
if (requestBytes == NULL) {
|
||||
NSDictionary *errorInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Cannot process \"%s\" requests without \"request\" data", action],
|
||||
};
|
||||
replyWithError(response, [NSError errorWithDomain:SQRLShipItErrorDomain code:SQRLShipItErrorUnknownAction userInfo:errorInfo]);
|
||||
return;
|
||||
}
|
||||
|
||||
[[[SQRLShipItRequest
|
||||
readFromData:[NSData dataWithBytes:requestBytes length:length] ]
|
||||
flattenMap:^(SQRLShipItRequest *request) {
|
||||
return [[installer.installUpdateCommand
|
||||
execute:request]
|
||||
catch:^(NSError *error) {
|
||||
return [[[installer.abortInstallationCommand
|
||||
execute:nil]
|
||||
doCompleted:^{
|
||||
NSLog(@"Abort completed successfully");
|
||||
}]
|
||||
concat:[RACSignal error:error]];
|
||||
}];
|
||||
}]
|
||||
subscribeError:^(NSError *error){
|
||||
NSLog(@"Installation failed with error: %@ %@", error, error.userInfo);
|
||||
replyWithError(response, error);
|
||||
} completed:^{
|
||||
NSLog(@"Installation completed successfully");
|
||||
replyWithSuccess(response);
|
||||
}];
|
||||
}
|
||||
|
||||
// Peer connections from the listener connection.
|
||||
//
|
||||
// applicationIdentifier - Current process reverse DNS identifier.
|
||||
// newConnection - The newly accepted connection from the listener.
|
||||
//
|
||||
// Returns nothing.
|
||||
static void handleConnection(NSString *applicationIdentifier, xpc_connection_t newConnection) {
|
||||
xpc_connection_set_event_handler(newConnection, ^(xpc_object_t object) {
|
||||
xpc_type_t type = xpc_get_type(object);
|
||||
if (type == XPC_TYPE_ERROR) {
|
||||
char *description = xpc_copy_description(object);
|
||||
NSLog(@"XPC peer error: %s", description);
|
||||
free(description);
|
||||
return;
|
||||
}
|
||||
|
||||
if (type != XPC_TYPE_DICTIONARY) {
|
||||
NSLog(@"XPC peer expected dictionary");
|
||||
return;
|
||||
}
|
||||
|
||||
handleRequest(applicationIdentifier, object);
|
||||
});
|
||||
xpc_connection_resume(newConnection);
|
||||
}
|
||||
|
||||
// Listens for XPC messages from clients.
|
||||
//
|
||||
// Arguments are expected in the following order:
|
||||
//
|
||||
// jobLabel - The launchd job label for this task.
|
||||
//
|
||||
// Returns 0 on successful termination, non 0 otherwise.
|
||||
int main(int argc, const char * argv[]) {
|
||||
@autoreleasepool {
|
||||
atexit_b(^{
|
||||
NSLog(@"ShipIt quitting");
|
||||
});
|
||||
|
||||
if (argc < 2) {
|
||||
NSLog(@"Missing launchd job label for ShipIt");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
char const *jobLabel = argv[1];
|
||||
NSString *applicationIdentifier = @(jobLabel);
|
||||
|
||||
xpc_connection_t server = xpc_connection_create_mach_service(jobLabel, NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER);
|
||||
xpc_connection_set_event_handler(server, ^(xpc_object_t object) {
|
||||
xpc_type_t type = xpc_get_type(object);
|
||||
if (type == XPC_TYPE_ERROR) {
|
||||
char *description = xpc_copy_description(object);
|
||||
NSLog(@"XPC listener error: %s", description);
|
||||
free(description);
|
||||
} else if (type == XPC_TYPE_CONNECTION) {
|
||||
handleConnection(applicationIdentifier, object);
|
||||
}
|
||||
});
|
||||
xpc_connection_resume(server);
|
||||
|
||||
dispatch_main();
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
<key>CFBundleIconFile</key>
|
||||
<string></string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<string>com.github.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
//
|
||||
// Prefix header for all source files of the 'Squirrel' target in the 'Squirrel' project
|
||||
//
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <SystemConfiguration/SystemConfiguration.h>
|
||||
#endif
|
||||
@@ -6,14 +6,6 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for Squirrel.
|
||||
FOUNDATION_EXPORT double SquirrelVersionNumber;
|
||||
|
||||
//! Project version string for Squirrel.
|
||||
FOUNDATION_EXPORT const unsigned char SquirrelVersionString[];
|
||||
|
||||
#import <Squirrel/NSBundle+SQRLVersionExtensions.h>
|
||||
#import <Squirrel/NSProcessInfo+SQRLVersionExtensions.h>
|
||||
#import <Squirrel/SQRLDownloadedUpdate.h>
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/* Localized versions of Info.plist keys */
|
||||
|
||||
@@ -6,35 +6,30 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
QuickSpecBegin(NSProcessInfoExtensions)
|
||||
SpecBegin(NSProcessInfoExtensions)
|
||||
|
||||
describe(@"-sqrl_operatingSystemShortVersionString", ^{
|
||||
__block NSString *versionString;
|
||||
|
||||
beforeEach(^{
|
||||
versionString = NSProcessInfo.processInfo.sqrl_operatingSystemShortVersionString;
|
||||
expect(versionString).notTo(beNil());
|
||||
expect(versionString).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should follow major.minor.patch format", ^{
|
||||
NSError *error = nil;
|
||||
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]+(\\.[0-9]+)*$" options:0 error:&error];
|
||||
expect(regex).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(regex).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
NSRange fullRange = NSMakeRange(0, versionString.length);
|
||||
NSRange matchRange = [regex rangeOfFirstMatchInString:versionString options:0 range:fullRange];
|
||||
expect(@(NSEqualRanges(matchRange, fullRange))).to(beTruthy());
|
||||
expect(NSEqualRanges(matchRange, fullRange)).to.beTruthy();
|
||||
});
|
||||
|
||||
it(@"should be numerically comparable", ^{
|
||||
expect(@([@"10.6.9" compare:versionString options:NSNumericSearch])).to(equal(@(NSOrderedAscending)));
|
||||
expect([@"10.6.9" compare:versionString options:NSNumericSearch]).to.equal(NSOrderedAscending);
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -6,16 +6,9 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLCodeSignatureSpec)
|
||||
SpecBegin(SQRLCodeSignature)
|
||||
|
||||
__block NSBundle *bundle;
|
||||
__block void (^corruptURL)(NSURL *URL);
|
||||
@@ -24,26 +17,26 @@ beforeEach(^{
|
||||
bundle = self.testApplicationBundle;
|
||||
|
||||
corruptURL = ^(NSURL *URL) {
|
||||
expect(@([@"this bundle is corrupted, yo" writeToURL:bundle.executableURL atomically:YES encoding:NSUTF8StringEncoding error:NULL])).to(beTruthy());
|
||||
expect([@"this bundle is corrupted, yo" writeToURL:bundle.executableURL atomically:YES encoding:NSUTF8StringEncoding error:NULL]).to.beTruthy();
|
||||
};
|
||||
});
|
||||
|
||||
it(@"should verify a valid bundle", ^{
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should fail to verify with different code signing requirements", ^{
|
||||
NSError *error = nil;
|
||||
SQRLCodeSignature *signature = [SQRLCodeSignature currentApplicationSignature:&error];
|
||||
expect(signature).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(signature).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
BOOL success = [[signature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
expect(success).to.beFalsy();
|
||||
expect(error).notTo.beNil();
|
||||
});
|
||||
|
||||
describe(@"code signature changes", ^{
|
||||
@@ -54,15 +47,15 @@ describe(@"code signature changes", ^{
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing code signature", ^{
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL]).to.beTruthy();
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt code signature", ^{
|
||||
@@ -70,25 +63,25 @@ describe(@"code signature changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"main executable changes", ^{
|
||||
it(@"should fail to verify a bundle with a missing executable", ^{
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:bundle.executableURL error:NULL])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:bundle.executableURL error:NULL]).to.beTruthy();
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorCouldNotCreateStaticCode);
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt executable", ^{
|
||||
@@ -96,11 +89,11 @@ describe(@"main executable changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -109,19 +102,19 @@ describe(@"helper executable changes", ^{
|
||||
|
||||
beforeEach(^{
|
||||
helperURL = [bundle URLForAuxiliaryExecutable:@"unused-helper"];
|
||||
expect(helperURL).notTo(beNil());
|
||||
expect(helperURL).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing helper", ^{
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:helperURL error:NULL])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:helperURL error:NULL]).to.beTruthy();
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt helper", ^{
|
||||
@@ -129,11 +122,11 @@ describe(@"helper executable changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -142,19 +135,19 @@ describe(@"resource changes", ^{
|
||||
|
||||
beforeEach(^{
|
||||
resourceURL = [bundle URLForResource:@"MainMenu" withExtension:@"nib"];
|
||||
expect(resourceURL).notTo(beNil());
|
||||
expect(resourceURL).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing resource", ^{
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:resourceURL error:NULL])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:resourceURL error:NULL]).to.beTruthy();
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt resource", ^{
|
||||
@@ -162,11 +155,11 @@ describe(@"resource changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -178,15 +171,15 @@ describe(@"framework changes", ^{
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a missing framework", ^{
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:frameworkURL error:NULL])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:frameworkURL error:NULL]).to.beTruthy();
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
|
||||
it(@"should fail to verify a bundle with a corrupt framework", ^{
|
||||
@@ -194,12 +187,12 @@ describe(@"framework changes", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:bundle.bundleURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLCodeSignatureErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLCodeSignatureErrorDidNotPass)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLCodeSignatureErrorDomain);
|
||||
expect(error.code).to.equal(SQRLCodeSignatureErrorDidNotPass);
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//
|
||||
// SQRLDeepCodesignSpec.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Keith Duncan on 2013-09-05.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
SpecBegin(SQRLDeepCodesign)
|
||||
|
||||
NSMutableDictionary * (^environmentSuitableForChildProcess)(void) = ^ {
|
||||
// Remove environment variables that configure the Obj-C runtime
|
||||
// Specifically OBJC_DISABLE_GC so that child processes aren't forced to
|
||||
// adopt the GC preference of the test suite
|
||||
NSMutableDictionary *environment = [NSProcessInfo.processInfo.environment mutableCopy];
|
||||
NSSet *objcEnvironmentVariables = [environment keysOfEntriesPassingTest:^(NSString *variable, id obj, BOOL *stop) {
|
||||
return [variable hasPrefix:@"OBJC"];
|
||||
}];
|
||||
[environment removeObjectsForKeys:objcEnvironmentVariables.allObjects];
|
||||
return environment;
|
||||
};
|
||||
|
||||
NSTask * (^codesignTaskWithArguments)(NSArray *) = ^ (NSArray *arguments) {
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = @"/usr/bin/xcrun";
|
||||
task.arguments = [@[ @"codesign" ] arrayByAddingObjectsFromArray:arguments];
|
||||
task.environment = environmentSuitableForChildProcess();
|
||||
return task;
|
||||
};
|
||||
|
||||
void (^resignTestApplicationPreserveEverythingButTheRequirements)(void) = ^{
|
||||
NSURL *testApplicationLocation = self.testApplicationURL;
|
||||
|
||||
NSTask *resignCodesignTask = codesignTaskWithArguments(@[
|
||||
@"--sign", @"-",
|
||||
@"--force",
|
||||
@"--verbose=4",
|
||||
@"--preserve-metadata=identifier,entitlements,resource-rules",
|
||||
testApplicationLocation.path,
|
||||
]);
|
||||
|
||||
[resignCodesignTask launch];
|
||||
[resignCodesignTask waitUntilExit];
|
||||
|
||||
expect(resignCodesignTask.terminationStatus).to.equal(0);
|
||||
};
|
||||
|
||||
void (^deepCodesignTestApplication)(void) = ^{
|
||||
NSURL *testApplicationLocation = self.testApplicationURL;
|
||||
|
||||
NSBundle *testsBundle = [NSBundle bundleForClass:self.class];
|
||||
NSURL *deepCodesignLocation = [testsBundle URLForResource:@"deep-codesign" withExtension:nil];
|
||||
|
||||
NSNumber *executable = nil;
|
||||
NSError *executableError = nil;
|
||||
BOOL getExecutable = [deepCodesignLocation getResourceValue:&executable forKey:NSURLIsExecutableKey error:&executableError];
|
||||
expect(getExecutable).to.beTruthy();
|
||||
expect(executable.boolValue).to.beTruthy();
|
||||
expect(executableError).to.beNil();
|
||||
|
||||
NSTask *deepCodesignTask = [[NSTask alloc] init];
|
||||
deepCodesignTask.launchPath = deepCodesignLocation.path;
|
||||
deepCodesignTask.standardError = [NSPipe pipe];
|
||||
deepCodesignTask.standardOutput = [NSPipe pipe];
|
||||
|
||||
NSMutableDictionary *environment = environmentSuitableForChildProcess();
|
||||
[environment addEntriesFromDictionary:@{
|
||||
@"CODE_SIGN_IDENTITY": @"-",
|
||||
@"CONFIGURATION_BUILD_DIR": testApplicationLocation.URLByDeletingLastPathComponent.path,
|
||||
@"FULL_PRODUCT_NAME": testApplicationLocation.lastPathComponent,
|
||||
}];
|
||||
|
||||
deepCodesignTask.environment = environment;
|
||||
|
||||
[deepCodesignTask launch];
|
||||
[deepCodesignTask waitUntilExit];
|
||||
|
||||
expect(deepCodesignTask.terminationStatus).to.equal(0);
|
||||
|
||||
/*
|
||||
By signing test application's contents, which are covered by test
|
||||
application's ResourceRules it's signature becomes invalid. Usually,
|
||||
Xcode would sign the application after deep-codesign has run so the
|
||||
signature would include the _signed_ child resources which are covered
|
||||
by test application's ResourceRules
|
||||
|
||||
test application is already signed, so we need to manually resign it
|
||||
|
||||
deep-codesign preserves the requirements, we can't use it to resign the
|
||||
root target, the new signing identity wouldn't verify against the
|
||||
original designated requirement
|
||||
*/
|
||||
resignTestApplicationPreserveEverythingButTheRequirements();
|
||||
};
|
||||
|
||||
BOOL (^deepVerify)(void) = ^ BOOL {
|
||||
NSTask *deepVerifyTask = codesignTaskWithArguments(@[
|
||||
@"--deep-verify",
|
||||
@"--verbose=4",
|
||||
self.testApplicationURL.path
|
||||
]);
|
||||
|
||||
[deepVerifyTask launch];
|
||||
[deepVerifyTask waitUntilExit];
|
||||
|
||||
return deepVerifyTask.terminationStatus == 0;
|
||||
};
|
||||
|
||||
it(@"should deep sign the test application", ^{
|
||||
deepCodesignTestApplication();
|
||||
});
|
||||
|
||||
xit(@"should deep verify after signing", ^{
|
||||
expect(deepVerify()).to.beFalsy();
|
||||
deepCodesignTestApplication();
|
||||
expect(deepVerify()).to.beTruthy();
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
@@ -6,44 +6,39 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
|
||||
QuickSpecBegin(SQRLDirectoryManagerSpec)
|
||||
SpecBegin(SQRLDirectoryManager)
|
||||
|
||||
__block NSString *otestIdentifier;
|
||||
|
||||
beforeEach(^{
|
||||
otestIdentifier = NSProcessInfo.processInfo.environment[@"FORCE_APP_IDENTIFIER"];
|
||||
expect(otestIdentifier).notTo(beNil());
|
||||
otestIdentifier = NSRunningApplication.currentApplication.localizedName;
|
||||
expect(otestIdentifier).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should initialize", ^{
|
||||
SQRLDirectoryManager *manager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:otestIdentifier];
|
||||
expect(manager).notTo(beNil());
|
||||
expect(manager).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should create a manager for the current app", ^{
|
||||
SQRLDirectoryManager *manager = SQRLDirectoryManager.currentApplicationManager;
|
||||
expect(manager).notTo(beNil());
|
||||
expect(manager).to(equal([[SQRLDirectoryManager alloc] initWithApplicationIdentifier:otestIdentifier]));
|
||||
expect(manager).notTo.beNil();
|
||||
expect(manager).to.equal([[SQRLDirectoryManager alloc] initWithApplicationIdentifier:otestIdentifier]);
|
||||
});
|
||||
|
||||
it(@"should send an Application Support URL", ^{
|
||||
SQRLDirectoryManager *manager = SQRLDirectoryManager.currentApplicationManager;
|
||||
|
||||
NSError *error = nil;
|
||||
NSURL *appSupportURL = [[manager storageURL] firstOrDefault:nil success:NULL error:&error];
|
||||
expect(appSupportURL).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
NSURL *appSupportURL = [[manager applicationSupportURL] firstOrDefault:nil success:NULL error:&error];
|
||||
expect(appSupportURL).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
__block BOOL directory = NO;
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:appSupportURL.path isDirectory:&directory])).to(beTruthy());
|
||||
expect(@(directory)).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:appSupportURL.path isDirectory:&directory]).to.beTruthy();
|
||||
expect(directory).to.beTruthy();
|
||||
});
|
||||
|
||||
it(@"should send a ShipIt state URL", ^{
|
||||
@@ -51,8 +46,8 @@ it(@"should send a ShipIt state URL", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
NSURL *stateURL = [[manager shipItStateURL] firstOrDefault:nil success:NULL error:&error];
|
||||
expect(stateURL).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(stateURL).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -6,29 +6,24 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLInstaller.h"
|
||||
#import "SQRLInstaller+Private.h"
|
||||
#import "SQRLInstallerOwnedBundle.h"
|
||||
#import "SQRLShipItConnection.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import "SQRLInstallerOwnedBundle.h"
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLInstallerSpec)
|
||||
SpecBegin(SQRLInstaller)
|
||||
|
||||
mode_t (^modeOfURL)(NSURL *) = ^ mode_t (NSURL *fileURL) {
|
||||
NSFileSecurity *fileSecurity = nil;
|
||||
BOOL success = [fileURL getResourceValue:&fileSecurity forKey:NSURLFileSecurityKey error:NULL];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(fileSecurity).notTo(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(fileSecurity).notTo.beNil();
|
||||
|
||||
__block mode_t mode;
|
||||
expect(@(CFFileSecurityGetMode((__bridge CFFileSecurityRef)fileSecurity, &mode))).to(beTruthy());
|
||||
expect(CFFileSecurityGetMode((__bridge CFFileSecurityRef)fileSecurity, &mode)).to.beTruthy();
|
||||
|
||||
return mode & (S_IRWXU | S_IRWXG | S_IRWXO);
|
||||
};
|
||||
@@ -40,71 +35,75 @@ beforeEach(^{
|
||||
});
|
||||
|
||||
it(@"should install an update using ShipIt", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
it(@"should install an update in process", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
|
||||
[self installWithRequest:request remote:NO];
|
||||
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
it(@"should install an update and relaunch", ^{
|
||||
NSString *bundleIdentifier = @"com.github.Squirrel.TestApplication";
|
||||
NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleIdentifier];
|
||||
expect(@(apps.count)).to(equal(@0));
|
||||
expect(apps.count).to.equal(0);
|
||||
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:YES useUpdateBundleName:NO];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:YES];
|
||||
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(@([NSRunningApplication runningApplicationsWithBundleIdentifier:bundleIdentifier].count)).toEventually(equal(@1));
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
expect([NSRunningApplication runningApplicationsWithBundleIdentifier:bundleIdentifier].count).will.equal(1);
|
||||
});
|
||||
|
||||
it(@"should install an update from another volume", ^{
|
||||
NSURL *diskImageURL = [self createAndMountDiskImageNamed:@"TestApplication 2.1" fromDirectory:updateURL.URLByDeletingLastPathComponent];
|
||||
updateURL = [diskImageURL URLByAppendingPathComponent:updateURL.lastPathComponent];
|
||||
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
it(@"should install an update to another volume", ^{
|
||||
NSURL *diskImageURL = [self createAndMountDiskImageNamed:@"TestApplication" fromDirectory:self.testApplicationURL.URLByDeletingLastPathComponent];
|
||||
NSURL *targetURL = [diskImageURL URLByAppendingPathComponent:self.testApplicationURL.lastPathComponent];
|
||||
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
NSURL *plistURL = [targetURL URLByAppendingPathComponent:@"Contents/Info.plist"];
|
||||
expect([NSDictionary dictionaryWithContentsOfURL:plistURL][SQRLBundleShortVersionStringKey]).withTimeout(SQRLLongTimeout).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect([NSDictionary dictionaryWithContentsOfURL:plistURL][SQRLBundleShortVersionStringKey]).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
describe(@"with backup restoration", ^{
|
||||
__block NSURL *targetURL;
|
||||
|
||||
__block SQRLShipItRequest *request;
|
||||
|
||||
beforeEach(^{
|
||||
targetURL = self.testApplicationURL;
|
||||
|
||||
request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
|
||||
NSURL *copiedTargetURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication Target.app"];
|
||||
expect(@([NSFileManager.defaultManager moveItemAtURL:targetURL toURL:copiedTargetURL error:NULL])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager moveItemAtURL:targetURL toURL:copiedTargetURL error:NULL]).to.beTruthy();
|
||||
|
||||
SQRLCodeSignature *codeSignature = self.testApplicationSignature;
|
||||
|
||||
SQRLInstallerOwnedBundle *ownedBundle = [[SQRLInstallerOwnedBundle alloc] initWithOriginalURL:targetURL temporaryURL:copiedTargetURL codeSignature:codeSignature];
|
||||
NSData *ownedBundleArchive = [NSKeyedArchiver archivedDataWithRootObject:ownedBundle];
|
||||
expect(ownedBundleArchive).notTo(beNil());
|
||||
expect(ownedBundleArchive).notTo.beNil();
|
||||
|
||||
// Set up ShipIt's preferences like it paused in the middle of an
|
||||
// installation.
|
||||
@@ -114,71 +113,56 @@ describe(@"with backup restoration", ^{
|
||||
CFPreferencesSetValue((__bridge CFStringRef)SQRLInstallerOwnedBundleKey, (__bridge CFDataRef)ownedBundleArchive, (__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
|
||||
BOOL synchronized = CFPreferencesSynchronize((__bridge CFStringRef)applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
|
||||
expect(@(synchronized)).to(beTruthy());
|
||||
expect(synchronized).to.beTruthy();
|
||||
});
|
||||
|
||||
afterEach(^{
|
||||
__block NSError *error;
|
||||
expect([[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error]).will.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(self.testApplicationBundleVersion).to.equal(SQRLTestApplicationOriginalShortVersionString);
|
||||
});
|
||||
|
||||
it(@"should not install an update after too many attempts", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
__block NSError *error;
|
||||
expect(@([[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error])).toEventually(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect(self.testApplicationBundleVersion).to(equal(SQRLTestApplicationOriginalShortVersionString));
|
||||
});
|
||||
|
||||
it(@"should relaunch even after failing to install an update", ^{
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:YES useUpdateBundleName:NO];
|
||||
request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:targetURL bundleIdentifier:nil launchAfterInstallation:YES];
|
||||
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(@([NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.github.Squirrel.TestApplication"].count)).toEventually(equal(@1));
|
||||
|
||||
__block NSError *error;
|
||||
expect(@([[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error])).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect(self.testApplicationBundleVersion).to(equal(SQRLTestApplicationOriginalShortVersionString));
|
||||
expect([NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.github.Squirrel.TestApplication"].count).will.equal(1);
|
||||
});
|
||||
});
|
||||
|
||||
it(@"should disallow writing the updated application except by the owner", ^{
|
||||
NSString *command = [NSString stringWithFormat:@"chmod -R 0777 '%@'", updateURL.path];
|
||||
expect(@(system(command.UTF8String))).to(equal(@0));
|
||||
expect(system(command.UTF8String)).to.equal(0);
|
||||
|
||||
expect(@(modeOfURL(updateURL))).to(equal(@0777));
|
||||
expect(@(modeOfURL([updateURL URLByAppendingPathComponent:@"Contents/MacOS/TestApplication"]))).to(equal(@0777));
|
||||
expect(modeOfURL(updateURL)).to.equal(0777);
|
||||
expect(modeOfURL([updateURL URLByAppendingPathComponent:@"Contents/MacOS/TestApplication"])).to.equal(0777);
|
||||
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
|
||||
expect(@(modeOfURL(self.testApplicationURL))).to(equal(@0755));
|
||||
expect(@(modeOfURL([self.testApplicationURL URLByAppendingPathComponent:@"Contents/MacOS/TestApplication"]))).to(equal(@0755));
|
||||
expect(modeOfURL(self.testApplicationURL)).to.equal(0755);
|
||||
expect(modeOfURL([self.testApplicationURL URLByAppendingPathComponent:@"Contents/MacOS/TestApplication"])).to.equal(0755);
|
||||
});
|
||||
|
||||
describe(@"signal handling", ^{
|
||||
__block NSURL *targetURL;
|
||||
|
||||
void (^verifyUpdate)(void) = ^{
|
||||
// Wait up to the launchd throttle interval, then verify that ShipIt
|
||||
// relaunched and finished installing the update.
|
||||
expect(self.testApplicationBundleVersion).withTimeout(SQRLLongTimeout).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
|
||||
NSError *error;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
};
|
||||
|
||||
beforeEach(^{
|
||||
// Copied so that we don't recreate the TestApplication bundle by
|
||||
// accessing the property.
|
||||
targetURL = self.testApplicationURL;
|
||||
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
|
||||
[self installWithRequest:request remote:YES];
|
||||
|
||||
@@ -188,24 +172,32 @@ describe(@"signal handling", ^{
|
||||
[NSThread sleepForTimeInterval:delay];
|
||||
});
|
||||
|
||||
afterEach(^{
|
||||
// Wait up to the launchd throttle interval, then verify that ShipIt
|
||||
// relaunched and finished installing the update.
|
||||
Expecta.asynchronousTestTimeout = 5;
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
|
||||
NSError *error;
|
||||
BOOL success = [[self.testApplicationSignature verifyBundleAtURL:targetURL] waitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should handle SIGHUP", ^{
|
||||
system("killall -HUP ShipIt");
|
||||
verifyUpdate();
|
||||
system("killall -HUP shipit-installer");
|
||||
});
|
||||
|
||||
it(@"should handle SIGTERM", ^{
|
||||
system("killall -TERM ShipIt");
|
||||
verifyUpdate();
|
||||
system("killall -TERM shipit-installer");
|
||||
});
|
||||
|
||||
it(@"should handle SIGINT", ^{
|
||||
system("killall -INT ShipIt");
|
||||
verifyUpdate();
|
||||
system("killall -INT shipit-installer");
|
||||
});
|
||||
|
||||
it(@"should handle SIGQUIT", ^{
|
||||
system("killall -QUIT ShipIt");
|
||||
verifyUpdate();
|
||||
system("killall -QUIT shipit-installer");
|
||||
});
|
||||
|
||||
it(@"should handle SIGKILL", ^{
|
||||
@@ -214,16 +206,14 @@ describe(@"signal handling", ^{
|
||||
//
|
||||
// Two SIGKILL signals means that it'll be launched three times (which
|
||||
// matches the maximum number of attempts per state).
|
||||
for (int i = 0; i < 2; i++) {
|
||||
system("killall -KILL ShipIt");
|
||||
for (int i = 0; i < 3; i++) {
|
||||
system("killall -KILL shipit-installer");
|
||||
|
||||
// Wait at least for the launchd throttle interval.
|
||||
NSTimeInterval delay = 2 + (arc4random_uniform(100) / 1000.0);
|
||||
[NSThread sleepForTimeInterval:delay];
|
||||
}
|
||||
|
||||
verifyUpdate();
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -6,17 +6,10 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLShipItRequestSpec)
|
||||
SpecBegin(SQRLShipItRequest)
|
||||
|
||||
__block SQRLDirectoryManager *directoryManager;
|
||||
__block SQRLShipItRequest *request;
|
||||
@@ -25,46 +18,46 @@ beforeEach(^{
|
||||
directoryManager = SQRLDirectoryManager.currentApplicationManager;
|
||||
|
||||
NSURL *updateURL = [self createTestApplicationUpdate];
|
||||
request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO useUpdateBundleName:NO];
|
||||
expect(request).notTo(beNil());
|
||||
request = [[SQRLShipItRequest alloc] initWithUpdateBundleURL:updateURL targetBundleURL:self.testApplicationURL bundleIdentifier:nil launchAfterInstallation:NO];
|
||||
expect(request).notTo.beNil();
|
||||
|
||||
expect(request.targetBundleURL).to(equal(self.testApplicationURL));
|
||||
expect(request.updateBundleURL).to(equal(updateURL));
|
||||
expect(request.bundleIdentifier).to(beNil());
|
||||
expect(@(request.launchAfterInstallation)).to(beFalsy());
|
||||
expect(request.targetBundleURL).to.equal(self.testApplicationURL);
|
||||
expect(request.updateBundleURL).to.equal(updateURL);
|
||||
expect(request.bundleIdentifier).to.beNil();
|
||||
expect(request.launchAfterInstallation).to.beFalsy();
|
||||
});
|
||||
|
||||
afterEach(^{
|
||||
NSURL *stateURL = [[directoryManager shipItStateURL] first];
|
||||
expect(stateURL).notTo(beNil());
|
||||
|
||||
expect(stateURL).notTo.beNil();
|
||||
|
||||
[NSFileManager.defaultManager removeItemAtURL:stateURL error:NULL];
|
||||
});
|
||||
|
||||
it(@"should copy", ^{
|
||||
SQRLShipItRequest *requestCopy = [request copy];
|
||||
expect(requestCopy).to(equal(request));
|
||||
expect(requestCopy).notTo(beIdenticalTo(request));
|
||||
expect(requestCopy).to.equal(request);
|
||||
expect(requestCopy).notTo.beIdenticalTo(request);
|
||||
});
|
||||
|
||||
it(@"should fail to read state when no file exists yet", ^{
|
||||
it(@"should fail to read when no file exists yet", ^{
|
||||
NSError *error;
|
||||
BOOL success = [[SQRLShipItRequest readUsingURL:directoryManager.shipItStateURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
BOOL success = [[SQRLShipItRequest readFromURL:[directoryManager.shipItStateURL first]] waitUntilCompleted:&error];
|
||||
expect(success).to.beFalsy();
|
||||
expect(error).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should write and read state to disk", ^{
|
||||
it(@"should write and read to disk", ^{
|
||||
NSError *error;
|
||||
BOOL success = [[request writeUsingURL:directoryManager.shipItStateURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
BOOL success = [[request writeToURL:[directoryManager.shipItStateURL first]] waitUntilCompleted:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
SQRLShipItRequest *readRequest = [[SQRLShipItRequest readUsingURL:directoryManager.shipItStateURL] firstOrDefault:nil success:&success error:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
SQRLShipItRequest *readRequest = [[SQRLShipItRequest readFromURL:[directoryManager.shipItStateURL first]] firstOrDefault:nil success:&success error:&error];
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(readRequest).to(equal(request));
|
||||
expect(readRequest).to.equal(request);
|
||||
});
|
||||
|
||||
it(@"should fail gracefully with archives encoding a different class", ^{
|
||||
@@ -72,15 +65,15 @@ it(@"should fail gracefully with archives encoding a different class", ^{
|
||||
|
||||
NSError *error;
|
||||
BOOL write = [[NSKeyedArchiver archivedDataWithRootObject:@"rogue object"] writeToURL:archiveLocation atomically:YES];
|
||||
expect(@(write)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(write).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
BOOL success = NO;
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest readUsingURL:[RACSignal return:archiveLocation]] firstOrDefault:nil success:&success error:&error];
|
||||
expect(request).to(beNil());
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error.domain).to(equal(SQRLShipItRequestErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLShipItRequestErrorUnarchiving)));
|
||||
SQRLShipItRequest *request = [[SQRLShipItRequest readFromURL:archiveLocation] firstOrDefault:nil success:&success error:&error];
|
||||
expect(request).to.beNil();
|
||||
expect(success).to.beFalsy();
|
||||
expect(error.domain).to.equal(SQRLShipItRequestErrorDomain);
|
||||
expect(error.code).to.equal(SQRLShipItRequestErrorUnarchiving);
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
//
|
||||
// SQRLTerminationListenerSpec.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-10-07.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLTerminationListener.h"
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
|
||||
QuickSpecBegin(SQRLTerminationListenerSpec)
|
||||
|
||||
__block SQRLTerminationListener *listener;
|
||||
|
||||
beforeEach(^{
|
||||
listener = [[SQRLTerminationListener alloc] initWithURL:self.testApplicationURL bundleIdentifier:self.testApplicationBundle.bundleIdentifier];
|
||||
expect(listener).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should complete immediately when the app is not running", ^{
|
||||
__block BOOL completed = NO;
|
||||
[[listener waitForTermination] subscribeCompleted:^{
|
||||
completed = YES;
|
||||
}];
|
||||
|
||||
expect(@(completed)).to(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should wait until one instance terminates", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSRunningApplication *app = [self launchTestApplicationWithEnvironment:nil];
|
||||
|
||||
__block NSRunningApplication *observedApp = nil;
|
||||
__block BOOL completed = NO;
|
||||
[[listener waitForTermination] subscribeNext:^(id x) {
|
||||
observedApp = x;
|
||||
} completed:^{
|
||||
completed = YES;
|
||||
}];
|
||||
|
||||
expect(observedApp).toEventually(equal(app));
|
||||
expect(@(completed)).to(beFalsy());
|
||||
|
||||
[app forceTerminate];
|
||||
expect(@(app.terminated)).toEventually(beTruthy());
|
||||
expect(@(completed)).toEventually(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should wait until multiple instances terminate", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSRunningApplication *app1 = [self launchTestApplicationWithEnvironment:nil];
|
||||
NSRunningApplication *app2 = [self launchTestApplicationWithEnvironment:nil];
|
||||
|
||||
__block BOOL completed = NO;
|
||||
[[listener waitForTermination] subscribeCompleted:^{
|
||||
completed = YES;
|
||||
}];
|
||||
|
||||
expect(@(completed)).to(beFalsy());
|
||||
|
||||
[app1 forceTerminate];
|
||||
expect(@(app1.terminated)).toEventually(beTruthy());
|
||||
expect(@(completed)).to(beFalsy());
|
||||
|
||||
[app2 forceTerminate];
|
||||
expect(@(app2.terminated)).toEventually(beTruthy());
|
||||
expect(@(completed)).toEventually(beTruthy());
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
@@ -1,19 +1,11 @@
|
||||
//
|
||||
// QuickSpec+SQRLFixtures.h
|
||||
// SQRLTestCase.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-06.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
/// See https://github.com/Squirrel/Squirrel.Mac/pull/154#issuecomment-151287744
|
||||
#define SKIP_IF_RUNNING_ON_TRAVIS if (self.runningOnTravis) return;
|
||||
|
||||
// The short version string for the `testApplicationBundle`.
|
||||
extern NSString * const SQRLTestApplicationOriginalShortVersionString;
|
||||
|
||||
@@ -24,15 +16,11 @@ extern NSString * const SQRLTestApplicationUpdatedShortVersionString;
|
||||
// The Info.plist key associated with a bundle's short version string.
|
||||
extern NSString * const SQRLBundleShortVersionStringKey;
|
||||
|
||||
/// The longer timeout we should use for things that take a long time. This is
|
||||
/// especially needed on slower machines (e.g., Travis CI).
|
||||
extern const NSTimeInterval SQRLLongTimeout;
|
||||
|
||||
@class SQRLCodeSignature;
|
||||
@class SQRLDirectoryManager;
|
||||
@class SQRLShipItRequest;
|
||||
|
||||
@interface QuickSpec (SQRLFixtures)
|
||||
@interface SQRLTestCase : SPTXCTestCase
|
||||
|
||||
// A URL to a temporary directory tests can use.
|
||||
//
|
||||
@@ -61,9 +49,6 @@ extern const NSTimeInterval SQRLLongTimeout;
|
||||
// A directory manager for finding URLs that apply to ShipIt.
|
||||
@property (nonatomic, strong, readonly) SQRLDirectoryManager *shipItDirectoryManager;
|
||||
|
||||
/// Are the tests currently being run on Travis?
|
||||
@property (nonatomic, readonly, assign, getter = isRunningOnTravis) BOOL runningOnTravis;
|
||||
|
||||
// Launches a new copy of TestApplication.app from the `testApplicationBundle`.
|
||||
//
|
||||
// Invoking this method multiple times will result in multiple running instances
|
||||
@@ -87,6 +72,8 @@ extern const NSTimeInterval SQRLLongTimeout;
|
||||
- (NSURL *)createTestApplicationUpdate;
|
||||
|
||||
// Runs the installer in process or submits ShipIt's launchd job to start it up.
|
||||
//
|
||||
// request - The install to send to ShipIt.
|
||||
- (void)installWithRequest:(SQRLShipItRequest *)request remote:(BOOL)remote;
|
||||
|
||||
// Creates a disk image, then mounts it.
|
||||
@@ -1,20 +1,20 @@
|
||||
//
|
||||
// QuickSpec+SQRLFixtures.m
|
||||
// SQRLTestCase.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-08-06.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
#import "SQRLTestCase.h"
|
||||
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLShipItConnection.h"
|
||||
#import "SQRLInstaller.h"
|
||||
#import "SQRLShipItLauncher.h"
|
||||
#import "SQRLShipItRequest.h"
|
||||
#import "SQRLTestHelper.h"
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||
@@ -23,8 +23,6 @@ NSString * const SQRLTestApplicationOriginalShortVersionString = @"1.0";
|
||||
NSString * const SQRLTestApplicationUpdatedShortVersionString = @"2.1";
|
||||
NSString * const SQRLBundleShortVersionStringKey = @"CFBundleShortVersionString";
|
||||
|
||||
const NSTimeInterval SQRLLongTimeout = 20;
|
||||
|
||||
static void SQRLKillAllTestApplications(void) {
|
||||
// Forcibly kill all copies of the TestApplication that may be running.
|
||||
NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.github.Squirrel.TestApplication"];
|
||||
@@ -45,25 +43,40 @@ static void SQRLSignalHandler(int sig) {
|
||||
abort();
|
||||
}
|
||||
|
||||
static NSBundle *SQRLTestBundle(void) {
|
||||
return [NSBundle bundleWithIdentifier:@"com.github.SquirrelTests"];
|
||||
}
|
||||
@interface SQRLTestCase ()
|
||||
|
||||
static NSMutableArray *cleanupBlocks = nil;
|
||||
// An array of dispatch_block_t values, for performing cleanup after the current
|
||||
// example finishes.
|
||||
//
|
||||
// This array will be emptied between each example.
|
||||
@property (nonatomic, strong, readonly) NSMutableArray *exampleCleanupBlocks;
|
||||
|
||||
// The URL to the temporary directory which contains `temporaryDirectoryURL` and
|
||||
// all copied test data.
|
||||
static NSURL *baseTemporaryDirectoryURL = nil;
|
||||
@property (nonatomic, copy, readonly) NSURL *baseTemporaryDirectoryURL;
|
||||
|
||||
QuickConfigurationBegin(Fixtures)
|
||||
// Returns an _unlaunched_ task that will follow log files at the given paths,
|
||||
// then pipe that output through this process.
|
||||
+ (NSTask *)tailTaskWithPaths:(RACSequence *)paths;
|
||||
|
||||
+ (void)configure:(Configuration *)configuration {
|
||||
@end
|
||||
|
||||
@implementation SQRLTestCase
|
||||
|
||||
#pragma mark Properties
|
||||
|
||||
@synthesize baseTemporaryDirectoryURL = _baseTemporaryDirectoryURL;
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
+ (void)load {
|
||||
NSURL *appSupportURL = [NSFileManager.defaultManager URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];
|
||||
NSAssert(appSupportURL != nil, @"Could not find Application Support folder");
|
||||
|
||||
NSArray *folders = @[
|
||||
@"com.github.Squirrel.TestApplication.ShipIt",
|
||||
@"com.github.Squirrel.SquirrelTests.ShipIt",
|
||||
@"otest.ShipIt",
|
||||
@"otest-x86_64.ShipIt",
|
||||
];
|
||||
|
||||
RACSequence *URLs = [folders.rac_sequence flattenMap:^(NSString *folder) {
|
||||
@@ -74,69 +87,79 @@ QuickConfigurationBegin(Fixtures)
|
||||
].rac_sequence;
|
||||
}];
|
||||
|
||||
[configuration beforeSuite:^{
|
||||
signal(SIGILL, &SQRLSignalHandler);
|
||||
NSSetUncaughtExceptionHandler(&SQRLUncaughtExceptionHandler);
|
||||
for (NSURL *URL in URLs) {
|
||||
[[NSData data] writeToURL:URL atomically:YES];
|
||||
}
|
||||
|
||||
cleanupBlocks = [NSMutableArray array];
|
||||
|
||||
for (NSURL *URL in URLs) {
|
||||
[NSFileManager.defaultManager createDirectoryAtURL:URL.URLByDeletingLastPathComponent withIntermediateDirectories:YES attributes:nil error:NULL];
|
||||
if (![[NSData data] writeToURL:URL atomically:YES]) {
|
||||
NSLog(@"Could not touch log file at %@", URL);
|
||||
}
|
||||
}
|
||||
RACSequence *paths = [URLs map:^(NSURL *URL) {
|
||||
return URL.path;
|
||||
}];
|
||||
|
||||
// We want to run any enqueued cleanup blocks after _and before_ each spec,
|
||||
// in case beforeSuites (for example) use the fixtures.
|
||||
void (^runCleanupBlocks)(void) = ^{
|
||||
// Enumerate backwards, so later resources are cleaned up first.
|
||||
for (dispatch_block_t block in cleanupBlocks.reverseObjectEnumerator) {
|
||||
block();
|
||||
}
|
||||
NSTask *readShipIt = [self tailTaskWithPaths:paths];
|
||||
[readShipIt launch];
|
||||
|
||||
[cleanupBlocks removeAllObjects];
|
||||
};
|
||||
NSAssert([readShipIt isRunning], @"Could not start task %@", readShipIt);
|
||||
|
||||
[configuration beforeEach:^{
|
||||
runCleanupBlocks();
|
||||
}];
|
||||
|
||||
[configuration afterEach:^{
|
||||
runCleanupBlocks();
|
||||
SQRLKillAllTestApplications();
|
||||
}];
|
||||
atexit_b(^{
|
||||
[readShipIt terminate];
|
||||
});
|
||||
}
|
||||
|
||||
QuickConfigurationEnd
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
|
||||
@implementation QuickSpec (SQRLFixtures)
|
||||
signal(SIGILL, &SQRLSignalHandler);
|
||||
NSSetUncaughtExceptionHandler(&SQRLUncaughtExceptionHandler);
|
||||
|
||||
#pragma mark Lifecycle
|
||||
Expecta.asynchronousTestTimeout = 3;
|
||||
}
|
||||
|
||||
- (void)tearDown {
|
||||
[super tearDown];
|
||||
|
||||
SQRLKillAllTestApplications();
|
||||
}
|
||||
|
||||
- (void)addCleanupBlock:(dispatch_block_t)block {
|
||||
[cleanupBlocks addObject:[block copy]];
|
||||
[SQRLTestHelper addCleanupBlock:block];
|
||||
}
|
||||
|
||||
#pragma mark Logging
|
||||
|
||||
+ (NSTask *)tailTaskWithPaths:(RACSequence *)paths {
|
||||
NSPipe *outputPipe = [NSPipe pipe];
|
||||
NSFileHandle *outputHandle = outputPipe.fileHandleForReading;
|
||||
|
||||
outputHandle.readabilityHandler = ^(NSFileHandle *handle) {
|
||||
NSString *output = [[NSString alloc] initWithData:handle.availableData encoding:NSUTF8StringEncoding];
|
||||
NSLog(@"\n%@", output);
|
||||
};
|
||||
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = @"/usr/bin/tail";
|
||||
task.standardOutput = outputPipe;
|
||||
task.arguments = [[paths startWith:@"-f"] array];
|
||||
return task;
|
||||
}
|
||||
|
||||
#pragma mark Temporary Directory
|
||||
|
||||
- (NSURL *)baseTemporaryDirectoryURL {
|
||||
if (baseTemporaryDirectoryURL == nil) {
|
||||
if (_baseTemporaryDirectoryURL == nil) {
|
||||
NSURL *globalTemporaryDirectory = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
|
||||
baseTemporaryDirectoryURL = [[globalTemporaryDirectory URLByAppendingPathComponent:@"com.github.SquirrelTests"] URLByAppendingPathComponent:[NSProcessInfo.processInfo globallyUniqueString]];
|
||||
_baseTemporaryDirectoryURL = [[globalTemporaryDirectory URLByAppendingPathComponent:@"com.github.SquirrelTests"] URLByAppendingPathComponent:[NSProcessInfo.processInfo globallyUniqueString]];
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [NSFileManager.defaultManager createDirectoryAtURL:baseTemporaryDirectoryURL withIntermediateDirectories:YES attributes:nil error:&error];
|
||||
XCTAssertTrue(success, @"Couldn't create temporary directory at %@: %@", baseTemporaryDirectoryURL, error);
|
||||
BOOL success = [NSFileManager.defaultManager createDirectoryAtURL:_baseTemporaryDirectoryURL withIntermediateDirectories:YES attributes:nil error:&error];
|
||||
XCTAssertTrue(success, @"Couldn't create temporary directory at %@: %@", _baseTemporaryDirectoryURL, error);
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
[NSFileManager.defaultManager removeItemAtURL:baseTemporaryDirectoryURL error:NULL];
|
||||
baseTemporaryDirectoryURL = nil;
|
||||
[NSFileManager.defaultManager removeItemAtURL:_baseTemporaryDirectoryURL error:NULL];
|
||||
_baseTemporaryDirectoryURL = nil;
|
||||
}];
|
||||
}
|
||||
|
||||
return baseTemporaryDirectoryURL;
|
||||
return _baseTemporaryDirectoryURL;
|
||||
}
|
||||
|
||||
- (NSURL *)temporaryDirectoryURL {
|
||||
@@ -154,7 +177,7 @@ QuickConfigurationEnd
|
||||
- (NSURL *)testApplicationURL {
|
||||
NSURL *fixtureURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication.app" isDirectory:YES];
|
||||
if (![NSFileManager.defaultManager fileExistsAtPath:fixtureURL.path]) {
|
||||
NSURL *bundleURL = [SQRLTestBundle() URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
NSURL *bundleURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
XCTAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
|
||||
NSError *error = nil;
|
||||
@@ -163,6 +186,15 @@ QuickConfigurationEnd
|
||||
|
||||
NSURL *testAppLog = [fixtureURL.URLByDeletingLastPathComponent URLByAppendingPathComponent:@"TestApplication.log"];
|
||||
[[NSData data] writeToURL:testAppLog atomically:YES];
|
||||
|
||||
NSTask *readTestApp = [self.class tailTaskWithPaths:[RACSequence return:testAppLog.path]];
|
||||
[readTestApp launch];
|
||||
|
||||
XCTAssertTrue([readTestApp isRunning], @"Could not start task %@ to read %@", readTestApp, testAppLog);
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
[readTestApp terminate];
|
||||
}];
|
||||
}
|
||||
|
||||
return fixtureURL;
|
||||
@@ -211,7 +243,7 @@ QuickConfigurationEnd
|
||||
}
|
||||
|
||||
- (NSURL *)createTestApplicationUpdate {
|
||||
NSURL *originalURL = [SQRLTestBundle() URLForResource:@"TestApplication 2.1" withExtension:@"app"];
|
||||
NSURL *originalURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication 2.1" withExtension:@"app"];
|
||||
XCTAssertNotNil(originalURL, @"Couldn't find TestApplication update in test bundle");
|
||||
|
||||
NSError *error = nil;
|
||||
@@ -230,7 +262,7 @@ QuickConfigurationEnd
|
||||
}
|
||||
|
||||
- (id)performWithTestApplicationRequirement:(id (^)(SecRequirementRef requirement))block {
|
||||
NSURL *bundleURL = [SQRLTestBundle() URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
NSURL *bundleURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
XCTAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
|
||||
SecStaticCodeRef staticCode = NULL;
|
||||
@@ -253,7 +285,7 @@ QuickConfigurationEnd
|
||||
}
|
||||
|
||||
- (SQRLCodeSignature *)testApplicationSignature {
|
||||
NSURL *bundleURL = [SQRLTestBundle() URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
NSURL *bundleURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication" withExtension:@"app"];
|
||||
XCTAssertNotNil(bundleURL, @"Couldn't find TestApplication.app in test bundle");
|
||||
|
||||
NSError *error = nil;
|
||||
@@ -264,7 +296,7 @@ QuickConfigurationEnd
|
||||
}
|
||||
|
||||
- (SQRLDirectoryManager *)shipItDirectoryManager {
|
||||
NSString *identifier = SQRLShipItLauncher.shipItJobLabel;
|
||||
NSString *identifier = SQRLShipItConnection.shipItJobLabel;
|
||||
SQRLDirectoryManager *manager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:identifier];
|
||||
XCTAssertNotNil(manager, @"Could not create directory manager for %@", identifier);
|
||||
|
||||
@@ -273,31 +305,31 @@ QuickConfigurationEnd
|
||||
|
||||
- (void)installWithRequest:(SQRLShipItRequest *)request remote:(BOOL)remote {
|
||||
if (remote) {
|
||||
expect(@([[request writeUsingURL:self.shipItDirectoryManager.shipItStateURL] waitUntilCompleted:NULL])).to(beTruthy());
|
||||
SQRLShipItConnection *connection = [[SQRLShipItConnection alloc] initWithRootPrivileges:NO];
|
||||
|
||||
__block NSError *error = nil;
|
||||
expect(@([[SQRLShipItLauncher launchPrivileged:NO] waitUntilCompleted:&error])).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect([[connection sendRequest:request] waitUntilCompleted:&error]).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
[self addCleanupBlock:^{
|
||||
// Remove ShipIt's launchd job so it doesn't relaunch itself.
|
||||
SMJobRemove(kSMDomainUserLaunchd, (__bridge CFStringRef)SQRLShipItLauncher.shipItJobLabel, NULL, true, NULL);
|
||||
SMJobRemove(kSMDomainUserLaunchd, (__bridge CFStringRef)SQRLShipItConnection.shipItJobLabel, NULL, true, NULL);
|
||||
|
||||
NSError *lookupError;
|
||||
NSURL *stateURL = [[self.shipItDirectoryManager shipItStateURL] firstOrDefault:nil success:NULL error:&lookupError];
|
||||
expect(stateURL).notTo(beNil());
|
||||
expect(lookupError).to(beNil());
|
||||
expect(stateURL).notTo.beNil();
|
||||
expect(lookupError).to.beNil();
|
||||
|
||||
[NSFileManager.defaultManager removeItemAtURL:stateURL error:NULL];
|
||||
}];
|
||||
} else {
|
||||
SQRLInstaller *installer = [[SQRLInstaller alloc] initWithApplicationIdentifier:self.shipItDirectoryManager.applicationIdentifier];
|
||||
expect(installer).notTo(beNil());
|
||||
expect(installer).notTo.beNil();
|
||||
|
||||
NSError *installedError = nil;
|
||||
BOOL installed = [[installer.installUpdateCommand execute:request] asynchronouslyWaitUntilCompleted:&installedError];
|
||||
expect(@(installed)).to(beTruthy());
|
||||
expect(installedError).to(beNil());
|
||||
expect(installed).to.beTruthy();
|
||||
expect(installedError).to.beNil();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,24 +344,20 @@ QuickConfigurationEnd
|
||||
createInvocation = [NSString stringWithFormat:@"hdiutil create '%@' -fs 'HFS+' -volname '%@' -format UDSP -size 10m -srcfolder '%@' -quiet", destinationURL.path, name, directoryURL.path];
|
||||
}
|
||||
|
||||
expect(@(system(createInvocation.UTF8String))).to(equal(@0));
|
||||
expect(system(createInvocation.UTF8String)).to.equal(0);
|
||||
|
||||
NSString *mountInvocation = [NSString stringWithFormat:@"hdiutil attach '%@.sparseimage' -noverify -noautofsck -readwrite -quiet", destinationURL.path];
|
||||
expect(@(system(mountInvocation.UTF8String))).to(equal(@0));
|
||||
expect(system(mountInvocation.UTF8String)).to.equal(0);
|
||||
|
||||
NSString *path = [NSString stringWithFormat:@"/Volumes/%@", name];
|
||||
[self addCleanupBlock:^{
|
||||
NSString *detachInvocation = [NSString stringWithFormat:@"hdiutil detach '%@' -force -quiet", path];
|
||||
expect(@(system(detachInvocation.UTF8String))).to(equal(@0));
|
||||
expect(system(detachInvocation.UTF8String)).to.equal(0);
|
||||
}];
|
||||
|
||||
return [NSURL fileURLWithPath:path isDirectory:YES];
|
||||
}
|
||||
|
||||
- (BOOL)isRunningOnTravis {
|
||||
return NSProcessInfo.processInfo.environment[@"TRAVIS"] != nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
@@ -0,0 +1,17 @@
|
||||
//
|
||||
// SQRLTestHelper.h
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Matt Diephouse on 7/7/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/// A test helper class that will run cleanup blocks after each test finishes.
|
||||
@interface SQRLTestHelper : NSObject
|
||||
|
||||
/// Adds a cleanup block that will run after the next test completes.
|
||||
+ (void)addCleanupBlock:(dispatch_block_t)block;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,42 @@
|
||||
//
|
||||
// SQRLTestHelper.m
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Matt Diephouse on 7/7/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SQRLTestHelper.h"
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
@implementation SQRLTestHelper
|
||||
|
||||
#pragma mark - Specta Methods
|
||||
|
||||
+ (void)afterEach {
|
||||
// Enumerate backwards, so later resources are cleaned up first.
|
||||
for (dispatch_block_t block in self.cleanupBlocks.reverseObjectEnumerator) {
|
||||
block();
|
||||
}
|
||||
[self.cleanupBlocks removeAllObjects];
|
||||
}
|
||||
|
||||
#pragma mark - Public Methods
|
||||
|
||||
+ (void)addCleanupBlock:(dispatch_block_t)block {
|
||||
[self.cleanupBlocks addObject:[block copy]];
|
||||
}
|
||||
|
||||
#pragma mark - Private Methods
|
||||
|
||||
+ (NSMutableArray *)cleanupBlocks {
|
||||
NSMutableArray *blocks = objc_getAssociatedObject(self, "sqrl_cleanupBlocks");
|
||||
if (blocks == nil) {
|
||||
blocks = [NSMutableArray array];
|
||||
objc_setAssociatedObject(self, "sqrl_cleanupBlocks", blocks, OBJC_ASSOCIATION_RETAIN);
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -6,27 +6,22 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
QuickSpecBegin(SQRLUpdateSpec)
|
||||
SpecBegin(SQRLUpdate)
|
||||
|
||||
it(@"should return nil when initialised without a url", ^{
|
||||
NSError *error = nil;
|
||||
SQRLUpdate *update = [[SQRLUpdate alloc] initWithDictionary:@{} error:&error];
|
||||
expect(update).to(beNil());
|
||||
expect(error.domain).to(equal(NSCocoaErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(NSKeyValueValidationError)));
|
||||
expect(update).to.beNil();
|
||||
expect(error.domain).to.equal(NSCocoaErrorDomain);
|
||||
expect(error.code).to.equal(NSKeyValueValidationError);
|
||||
});
|
||||
|
||||
it(@"should return nil when initialised with a url not in URL syntax", ^{
|
||||
NSError *error = nil;
|
||||
SQRLUpdate *update = [[SQRLUpdate alloc] initWithDictionary:@{ @"updateURL": [NSURL URLWithString:@"test"] } error:&error];
|
||||
expect(update).to(beNil());
|
||||
expect(error.domain).to(equal(NSCocoaErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(NSKeyValueValidationError)));
|
||||
expect(update).to.beNil();
|
||||
expect(error.domain).to.equal(NSCocoaErrorDomain);
|
||||
expect(error.code).to.equal(NSKeyValueValidationError);
|
||||
});
|
||||
|
||||
it(@"should validate release name and notes", ^{
|
||||
@@ -37,20 +32,20 @@ it(@"should validate release name and notes", ^{
|
||||
@"releaseNotes": [[NSObject alloc] init]
|
||||
} error:NULL];
|
||||
|
||||
expect(update).notTo(beNil());
|
||||
expect(update.updateURL).to(equal(updateURL));
|
||||
expect(update.releaseName).to(beNil());
|
||||
expect(update.releaseNotes).to(beNil());
|
||||
expect(update).notTo.beNil();
|
||||
expect(update.updateURL).to.equal(updateURL);
|
||||
expect(update.releaseName).to.beNil();
|
||||
expect(update.releaseNotes).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should parse Central style dates", ^{
|
||||
SQRLUpdate *update = [MTLJSONAdapter modelOfClass:SQRLUpdate.class fromJSONDictionary:@{ @"url": @"http://example.com/update", @"pub_date": @"Tue Sep 17 10:24:27 -0700 2013" } error:NULL];
|
||||
expect(update.releaseDate).to(equal([NSDate dateWithTimeIntervalSince1970:1379438667]));
|
||||
expect(update.releaseDate).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should parse ISO 8601 dates", ^{
|
||||
SQRLUpdate *update = [MTLJSONAdapter modelOfClass:SQRLUpdate.class fromJSONDictionary:@{ @"url": @"http://example.com/update", @"pub_date": @"2013-09-18T13:17:07+01:00" } error:NULL];
|
||||
expect(update.releaseDate).to(equal([NSDate dateWithTimeIntervalSince1970:1379506627]));
|
||||
expect(update.releaseDate).notTo.beNil();
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -6,44 +6,38 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "SQRLDirectoryManager.h"
|
||||
#import "SQRLZipArchiver.h"
|
||||
|
||||
#import "OHHTTPStubs/OHHTTPStubs.h"
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
#import "SQRLTestUpdate.h"
|
||||
#import "OHHTTPStubs/OHHTTPStubs.h"
|
||||
#import "TestAppConstants.h"
|
||||
|
||||
QuickSpecBegin(SQRLUpdaterSpec)
|
||||
SpecBegin(SQRLUpdater)
|
||||
|
||||
__block NSURL *JSONURL;
|
||||
|
||||
void (^writeUpdate)(SQRLUpdate *) = ^(SQRLUpdate *update) {
|
||||
NSDictionary *updateInfo = [MTLJSONAdapter JSONDictionaryFromModel:update];
|
||||
expect(updateInfo).notTo(beNil());
|
||||
expect(updateInfo).notTo.beNil();
|
||||
|
||||
NSError *error = nil;
|
||||
NSData *JSON = [NSJSONSerialization dataWithJSONObject:updateInfo options:NSJSONWritingPrettyPrinted error:&error];
|
||||
expect(JSON).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(JSON).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
BOOL success = [JSON writeToURL:JSONURL options:NSDataWritingAtomic error:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
};
|
||||
|
||||
NSURL * (^zipUpdate)(NSURL *) = ^(NSURL *updateURL) {
|
||||
NSURL *zipFolderURL = [NSFileManager.defaultManager URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:self.temporaryDirectoryURL create:YES error:NULL];
|
||||
expect(zipFolderURL).notTo(beNil());
|
||||
expect(zipFolderURL).notTo.beNil();
|
||||
|
||||
NSURL *zippedUpdateURL = [[zipFolderURL URLByAppendingPathComponent:updateURL.lastPathComponent] URLByAppendingPathExtension:@"zip"];
|
||||
BOOL success = [[SQRLZipArchiver createZipArchiveAtURL:zippedUpdateURL fromDirectoryAtURL:updateURL] asynchronouslyWaitUntilCompleted:NULL];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(success).to.beTruthy();
|
||||
|
||||
return zippedUpdateURL;
|
||||
};
|
||||
@@ -61,34 +55,30 @@ beforeEach(^{
|
||||
|
||||
describe(@"updating", ^{
|
||||
__block NSURL *updateURL;
|
||||
|
||||
|
||||
beforeEach(^{
|
||||
updateURL = [self createTestApplicationUpdate];
|
||||
});
|
||||
|
||||
it(@"should use the application's bundled version of Squirrel and update in-place", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSError *error = nil;
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:&error];
|
||||
expect(update).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(update).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(app.terminated).will.beTruthy();
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
it(@"should not install a corrupt update", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSURL *codeSignatureURL = [updateURL URLByAppendingPathComponent:@"Contents/_CodeSignature"];
|
||||
expect(@([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager removeItemAtURL:codeSignatureURL error:NULL]).to.beTruthy();
|
||||
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@@ -98,16 +88,14 @@ describe(@"updating", ^{
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(app.terminated).will.beTruthy();
|
||||
|
||||
// Give the update some time to finish installing.
|
||||
[NSThread sleepForTimeInterval:0.2];
|
||||
expect(self.testApplicationBundleVersion).to(equal(SQRLTestApplicationOriginalShortVersionString));
|
||||
expect(self.testApplicationBundleVersion).to.equal(SQRLTestApplicationOriginalShortVersionString);
|
||||
});
|
||||
|
||||
it(@"should update to the most recently enqueued job", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(self.testApplicationURL)
|
||||
} error:NULL];
|
||||
@@ -131,13 +119,11 @@ describe(@"updating", ^{
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
expect(app.terminated).will.beTruthy();
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
it(@"should use the application's bundled version of Squirrel and update in-place after a significant delay", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
@@ -145,22 +131,24 @@ describe(@"updating", ^{
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSTimeInterval delay = 15;
|
||||
NSTimeInterval delay = 30;
|
||||
NSRunningApplication *app = launchWithEnvironment(@{ @"SQRLUpdateDelay": [NSString stringWithFormat:@"%f", delay] });
|
||||
|
||||
expect(@(app.terminated)).withTimeout(delay + SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
Expecta.asynchronousTestTimeout = delay + 3;
|
||||
expect(app.terminated).will.beTruthy();
|
||||
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
});
|
||||
|
||||
describe(@"cleaning up", ^{
|
||||
__block NSURL *appSupportURL;
|
||||
__block RACSignal *updateDirectoryURLs;
|
||||
|
||||
|
||||
beforeEach(^{
|
||||
SQRLDirectoryManager *directoryManager = [[SQRLDirectoryManager alloc] initWithApplicationIdentifier:@"com.github.Squirrel.TestApplication.ShipIt"];
|
||||
|
||||
appSupportURL = [[directoryManager storageURL] first];
|
||||
expect(appSupportURL).notTo(beNil());
|
||||
appSupportURL = [[directoryManager applicationSupportURL] first];
|
||||
expect(appSupportURL).notTo.beNil();
|
||||
|
||||
updateDirectoryURLs = [[RACSignal
|
||||
defer:^{
|
||||
@@ -175,25 +163,22 @@ describe(@"updating", ^{
|
||||
});
|
||||
|
||||
it(@"should remove downloaded archives after updating", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSError *error = nil;
|
||||
SQRLTestUpdate *update = [SQRLTestUpdate modelWithDictionary:@{
|
||||
@"updateURL": zipUpdate(updateURL),
|
||||
@"final": @YES
|
||||
} error:&error];
|
||||
|
||||
expect(update).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(update).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
NSRunningApplication *app = launchWithEnvironment(@{ @"SQRLUpdateRequestCount": @2 });
|
||||
expect([updateDirectoryURLs toArray]).toEventuallyNot(equal(@[]));
|
||||
expect(@(app.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(self.testApplicationBundleVersion).toEventually(equal(SQRLTestApplicationUpdatedShortVersionString));
|
||||
NSRunningApplication *app = launchWithEnvironment(nil);
|
||||
expect(app.terminated).will.beTruthy();
|
||||
expect(self.testApplicationBundleVersion).will.equal(SQRLTestApplicationUpdatedShortVersionString);
|
||||
|
||||
expect([updateDirectoryURLs toArray]).toEventually(equal(@[]));
|
||||
expect([updateDirectoryURLs toArray]).will.equal(@[]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -202,7 +187,7 @@ describe(@"response handling", ^{
|
||||
__block NSURLRequest *localRequest = nil;
|
||||
__block SQRLUpdater *updater = nil;
|
||||
|
||||
beforeEach(^{
|
||||
before(^{
|
||||
localRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"fake://host/path"]];
|
||||
updater = [[SQRLUpdater alloc] initWithUpdateRequest:localRequest];
|
||||
});
|
||||
@@ -219,9 +204,9 @@ describe(@"response handling", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL result = [[updater.checkForUpdatesCommand execute:nil] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(result)).to(beFalsy());
|
||||
expect(error.domain).to(equal(SQRLUpdaterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLUpdaterErrorInvalidServerResponse)));
|
||||
expect(result).to.beFalsy();
|
||||
expect(error.domain).to.equal(SQRLUpdaterErrorDomain);
|
||||
expect(error.code).to.equal(SQRLUpdaterErrorInvalidServerResponse);
|
||||
});
|
||||
|
||||
it(@"should return an error for non JSON data", ^{
|
||||
@@ -236,9 +221,9 @@ describe(@"response handling", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL result = [[updater.checkForUpdatesCommand execute:nil] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(result)).to(beFalsy());
|
||||
expect(error.domain).to(equal(SQRLUpdaterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLUpdaterErrorInvalidServerBody)));
|
||||
expect(result).to.beFalsy();
|
||||
expect(error.domain).to.equal(SQRLUpdaterErrorDomain);
|
||||
expect(error.code).to.equal(SQRLUpdaterErrorInvalidServerBody);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -253,8 +238,6 @@ static RACSignal * (^stateNotificationListener)(void) = ^ {
|
||||
|
||||
describe(@"state", ^{
|
||||
it(@"should transition through idle, checking and idle, when there is no update", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSMutableArray *states = [NSMutableArray array];
|
||||
[stateNotificationListener() subscribeNext:^(NSNumber *state) {
|
||||
[states addObject:state];
|
||||
@@ -267,14 +250,12 @@ describe(@"state", ^{
|
||||
@(SQRLUpdaterStateCheckingForUpdate),
|
||||
@(SQRLUpdaterStateIdle),
|
||||
];
|
||||
expect(states).toEventually(equal(expectedStates));
|
||||
expect(states).will.equal(expectedStates);
|
||||
|
||||
expect(@(testApplication.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(testApplication.terminated).will.beTruthy();
|
||||
});
|
||||
|
||||
it(@"should transition through idle, checking, downloading and awaiting relaunch, when there is an update", ^{
|
||||
SKIP_IF_RUNNING_ON_TRAVIS
|
||||
|
||||
NSMutableArray *states = [NSMutableArray array];
|
||||
[stateNotificationListener() subscribeNext:^(NSNumber *state) {
|
||||
[states addObject:state];
|
||||
@@ -285,8 +266,8 @@ describe(@"state", ^{
|
||||
@"updateURL": zipUpdate([self createTestApplicationUpdate]),
|
||||
@"final": @YES,
|
||||
} error:&error];
|
||||
expect(update).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(update).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
writeUpdate(update);
|
||||
|
||||
@@ -298,10 +279,10 @@ describe(@"state", ^{
|
||||
@(SQRLUpdaterStateDownloadingUpdate),
|
||||
@(SQRLUpdaterStateAwaitingRelaunch),
|
||||
];
|
||||
expect(states).withTimeout(SQRLLongTimeout).toEventually(equal(expectedStates));
|
||||
expect(states).will.equal(expectedStates);
|
||||
|
||||
expect(@(testApplication.terminated)).withTimeout(SQRLLongTimeout).toEventually(beTruthy());
|
||||
expect(testApplication.terminated).will.beTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -6,44 +6,38 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#import "QuickSpec+SQRLFixtures.h"
|
||||
#import "SQRLCodeSignature.h"
|
||||
#import "SQRLZipArchiver.h"
|
||||
|
||||
QuickSpecBegin(SQRLZipArchiverSpec)
|
||||
SpecBegin(SQRLZipArchiver)
|
||||
|
||||
it(@"should extract a zip archive created by the Finder", ^{
|
||||
NSURL *zipURL = [[NSBundle bundleForClass:self.class] URLForResource:@"TestApplication.app" withExtension:@"zip"];
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[SQRLZipArchiver unzipArchiveAtURL:zipURL intoDirectoryAtURL:self.temporaryDirectoryURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
NSURL *extractedAppURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication 2.1.app"];
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path]).to.beTruthy();
|
||||
|
||||
success = [[self.testApplicationSignature verifyBundleAtURL:extractedAppURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should fail to extract a nonexistent zip archive", ^{
|
||||
NSError *error = nil;
|
||||
BOOL success = [[SQRLZipArchiver unzipArchiveAtURL:[self.temporaryDirectoryURL URLByAppendingPathComponent:@"foo.zip"] intoDirectoryAtURL:self.temporaryDirectoryURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
NSLog(@"%@", error);
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(SQRLZipArchiverErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(SQRLZipArchiverShellTaskFailed)));
|
||||
expect(error.userInfo[SQRLZipArchiverExitCodeErrorKey]).notTo(equal(0));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(SQRLZipArchiverErrorDomain);
|
||||
expect(error.code).to.equal(SQRLZipArchiverShellTaskFailed);
|
||||
expect(error.userInfo[SQRLZipArchiverExitCodeErrorKey]).notTo.equal(0);
|
||||
});
|
||||
|
||||
it(@"should create a zip archive readable by itself", ^{
|
||||
@@ -51,21 +45,21 @@ it(@"should create a zip archive readable by itself", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [[SQRLZipArchiver createZipArchiveAtURL:zipURL fromDirectoryAtURL:self.testApplicationURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:zipURL.path])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:zipURL.path]).to.beTruthy();
|
||||
|
||||
success = [[SQRLZipArchiver unzipArchiveAtURL:zipURL intoDirectoryAtURL:self.temporaryDirectoryURL] asynchronouslyWaitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
NSURL *extractedAppURL = [self.temporaryDirectoryURL URLByAppendingPathComponent:@"TestApplication.app"];
|
||||
expect(@([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path])).to(beTruthy());
|
||||
expect([NSFileManager.defaultManager fileExistsAtPath:extractedAppURL.path]).to.beTruthy();
|
||||
|
||||
success = [[self.testApplicationSignature verifyBundleAtURL:extractedAppURL] waitUntilCompleted:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(error).to(beNil());
|
||||
expect(success).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<string>com.github.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// SquirrelTests-Prefix.pch
|
||||
// Squirrel
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-07-21.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <XCTest/XCTest.h>
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <ReactiveCocoa/ReactiveCocoa.h>
|
||||
#import <ReactiveCocoa/EXTScope.h>
|
||||
#import <Squirrel/Squirrel.h>
|
||||
|
||||
#define SPT_SUBCLASS SQRLTestCase
|
||||
#import "Specta.h"
|
||||
|
||||
#define EXP_SHORTHAND
|
||||
#import "Expecta.h"
|
||||
|
||||
// Expecta #defines startWith as beginWith, which messes up -startWith: :-(
|
||||
#undef startWith
|
||||
|
||||
#import "SQRLTestCase.h"
|
||||
#endif
|
||||
@@ -1,19 +0,0 @@
|
||||
//
|
||||
// SwiftSpec.swift
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2014-10-14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Nimble
|
||||
import Quick
|
||||
|
||||
// Without this, the Swift stdlib won't be linked into the test target (even if
|
||||
// “Embedded Content Contains Swift Code” is enabled).
|
||||
class SwiftSpec: QuickSpec {
|
||||
override func spec() {
|
||||
expect(true).to(beTruthy())
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
Versions/Current/Headers
|
||||
@@ -1 +0,0 @@
|
||||
Versions/Current/Mantle
|
||||
@@ -1 +0,0 @@
|
||||
Versions/Current/Modules
|
||||
@@ -1 +0,0 @@
|
||||
Versions/Current/Resources
|
||||
-172
@@ -1,172 +0,0 @@
|
||||
//
|
||||
// MTLJSONAdapter.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-02-12.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class MTLModel;
|
||||
|
||||
// A MTLModel object that supports being parsed from and serialized to JSON.
|
||||
@protocol MTLJSONSerializing
|
||||
@required
|
||||
|
||||
// Specifies how to map property keys to different key paths in JSON.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Any property keys not present in the dictionary are assumed to match the JSON
|
||||
// key that should be used. Any keys associated with NSNull will not participate
|
||||
// in JSON serialization.
|
||||
//
|
||||
// Returns a dictionary mapping property keys to JSON key paths (as strings) or
|
||||
// NSNull values.
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey;
|
||||
|
||||
@optional
|
||||
|
||||
// Specifies how to convert a JSON value to the given property key. If
|
||||
// reversible, the transformer will also be used to convert the property value
|
||||
// back to JSON.
|
||||
//
|
||||
// If the receiver implements a `+<key>JSONTransformer` method, MTLJSONAdapter
|
||||
// will use the result of that method instead.
|
||||
//
|
||||
// Returns a value transformer, or nil if no transformation should be performed.
|
||||
+ (NSValueTransformer *)JSONTransformerForKey:(NSString *)key;
|
||||
|
||||
// Overridden to parse the receiver as a different class, based on information
|
||||
// in the provided dictionary.
|
||||
//
|
||||
// This is mostly useful for class clusters, where the abstract base class would
|
||||
// be passed into -[MTLJSONAdapter initWithJSONDictionary:modelClass:], but
|
||||
// a subclass should be instantiated instead.
|
||||
//
|
||||
// JSONDictionary - The JSON dictionary that will be parsed.
|
||||
//
|
||||
// Returns the class that should be parsed (which may be the receiver), or nil
|
||||
// to abort parsing (e.g., if the data is invalid).
|
||||
+ (Class)classForParsingJSONDictionary:(NSDictionary *)JSONDictionary;
|
||||
|
||||
@end
|
||||
|
||||
// The domain for errors originating from MTLJSONAdapter.
|
||||
extern NSString * const MTLJSONAdapterErrorDomain;
|
||||
|
||||
// +classForParsingJSONDictionary: returned nil for the given dictionary.
|
||||
extern const NSInteger MTLJSONAdapterErrorNoClassFound;
|
||||
|
||||
// The provided JSONDictionary is not valid.
|
||||
extern const NSInteger MTLJSONAdapterErrorInvalidJSONDictionary;
|
||||
|
||||
// The model's implementation of +JSONKeyPathsByPropertyKey included a key which
|
||||
// does not actually exist in +propertyKeys.
|
||||
extern const NSInteger MTLJSONAdapterErrorInvalidJSONMapping;
|
||||
|
||||
// Converts a MTLModel object to and from a JSON dictionary.
|
||||
@interface MTLJSONAdapter : NSObject
|
||||
|
||||
// The model object that the receiver was initialized with, or that the receiver
|
||||
// parsed from a JSON dictionary.
|
||||
@property (nonatomic, strong, readonly) MTLModel<MTLJSONSerializing> *model;
|
||||
|
||||
// Attempts to parse a JSON dictionary into a model object.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON.
|
||||
// This class must conform to <MTLJSONSerializing>. This
|
||||
// argument must not be nil.
|
||||
// JSONDictionary - A dictionary representing JSON data. This should match the
|
||||
// format returned by NSJSONSerialization. If this argument is
|
||||
// nil, the method returns nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// parsing or initializing an instance of `modelClass`.
|
||||
//
|
||||
// Returns an instance of `modelClass` upon success, or nil if a parsing error
|
||||
// occurred.
|
||||
+ (id)modelOfClass:(Class)modelClass fromJSONDictionary:(NSDictionary *)JSONDictionary error:(NSError **)error;
|
||||
|
||||
// Attempts to parse an array of JSON dictionary objects into a model objects
|
||||
// of a specific class.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON. This
|
||||
// class must conform to <MTLJSONSerializing>. This argument must
|
||||
// not be nil.
|
||||
// JSONArray - A array of dictionaries representing JSON data. This should
|
||||
// match the format returned by NSJSONSerialization. If this
|
||||
// argument is nil, the method returns nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// parsing or initializing an any of the instances of
|
||||
// `modelClass`.
|
||||
//
|
||||
// Returns an array of `modelClass` instances upon success, or nil if a parsing
|
||||
// error occurred.
|
||||
+ (NSArray *)modelsOfClass:(Class)modelClass fromJSONArray:(NSArray *)JSONArray error:(NSError **)error;
|
||||
|
||||
// Converts a model into a JSON representation.
|
||||
//
|
||||
// model - The model to use for JSON serialization. This argument must not be
|
||||
// nil.
|
||||
//
|
||||
// Returns a JSON dictionary, or nil if a serialization error occurred.
|
||||
+ (NSDictionary *)JSONDictionaryFromModel:(MTLModel<MTLJSONSerializing> *)model;
|
||||
|
||||
// Converts a array of models into a JSON representation.
|
||||
//
|
||||
// models - The array of models to use for JSON serialization. This argument
|
||||
// must not be nil.
|
||||
//
|
||||
// Returns a JSON array, or nil if a serialization error occurred for any
|
||||
// model.
|
||||
+ (NSArray *)JSONArrayFromModels:(NSArray *)models;
|
||||
|
||||
// Initializes the receiver by attempting to parse a JSON dictionary into
|
||||
// a model object.
|
||||
//
|
||||
// JSONDictionary - A dictionary representing JSON data. This should match the
|
||||
// format returned by NSJSONSerialization. If this argument is
|
||||
// nil, the method returns nil and an error with code
|
||||
// MTLJSONAdapterErrorInvalidJSONDictionary.
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON.
|
||||
// This class must conform to <MTLJSONSerializing>. This
|
||||
// argument must not be nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// parsing or initializing an instance of `modelClass`.
|
||||
//
|
||||
// Returns an initialized adapter upon success, or nil if a parsing error
|
||||
// occurred.
|
||||
- (id)initWithJSONDictionary:(NSDictionary *)JSONDictionary modelClass:(Class)modelClass error:(NSError **)error;
|
||||
|
||||
// Initializes the receiver with an existing model.
|
||||
//
|
||||
// model - The model to use for JSON serialization. This argument must not be
|
||||
// nil.
|
||||
- (id)initWithModel:(MTLModel<MTLJSONSerializing> *)model;
|
||||
|
||||
// Serializes the receiver's `model` into JSON.
|
||||
//
|
||||
// Returns a JSON dictionary, or nil if a serialization error occurred.
|
||||
- (NSDictionary *)JSONDictionary;
|
||||
|
||||
// Looks up the JSON key path in the model's +propertyKeys.
|
||||
//
|
||||
// Subclasses may override this method to customize the adapter's seralizing
|
||||
// behavior. You should not call this method directly.
|
||||
//
|
||||
// key - The property key to retrieve the corresponding JSON key path for. This
|
||||
// argument must not be nil.
|
||||
//
|
||||
// Returns a key path to use, or nil to omit the property from JSON.
|
||||
- (NSString *)JSONKeyPathForPropertyKey:(NSString *)key;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLJSONAdapter (Deprecated)
|
||||
|
||||
+ (id)modelOfClass:(Class)modelClass fromJSONDictionary:(NSDictionary *)JSONDictionary __attribute__((deprecated("Replaced by +modelOfClass:fromJSONDictionary:error:")));
|
||||
- (id)initWithJSONDictionary:(NSDictionary *)JSONDictionary modelClass:(Class)modelClass __attribute__((deprecated("Replaced by -initWithJSONDictionary:modelClass:error:")));
|
||||
|
||||
@end
|
||||
-215
@@ -1,215 +0,0 @@
|
||||
//
|
||||
// MTLManagedObjectAdapter.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-03-29.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <CoreData/CoreData.h>
|
||||
|
||||
@class MTLModel;
|
||||
|
||||
// A MTLModel object that supports being serialized to and from Core Data as an
|
||||
// NSManagedObject.
|
||||
@protocol MTLManagedObjectSerializing
|
||||
@required
|
||||
|
||||
// The name of the Core Data entity that the receiver serializes to and
|
||||
// deserializes from.
|
||||
//
|
||||
// This method must not return nil.
|
||||
+ (NSString *)managedObjectEntityName;
|
||||
|
||||
// Specifies how to map property keys to different keys on the receiver's
|
||||
// +managedObjectEntity.
|
||||
//
|
||||
// Entity attributes will be mapped to and from the receiver's properties using
|
||||
// +entityAttributeTransformerForKey:. Entity relationships will be mapped to
|
||||
// and from MTLModel objects using +relationshipModelClassesByPropertyKey.
|
||||
// Fetched properties are not supported.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Any property keys not present in the dictionary are assumed to match the
|
||||
// entity key that should be used. Any keys associated with NSNull will not
|
||||
// participate in managed object serialization.
|
||||
//
|
||||
// Returns a dictionary mapping property keys to entity keys (as strings) or
|
||||
// NSNull values.
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey;
|
||||
|
||||
@optional
|
||||
|
||||
// Specifies a set of property keys used by the adapter to check for an already
|
||||
// existing managed object when converting the MTLModel to its related
|
||||
// NSManagedObject.
|
||||
//
|
||||
// The adapter will first map any keys provided by this method to the correct
|
||||
// keys in managedObjectKeysByPropertyKey.
|
||||
//
|
||||
// The adapter will then perform a fetch request in the provided context for a
|
||||
// managed object that matches the MTLModel's managedObjectEntityName and has
|
||||
// equal values set for the property keys on the MTLModel.
|
||||
//
|
||||
// The managed object returned by the fetch request will then be set with all
|
||||
// values from the MTLModel that the managed object is being converted from.
|
||||
//
|
||||
// If a property value of our MTLModel is yet another MTLModel which needs to be
|
||||
// converted to a managed object, the class for that MTLModel can also implement
|
||||
// this method to perform its own uniqing.
|
||||
//
|
||||
// For example:
|
||||
// 1. An MTLModel subclass has id_number = 10.
|
||||
// 2. An NSManagedObject accessible to the adapter's context has idnumber = 10.
|
||||
// 3. managedObjectKeysByPropertyKey returns @{@"id_number" : @"idnumber"}
|
||||
// 4. propertyKeysForManagedObjectUniquing returns
|
||||
// [NSSet setWithObject:@"id_number"];
|
||||
// 5. Then our fetch request may return this managed object (or another managed
|
||||
// object with idnumber = 10).
|
||||
//
|
||||
// NOTE: If multiple managed objects follow the same uniquing criteria only one
|
||||
// of them will be set with our MTLModel's values.
|
||||
+ (NSSet *)propertyKeysForManagedObjectUniquing;
|
||||
|
||||
// Specifies how to convert the given property key to a managed object
|
||||
// attribute. If reversible, the transformer will also be used to convert the
|
||||
// managed object attribute back to the property.
|
||||
//
|
||||
// If the receiver implements a `+<key>EntityAttributeTransformer` method,
|
||||
// MTLManagedObjectAdapter will use the result of that method instead.
|
||||
//
|
||||
// Returns a value transformer, or nil if no transformation should be performed.
|
||||
+ (NSValueTransformer *)entityAttributeTransformerForKey:(NSString *)key;
|
||||
|
||||
// Specifies the MTLModel subclasses that should be deserialized to the
|
||||
// receiver's property keys when a property key corresponds to an entity
|
||||
// relationship.
|
||||
//
|
||||
// In other words, the dictionary returned by this method is used to decode
|
||||
// managed object relationships into MTLModels (or NSArrays or NSSets thereof)
|
||||
// set on the receiver.
|
||||
//
|
||||
// If a property key is omitted from the returned dictionary, but present in
|
||||
// +managedObjectKeysByPropertyKey, and the receiver's +managedObjectEntity has
|
||||
// a relationship at the corresponding key, an exception will be thrown during
|
||||
// deserialization.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Returns a dictionary mapping property keys to the Class objects that should
|
||||
// be used.
|
||||
+ (NSDictionary *)relationshipModelClassesByPropertyKey;
|
||||
|
||||
// Overridden to deserialize a different class instead of the receiver, based on
|
||||
// information in the provided object.
|
||||
//
|
||||
// This is mostly useful for class clusters, where the abstract base class would
|
||||
// be passed into +[MTLManagedObjectAdapter
|
||||
// modelOfClass:fromManagedObject:error:], but a subclass should be instantiated
|
||||
// instead.
|
||||
//
|
||||
// managedObject - The object that will be deserialized.
|
||||
//
|
||||
// Returns the class that should be instantiated (which may be the receiver), or
|
||||
// nil to abort parsing (e.g., if the data is invalid).
|
||||
+ (Class)classForDeserializingManagedObject:(NSManagedObject *)managedObject;
|
||||
|
||||
// Overriden when merging the value of the given key on the receiver with the
|
||||
// value of the same key from the given `NSManagedObject` requires custom
|
||||
// handling.
|
||||
//
|
||||
// By default, this method is not implemented, and precedence will be given to
|
||||
// the value of the receiving model implicitly.
|
||||
//
|
||||
// When implemented, this method is called when an existing `NSManagedObject`
|
||||
// is found for the receiving model, before updating the `NSManagedObject`'s
|
||||
// properties.
|
||||
//
|
||||
// When implementing, you should use `+managedObjectKeysByPropertyKey` to map
|
||||
// the given `key` to the appropriate `NSManagedObject` property.
|
||||
- (void)mergeValueForKey:(NSString *)key fromManagedObject:(NSManagedObject *)managedObject;
|
||||
|
||||
// Overriden when merging values on the receiver with the given
|
||||
// `NSManagedObject` requires custom handling.
|
||||
//
|
||||
// By default, this method is not implemented, and precedence will be given to
|
||||
// the values of the receiving model implicitly.
|
||||
//
|
||||
// When implemented, this method is called when an existing `NSManagedObject`
|
||||
// is found for the receiving model, before updating the `NSManagedObject`'s
|
||||
// properties.
|
||||
//
|
||||
// When implementing, you should use `+managedObjectKeysByPropertyKey` to map
|
||||
// the given `key` to the appropriate `NSManagedObject` property.
|
||||
//
|
||||
// If you have also implemented `mergeValueForKey:fromManagedObject:` you have
|
||||
// to make sure to call `mergeValueForKey:fromManagedObject:` from this method
|
||||
// when appropriate.
|
||||
- (void)mergeValuesForKeysFromManagedObject:(NSManagedObject *)managedObject;
|
||||
|
||||
@end
|
||||
|
||||
// The domain for errors originating from MTLManagedObjectAdapter.
|
||||
extern NSString * const MTLManagedObjectAdapterErrorDomain;
|
||||
|
||||
// +classForDeserializingManagedObject: returned nil for the given object.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorNoClassFound;
|
||||
|
||||
// An NSManagedObject failed to initialize.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorInitializationFailed;
|
||||
|
||||
// The managed object key specified by +managedObjectKeysByPropertyKey does not
|
||||
// exist in the NSEntityDescription.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorInvalidManagedObjectKey;
|
||||
|
||||
// The managed object property specified has a type that isn't supported by
|
||||
// MTLManagedObjectAdapter.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorUnsupportedManagedObjectPropertyType;
|
||||
|
||||
// The fetch request to find an existing managed object based on
|
||||
// `+propertyKeysForManagedObjectUniquing` failed.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorUniqueFetchRequestFailed;
|
||||
|
||||
// A MTLModel property cannot be serialized to or deserialized from an
|
||||
// NSManagedObject relationship.
|
||||
//
|
||||
// For a to-one relationship, this means that the property does not contain
|
||||
// a MTLModel, or the MTLModel does not conform to <MTLManagedObjectSerializing>.
|
||||
//
|
||||
// For a to-many relationship, this means that the property does not contain an
|
||||
// NSArray or NSSet of MTLModel<MTLManagedObjectSerializing> instances.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorUnsupportedRelationshipClass;
|
||||
|
||||
// The model's implementation of +managedObjectKeysByPropertyKey included a key
|
||||
// which does not actually exist in +propertyKeys.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorInvalidManagedObjectMapping;
|
||||
|
||||
// Converts a MTLModel object to and from an NSManagedObject.
|
||||
@interface MTLManagedObjectAdapter : NSObject
|
||||
|
||||
// Attempts to deserialize an NSManagedObject into a MTLModel object.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to return. This class must conform to
|
||||
// <MTLManagedObjectSerializing>. This argument must not be nil.
|
||||
// managedObject - The managed object to deserialize. If this argument is nil,
|
||||
// the method returns nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// deserialization or initializing an instance of `modelClass`.
|
||||
//
|
||||
// Returns an instance of `modelClass` upon success, or nil if an error
|
||||
// occurred.
|
||||
+ (id)modelOfClass:(Class)modelClass fromManagedObject:(NSManagedObject *)managedObject error:(NSError **)error;
|
||||
|
||||
// Serializes a MTLModel into an NSManagedObject.
|
||||
//
|
||||
// model - The model object to serialize. This argument must not be nil.
|
||||
// context - The context into which to insert the created managed object. This
|
||||
// argument must not be nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// serialization or insertion.
|
||||
+ (id)managedObjectFromModel:(MTLModel<MTLManagedObjectSerializing> *)model insertingIntoContext:(NSManagedObjectContext *)context error:(NSError **)error;
|
||||
|
||||
@end
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
//
|
||||
// MTLModel+NSCoding.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-02-12.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLModel.h"
|
||||
|
||||
// Defines how a MTLModel property key should be encoded into an archive.
|
||||
//
|
||||
// MTLModelEncodingBehaviorExcluded - The property should never be encoded.
|
||||
// MTLModelEncodingBehaviorUnconditional - The property should always be
|
||||
// encoded.
|
||||
// MTLModelEncodingBehaviorConditional - The object should be encoded only
|
||||
// if unconditionally encoded elsewhere.
|
||||
// This should only be used for object
|
||||
// properties.
|
||||
typedef enum : NSUInteger {
|
||||
MTLModelEncodingBehaviorExcluded = 0,
|
||||
MTLModelEncodingBehaviorUnconditional,
|
||||
MTLModelEncodingBehaviorConditional,
|
||||
} MTLModelEncodingBehavior;
|
||||
|
||||
// Implements default archiving and unarchiving behaviors for MTLModel.
|
||||
@interface MTLModel (NSCoding) <NSCoding>
|
||||
|
||||
// Initializes the receiver from an archive.
|
||||
//
|
||||
// This will decode the original +modelVersion of the archived object, then
|
||||
// invoke -decodeValueForKey:withCoder:modelVersion: for each of the receiver's
|
||||
// +propertyKeys.
|
||||
//
|
||||
// Returns an initialized model object, or nil if a decoding error occurred.
|
||||
- (id)initWithCoder:(NSCoder *)coder;
|
||||
|
||||
// Archives the receiver using the given coder.
|
||||
//
|
||||
// This will encode the receiver's +modelVersion, then the receiver's properties
|
||||
// according to the behaviors specified in +encodingBehaviorsByPropertyKey.
|
||||
- (void)encodeWithCoder:(NSCoder *)coder;
|
||||
|
||||
// Determines how the +propertyKeys of the class are encoded into an archive.
|
||||
// The values of this dictionary should be boxed MTLModelEncodingBehavior
|
||||
// values.
|
||||
//
|
||||
// Any keys not present in the dictionary will be excluded from the archive.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Returns a dictionary mapping the receiver's +propertyKeys to default encoding
|
||||
// behaviors. If a property is an object with `weak` semantics, the default
|
||||
// behavior is MTLModelEncodingBehaviorConditional; otherwise, the default is
|
||||
// MTLModelEncodingBehaviorUnconditional.
|
||||
+ (NSDictionary *)encodingBehaviorsByPropertyKey;
|
||||
|
||||
// Determines the classes that are allowed to be decoded for each of the
|
||||
// receiver's properties when using <NSSecureCoding>. The values of this
|
||||
// dictionary should be NSArrays of Class objects.
|
||||
//
|
||||
// If any encodable keys (as determined by +encodingBehaviorsByPropertyKey) are
|
||||
// not present in the dictionary, an exception will be thrown during secure
|
||||
// encoding or decoding.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Returns a dictionary mapping the receiver's encodable keys (as determined by
|
||||
// +encodingBehaviorsByPropertyKey) to default allowed classes, based on the
|
||||
// type that each property is declared as. If type of an encodable property
|
||||
// cannot be determined (e.g., it is declared as `id`), it will be omitted from
|
||||
// the dictionary, and subclasses must provide a valid value to prevent an
|
||||
// exception being thrown during encoding/decoding.
|
||||
+ (NSDictionary *)allowedSecureCodingClassesByPropertyKey;
|
||||
|
||||
// Decodes the value of the given property key from an archive.
|
||||
//
|
||||
// By default, this method looks for a `-decode<Key>WithCoder:modelVersion:`
|
||||
// method on the receiver, and invokes it if found.
|
||||
//
|
||||
// If the custom method is not implemented and `coder` does not require secure
|
||||
// coding, `-[NSCoder decodeObjectForKey:]` will be invoked with the given
|
||||
// `key`.
|
||||
//
|
||||
// If the custom method is not implemented and `coder` requires secure coding,
|
||||
// `-[NSCoder decodeObjectOfClasses:forKey:]` will be invoked with the
|
||||
// information from +allowedSecureCodingClassesByPropertyKey and the given `key`. The
|
||||
// receiver must conform to <NSSecureCoding> for this to work correctly.
|
||||
//
|
||||
// key - The property key to decode the value for. This argument cannot
|
||||
// be nil.
|
||||
// coder - The NSCoder representing the archive being decoded. This
|
||||
// argument cannot be nil.
|
||||
// modelVersion - The version of the original model object that was encoded.
|
||||
//
|
||||
// Returns the decoded and boxed value, or nil if the key was not present.
|
||||
- (id)decodeValueForKey:(NSString *)key withCoder:(NSCoder *)coder modelVersion:(NSUInteger)modelVersion;
|
||||
|
||||
// The version of this MTLModel subclass.
|
||||
//
|
||||
// This version number is saved in archives so that later model changes can be
|
||||
// made backwards-compatible with old versions.
|
||||
//
|
||||
// Subclasses should override this method to return a higher version number
|
||||
// whenever a breaking change is made to the model.
|
||||
//
|
||||
// Returns 0.
|
||||
+ (NSUInteger)modelVersion;
|
||||
|
||||
@end
|
||||
|
||||
// This method must be overridden to support archives created by older versions
|
||||
// of Mantle (before the `MTLModel+NSCoding` interface existed).
|
||||
@interface MTLModel (OldArchiveSupport)
|
||||
|
||||
// Converts an archived external representation to a dictionary suitable for
|
||||
// passing to -initWithDictionary:.
|
||||
//
|
||||
// externalRepresentation - The decoded external representation of the receiver.
|
||||
// fromVersion - The model version at the time the external
|
||||
// representation was encoded.
|
||||
//
|
||||
// Returns nil by default, indicating that conversion failed.
|
||||
+ (NSDictionary *)dictionaryValueFromArchivedExternalRepresentation:(NSDictionary *)externalRepresentation version:(NSUInteger)fromVersion;
|
||||
|
||||
@end
|
||||
-125
@@ -1,125 +0,0 @@
|
||||
//
|
||||
// MTLModel.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2012-09-11.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// An abstract base class for model objects, using reflection to provide
|
||||
// sensible default behaviors.
|
||||
//
|
||||
// The default implementations of <NSCopying>, -hash, and -isEqual: make use of
|
||||
// the +propertyKeys method.
|
||||
@interface MTLModel : NSObject <NSCopying>
|
||||
|
||||
// Returns a new instance of the receiver initialized using
|
||||
// -initWithDictionary:error:.
|
||||
+ (instancetype)modelWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error;
|
||||
|
||||
// Initializes the receiver with default values.
|
||||
//
|
||||
// This is the designated initializer for this class.
|
||||
- (instancetype)init;
|
||||
|
||||
// Initializes the receiver using key-value coding, setting the keys and values
|
||||
// in the given dictionary.
|
||||
//
|
||||
// Subclass implementations may override this method, calling the super
|
||||
// implementation, in order to perform further processing and initialization
|
||||
// after deserialization.
|
||||
//
|
||||
// dictionaryValue - Property keys and values to set on the receiver. Any NSNull
|
||||
// values will be converted to nil before being used. KVC
|
||||
// validation methods will automatically be invoked for all of
|
||||
// the properties given. If nil, this method is equivalent to
|
||||
// -init.
|
||||
// error - If not NULL, this may be set to any error that occurs
|
||||
// (like a KVC validation error).
|
||||
//
|
||||
// Returns an initialized model object, or nil if validation failed.
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error;
|
||||
|
||||
// Returns the keys for all @property declarations, except for `readonly`
|
||||
// properties without ivars, or properties on MTLModel itself.
|
||||
+ (NSSet *)propertyKeys;
|
||||
|
||||
// A dictionary representing the properties of the receiver.
|
||||
//
|
||||
// The default implementation combines the values corresponding to all
|
||||
// +propertyKeys into a dictionary, with any nil values represented by NSNull.
|
||||
//
|
||||
// This property must never be nil.
|
||||
@property (nonatomic, copy, readonly) NSDictionary *dictionaryValue;
|
||||
|
||||
// Merges the value of the given key on the receiver with the value of the same
|
||||
// key from the given model object, giving precedence to the other model object.
|
||||
//
|
||||
// By default, this method looks for a `-merge<Key>FromModel:` method on the
|
||||
// receiver, and invokes it if found. If not found, and `model` is not nil, the
|
||||
// value for the given key is taken from `model`.
|
||||
- (void)mergeValueForKey:(NSString *)key fromModel:(MTLModel *)model;
|
||||
|
||||
// Merges the values of the given model object into the receiver, using
|
||||
// -mergeValueForKey:fromModel: for each key in +propertyKeys.
|
||||
//
|
||||
// `model` must be an instance of the receiver's class or a subclass thereof.
|
||||
- (void)mergeValuesForKeysFromModel:(MTLModel *)model;
|
||||
|
||||
// Compares the receiver with another object for equality.
|
||||
//
|
||||
// The default implementation is equivalent to comparing both models'
|
||||
// -dictionaryValue.
|
||||
//
|
||||
// Note that this may lead to infinite loops if the receiver holds a circular
|
||||
// reference to another MTLModel and both use the default behavior.
|
||||
// It is recommended to override -isEqual: in this scenario.
|
||||
- (BOOL)isEqual:(id)object;
|
||||
|
||||
// A string that describes the contents of the receiver.
|
||||
//
|
||||
// The default implementation is based on the receiver's class and its
|
||||
// -dictionaryValue.
|
||||
//
|
||||
// Note that this may lead to infinite loops if the receiver holds a circular
|
||||
// reference to another MTLModel and both use the default behavior.
|
||||
// It is recommended to override -description in this scenario.
|
||||
- (NSString *)description;
|
||||
|
||||
@end
|
||||
|
||||
// Implements validation logic for MTLModel.
|
||||
@interface MTLModel (Validation)
|
||||
|
||||
// Validates the model.
|
||||
//
|
||||
// The default implementation simply invokes -validateValue:forKey:error: with
|
||||
// all +propertyKeys and their current value. If -validateValue:forKey:error:
|
||||
// returns a new value, the property is set to that new value.
|
||||
//
|
||||
// error - If not NULL, this may be set to any error that occurs during
|
||||
// validation
|
||||
//
|
||||
// Returns YES if the model is valid, or NO if the validation failed.
|
||||
- (BOOL)validate:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLModel (Unavailable)
|
||||
|
||||
+ (instancetype)modelWithDictionary:(NSDictionary *)dictionaryValue __attribute__((deprecated("Replaced by +modelWithDictionary:error:")));
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue __attribute__((deprecated("Replaced by -initWithDictionary:error:")));
|
||||
|
||||
+ (instancetype)modelWithExternalRepresentation:(NSDictionary *)externalRepresentation __attribute__((deprecated("Replaced by -[MTLJSONAdapter initWithJSONDictionary:modelClass:]")));
|
||||
- (instancetype)initWithExternalRepresentation:(NSDictionary *)externalRepresentation __attribute__((deprecated("Replaced by -[MTLJSONAdapter initWithJSONDictionary:modelClass:]")));
|
||||
|
||||
@property (nonatomic, copy, readonly) NSDictionary *externalRepresentation __attribute__((deprecated("Replaced by MTLJSONAdapter.JSONDictionary")));
|
||||
|
||||
+ (NSDictionary *)externalRepresentationKeyPathsByPropertyKey __attribute__((deprecated("Replaced by +JSONKeyPathsByPropertyKey in <MTLJSONSerializing>")));
|
||||
+ (NSValueTransformer *)transformerForKey:(NSString *)key __attribute__((deprecated("Replaced by +JSONTransformerForKey: in <MTLJSONSerializing>")));
|
||||
|
||||
+ (NSDictionary *)migrateExternalRepresentation:(NSDictionary *)externalRepresentation fromVersion:(NSUInteger)fromVersion __attribute__((deprecated("Replaced by -decodeValueForKey:withCoder:modelVersion:")));
|
||||
|
||||
@end
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
//
|
||||
// MTLValueTransformer.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2012-09-11.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
typedef id (^MTLValueTransformerBlock)(id);
|
||||
|
||||
//
|
||||
// A value transformer supporting block-based transformation.
|
||||
//
|
||||
@interface MTLValueTransformer : NSValueTransformer
|
||||
|
||||
// Returns a transformer which transforms values using the given block. Reverse
|
||||
// transformations will not be allowed.
|
||||
+ (instancetype)transformerWithBlock:(MTLValueTransformerBlock)transformationBlock;
|
||||
|
||||
// Returns a transformer which transforms values using the given block, for
|
||||
// forward or reverse transformations.
|
||||
+ (instancetype)reversibleTransformerWithBlock:(MTLValueTransformerBlock)transformationBlock;
|
||||
|
||||
// Returns a transformer which transforms values using the given blocks.
|
||||
+ (instancetype)reversibleTransformerWithForwardBlock:(MTLValueTransformerBlock)forwardBlock reverseBlock:(MTLValueTransformerBlock)reverseBlock;
|
||||
|
||||
@end
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
//
|
||||
// Mantle.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2012-09-04.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for Mantle.
|
||||
FOUNDATION_EXPORT double MantleVersionNumber;
|
||||
|
||||
//! Project version string for Mantle.
|
||||
FOUNDATION_EXPORT const unsigned char MantleVersionString[];
|
||||
|
||||
#import <Mantle/MTLJSONAdapter.h>
|
||||
#import <Mantle/MTLManagedObjectAdapter.h>
|
||||
#import <Mantle/MTLModel.h>
|
||||
#import <Mantle/MTLModel+NSCoding.h>
|
||||
#import <Mantle/MTLValueTransformer.h>
|
||||
#import <Mantle/NSArray+MTLManipulationAdditions.h>
|
||||
#import <Mantle/NSDictionary+MTLManipulationAdditions.h>
|
||||
#import <Mantle/NSObject+MTLComparisonAdditions.h>
|
||||
#import <Mantle/NSValueTransformer+MTLInversionAdditions.h>
|
||||
#import <Mantle/NSValueTransformer+MTLPredefinedTransformerAdditions.h>
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
//
|
||||
// NSArray+MTLManipulationAdditions.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Josh Abernathy on 9/19/12.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface NSArray (MTLManipulationAdditions)
|
||||
|
||||
// The first object in the array or nil if the array is empty.
|
||||
// Forwards to `firstObject` which has been first declared in iOS7, but works with iOS4/10.6.
|
||||
@property (nonatomic, readonly, strong) id mtl_firstObject;
|
||||
|
||||
// Returns a new array without all instances of the given object.
|
||||
- (NSArray *)mtl_arrayByRemovingObject:(id)object;
|
||||
|
||||
// Returns a new array without the first object. If the array is empty, it
|
||||
// returns the empty array.
|
||||
- (NSArray *)mtl_arrayByRemovingFirstObject;
|
||||
|
||||
// Returns a new array without the last object. If the array is empty, it
|
||||
// returns the empty array.
|
||||
- (NSArray *)mtl_arrayByRemovingLastObject;
|
||||
|
||||
@end
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
//
|
||||
// NSDictionary+MTLManipulationAdditions.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2012-09-24.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface NSDictionary (MTLManipulationAdditions)
|
||||
|
||||
// Merges the keys and values from the given dictionary into the receiver. If
|
||||
// both the receiver and `dictionary` have a given key, the value from
|
||||
// `dictionary` is used.
|
||||
//
|
||||
// Returns a new dictionary containing the entries of the receiver combined with
|
||||
// those of `dictionary`.
|
||||
- (NSDictionary *)mtl_dictionaryByAddingEntriesFromDictionary:(NSDictionary *)dictionary;
|
||||
|
||||
// Creates a new dictionary with all the entries for the given keys removed from
|
||||
// the receiver.
|
||||
- (NSDictionary *)mtl_dictionaryByRemovingEntriesWithKeys:(NSSet *)keys;
|
||||
|
||||
@end
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
//
|
||||
// NSObject+MTLComparisonAdditions.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Josh Vera on 10/26/12.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
// Portions copyright (c) 2011 Bitswift. All rights reserved.
|
||||
// See the LICENSE file for more information.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// Returns whether both objects are identical or equal via -isEqual:
|
||||
BOOL MTLEqualObjects(id obj1, id obj2);
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
//
|
||||
// NSValueTransformer+MTLInversionAdditions.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-05-18.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@interface NSValueTransformer (MTLInversionAdditions)
|
||||
|
||||
// Flips the direction of the receiver's transformation, such that
|
||||
// -transformedValue: will become -reverseTransformedValue:, and vice-versa.
|
||||
//
|
||||
// The receiver must allow reverse transformation.
|
||||
//
|
||||
// Returns an inverted transformer.
|
||||
- (NSValueTransformer *)mtl_invertedTransformer;
|
||||
|
||||
@end
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
//
|
||||
// NSValueTransformer+MTLPredefinedTransformerAdditions.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2012-09-27.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// The name for a value transformer that converts strings into URLs and back.
|
||||
extern NSString * const MTLURLValueTransformerName;
|
||||
|
||||
// Ensure an NSNumber is backed by __NSCFBoolean/CFBooleanRef
|
||||
//
|
||||
// NSJSONSerialization, and likely other serialization libraries, ordinarily
|
||||
// serialize NSNumbers as numbers, and thus booleans would be serialized as
|
||||
// 0/1. The exception is when the NSNumber is backed by __NSCFBoolean, which,
|
||||
// though very much an implementation detail, is detected and serialized as a
|
||||
// proper boolean.
|
||||
extern NSString * const MTLBooleanValueTransformerName;
|
||||
|
||||
@interface NSValueTransformer (MTLPredefinedTransformerAdditions)
|
||||
|
||||
// Creates a reversible transformer to convert a JSON dictionary into a MTLModel
|
||||
// object, and vice-versa.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON. This
|
||||
// class must conform to <MTLJSONSerializing>. This argument must
|
||||
// not be nil.
|
||||
//
|
||||
// Returns a reversible transformer which uses MTLJSONAdapter for transforming
|
||||
// values back and forth.
|
||||
+ (NSValueTransformer *)mtl_JSONDictionaryTransformerWithModelClass:(Class)modelClass;
|
||||
|
||||
// Creates a reversible transformer to convert an array of JSON dictionaries
|
||||
// into an array of MTLModel objects, and vice-versa.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from each JSON
|
||||
// dictionary. This class must conform to <MTLJSONSerializing>.
|
||||
// This argument must not be nil.
|
||||
//
|
||||
// Returns a reversible transformer which uses MTLJSONAdapter for transforming
|
||||
// array elements back and forth.
|
||||
+ (NSValueTransformer *)mtl_JSONArrayTransformerWithModelClass:(Class)modelClass;
|
||||
|
||||
// A reversible value transformer to transform between the keys and objects of a
|
||||
// dictionary.
|
||||
//
|
||||
// dictionary - The dictionary whose keys and values should be
|
||||
// transformed between. This argument must not be nil.
|
||||
// defaultValue - The result to fall back to, in case no key matching the
|
||||
// input value was found during a forward transformation.
|
||||
// reverseDefaultValue - The result to fall back to, in case no value matching
|
||||
// the input value was found during a reverse
|
||||
// transformation.
|
||||
//
|
||||
// Can for example be used for transforming between enum values and their string
|
||||
// representation.
|
||||
//
|
||||
// NSValueTransformer *valueTransformer = [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{
|
||||
// @"foo": @(EnumDataTypeFoo),
|
||||
// @"bar": @(EnumDataTypeBar),
|
||||
// } defaultValue: @(EnumDataTypeUndefined) reverseDefaultValue: @"undefined"];
|
||||
//
|
||||
// Returns a transformer that will map from keys to values in dictionary
|
||||
// for forward transformation, and from values to keys for reverse
|
||||
// transformations. If no matching key or value can be found, the respective
|
||||
// default value is returned.
|
||||
+ (NSValueTransformer *)mtl_valueMappingTransformerWithDictionary:(NSDictionary *)dictionary defaultValue:(id)defaultValue reverseDefaultValue:(id)reverseDefaultValue;
|
||||
|
||||
// Returns a value transformer created by calling
|
||||
// `+mtl_valueMappingTransformerWithDictionary:defaultValue:reverseDefaultValue:`
|
||||
// with a default value of `nil` and a reverse default value of `nil`.
|
||||
+ (NSValueTransformer *)mtl_valueMappingTransformerWithDictionary:(NSDictionary *)dictionary;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSValueTransformer (UnavailableMTLPredefinedTransformerAdditions)
|
||||
|
||||
+ (NSValueTransformer *)mtl_externalRepresentationTransformerWithModelClass:(Class)modelClass __attribute__((deprecated("Replaced by +mtl_JSONDictionaryTransformerWithModelClass:")));
|
||||
+ (NSValueTransformer *)mtl_externalRepresentationArrayTransformerWithModelClass:(Class)modelClass __attribute__((deprecated("Replaced by +mtl_JSONArrayTransformerWithModelClass:")));
|
||||
|
||||
@end
|
||||
BIN
Binary file not shown.
-6
@@ -1,6 +0,0 @@
|
||||
framework module Mantle {
|
||||
umbrella header "Mantle.h"
|
||||
|
||||
export *
|
||||
module * { export * }
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>BuildMachineOSBuild</key>
|
||||
<string>16F2104</string>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>Mantle</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>org.mantle.Mantle</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>Mantle</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleSupportedPlatforms</key>
|
||||
<array>
|
||||
<string>MacOSX</string>
|
||||
</array>
|
||||
<key>CFBundleVersion</key>
|
||||
<string></string>
|
||||
<key>DTCompiler</key>
|
||||
<string>com.apple.compilers.llvm.clang.1_0</string>
|
||||
<key>DTPlatformBuild</key>
|
||||
<string>8E3004b</string>
|
||||
<key>DTPlatformVersion</key>
|
||||
<string>GM</string>
|
||||
<key>DTSDKBuild</key>
|
||||
<string>16E185</string>
|
||||
<key>DTSDKName</key>
|
||||
<string>macosx10.12</string>
|
||||
<key>DTXcode</key>
|
||||
<string>0833</string>
|
||||
<key>DTXcodeBuild</key>
|
||||
<string>8E3004b</string>
|
||||
<key>UIDeviceFamily</key>
|
||||
<array>
|
||||
<integer>1</integer>
|
||||
<integer>2</integer>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
-264
@@ -1,264 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>files</key>
|
||||
<dict>
|
||||
<key>Resources/Info.plist</key>
|
||||
<data>
|
||||
5gOxsGY3VGVvebnR8eP1z3BDrls=
|
||||
</data>
|
||||
</dict>
|
||||
<key>files2</key>
|
||||
<dict>
|
||||
<key>Headers/MTLJSONAdapter.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
HIypP9pGI7Wk97RKy3thGsC7LSg=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
YhksDrIzFk7TQllZD4eF2qEubtCfFlDrddfBeJEvpoc=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/MTLManagedObjectAdapter.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
tjTyEh7TlZBAXcyaY1I1SmXHbE4=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
WxYp7uqr+H3R5UnwMpDSHlxSt7MaAPhQob/BDXlWbVI=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/MTLModel+NSCoding.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
2tdybjH/C8ZU8VcZrX4oliXkuM8=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
QuzPKm76puk2/uZN0s9Jqn7g5AFF6xFbnBsN450IXfc=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/MTLModel.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
9c2w4hZo7o/vLu/3TaZ2vXXjwxc=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
2JEc6fCePU0odH+dDY8947O0/wS1Ey96Vuun1HCP564=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/MTLValueTransformer.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
m6veNGSL5/Kif8yDXH5zU+2CaK8=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
AnO4t0Ur5lBz44l14XRXgB3g6JEiUE1JBfPdvV+H7fA=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/Mantle.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
TYIHtg+qqzl8yG0InqTB7Oyr63A=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
YKN3UxwC4VdZ19A/VN8Ndpdf5PVHbZlYMb9K1etJKKg=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/NSArray+MTLManipulationAdditions.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
JkGLHSSIKlmCin6flems7m4llvE=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
fQTG4WuuoxdNhgn6wDU29iy18nNqFwlK9F45NRbpD6w=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/NSDictionary+MTLManipulationAdditions.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
bqGP1ngOZeJ16AY5Vi/2ObZCmlw=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
0Jf2Da8WIPOoV0BkwF1D69nsUwbgypRDMVoedgtuJ24=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/NSObject+MTLComparisonAdditions.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
2oBONz9+tBIWVjYGxYBIBT0b0n8=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
86zL7jX96Spa7xT5HQJ+aYmtXD1oKLUrU4JtlO2cIqU=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/NSValueTransformer+MTLInversionAdditions.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
sxXToKdUH8yMt45aTwPeM3hKmjs=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
6xpkrCw6Z2B3EOFKGMBi6o78Hau0v0zsfGJeQMAk354=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Headers/NSValueTransformer+MTLPredefinedTransformerAdditions.h</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
HhBKFxBsCIBfvD6Rm6d3yjVk540=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
QAg6gyiNeq39mqhxZ/OttPualO+F1x2E99sNuyNE1ZE=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Modules/module.modulemap</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
Bey/HDj6mfWAMaHrd42tLo2G6HA=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
kjfaRu6wmQ32w9Db79wuDbkttAjOMC2jrLbtCbIzrSM=
|
||||
</data>
|
||||
</dict>
|
||||
<key>Resources/Info.plist</key>
|
||||
<dict>
|
||||
<key>hash</key>
|
||||
<data>
|
||||
5gOxsGY3VGVvebnR8eP1z3BDrls=
|
||||
</data>
|
||||
<key>hash2</key>
|
||||
<data>
|
||||
e6zwAZD1Y0oZhr5vq5p/9RM9J6llqdDsogAev9b3loI=
|
||||
</data>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>rules</key>
|
||||
<dict>
|
||||
<key>^Resources/</key>
|
||||
<true/>
|
||||
<key>^Resources/.*\.lproj/</key>
|
||||
<dict>
|
||||
<key>optional</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1000</real>
|
||||
</dict>
|
||||
<key>^Resources/.*\.lproj/locversion.plist$</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1100</real>
|
||||
</dict>
|
||||
<key>^Resources/Base\.lproj/</key>
|
||||
<dict>
|
||||
<key>weight</key>
|
||||
<real>1010</real>
|
||||
</dict>
|
||||
<key>^version.plist$</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>rules2</key>
|
||||
<dict>
|
||||
<key>.*\.dSYM($|/)</key>
|
||||
<dict>
|
||||
<key>weight</key>
|
||||
<real>11</real>
|
||||
</dict>
|
||||
<key>^(.*/)?\.DS_Store$</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>2000</real>
|
||||
</dict>
|
||||
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
|
||||
<dict>
|
||||
<key>nested</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>10</real>
|
||||
</dict>
|
||||
<key>^.*</key>
|
||||
<true/>
|
||||
<key>^Info\.plist$</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>20</real>
|
||||
</dict>
|
||||
<key>^PkgInfo$</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>20</real>
|
||||
</dict>
|
||||
<key>^Resources/</key>
|
||||
<dict>
|
||||
<key>weight</key>
|
||||
<real>20</real>
|
||||
</dict>
|
||||
<key>^Resources/.*\.lproj/</key>
|
||||
<dict>
|
||||
<key>optional</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1000</real>
|
||||
</dict>
|
||||
<key>^Resources/.*\.lproj/locversion.plist$</key>
|
||||
<dict>
|
||||
<key>omit</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>1100</real>
|
||||
</dict>
|
||||
<key>^Resources/Base\.lproj/</key>
|
||||
<dict>
|
||||
<key>weight</key>
|
||||
<real>1010</real>
|
||||
</dict>
|
||||
<key>^[^/]+$</key>
|
||||
<dict>
|
||||
<key>nested</key>
|
||||
<true/>
|
||||
<key>weight</key>
|
||||
<real>10</real>
|
||||
</dict>
|
||||
<key>^embedded\.provisionprofile$</key>
|
||||
<dict>
|
||||
<key>weight</key>
|
||||
<real>20</real>
|
||||
</dict>
|
||||
<key>^version\.plist$</key>
|
||||
<dict>
|
||||
<key>weight</key>
|
||||
<real>20</real>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
-1
@@ -1 +0,0 @@
|
||||
A
|
||||
-1
@@ -1 +0,0 @@
|
||||
Versions/Current/Headers
|
||||
-1
@@ -1 +0,0 @@
|
||||
Versions/Current/Modules
|
||||
-1
@@ -1 +0,0 @@
|
||||
Versions/Current/ReactiveCocoa
|
||||
-1
@@ -1 +0,0 @@
|
||||
Versions/Current/Resources
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
//
|
||||
// EXTKeyPathCoding.h
|
||||
// extobjc
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 19.06.12.
|
||||
// Copyright (C) 2012 Justin Spahr-Summers.
|
||||
// Released under the MIT license.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "metamacros.h"
|
||||
|
||||
/**
|
||||
* \@keypath allows compile-time verification of key paths. Given a real object
|
||||
* receiver and key path:
|
||||
*
|
||||
* @code
|
||||
|
||||
NSString *UTF8StringPath = @keypath(str.lowercaseString.UTF8String);
|
||||
// => @"lowercaseString.UTF8String"
|
||||
|
||||
NSString *versionPath = @keypath(NSObject, version);
|
||||
// => @"version"
|
||||
|
||||
NSString *lowercaseStringPath = @keypath(NSString.new, lowercaseString);
|
||||
// => @"lowercaseString"
|
||||
|
||||
* @endcode
|
||||
*
|
||||
* ... the macro returns an \c NSString containing all but the first path
|
||||
* component or argument (e.g., @"lowercaseString.UTF8String", @"version").
|
||||
*
|
||||
* In addition to simply creating a key path, this macro ensures that the key
|
||||
* path is valid at compile-time (causing a syntax error if not), and supports
|
||||
* refactoring, such that changing the name of the property will also update any
|
||||
* uses of \@keypath.
|
||||
*/
|
||||
#define keypath(...) \
|
||||
metamacro_if_eq(1, metamacro_argcount(__VA_ARGS__))(keypath1(__VA_ARGS__))(keypath2(__VA_ARGS__))
|
||||
|
||||
#define keypath1(PATH) \
|
||||
(((void)(NO && ((void)PATH, NO)), strchr(# PATH, '.') + 1))
|
||||
|
||||
#define keypath2(OBJ, PATH) \
|
||||
(((void)(NO && ((void)OBJ.PATH, NO)), # PATH))
|
||||
|
||||
/**
|
||||
* \@collectionKeypath allows compile-time verification of key paths across collections NSArray/NSSet etc. Given a real object
|
||||
* receiver, collection object receiver and related keypaths:
|
||||
*
|
||||
* @code
|
||||
|
||||
NSString *employessFirstNamePath = @collectionKeypath(department.employees, Employee.new, firstName)
|
||||
// => @"employees.firstName"
|
||||
|
||||
NSString *employessFirstNamePath = @collectionKeypath(Department.new, employees, Employee.new, firstName)
|
||||
// => @"employees.firstName"
|
||||
|
||||
* @endcode
|
||||
*
|
||||
*/
|
||||
#define collectionKeypath(...) \
|
||||
metamacro_if_eq(3, metamacro_argcount(__VA_ARGS__))(collectionKeypath3(__VA_ARGS__))(collectionKeypath4(__VA_ARGS__))
|
||||
|
||||
#define collectionKeypath3(PATH, COLLECTION_OBJECT, COLLECTION_PATH) ([[NSString stringWithFormat:@"%s.%s",keypath(PATH), keypath(COLLECTION_OBJECT, COLLECTION_PATH)] UTF8String])
|
||||
|
||||
#define collectionKeypath4(OBJ, PATH, COLLECTION_OBJECT, COLLECTION_PATH) ([[NSString stringWithFormat:@"%s.%s",keypath(OBJ, PATH), keypath(COLLECTION_OBJECT, COLLECTION_PATH)] UTF8String])
|
||||
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
//
|
||||
// EXTScope.h
|
||||
// extobjc
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2011-05-04.
|
||||
// Copyright (C) 2012 Justin Spahr-Summers.
|
||||
// Released under the MIT license.
|
||||
//
|
||||
|
||||
#import "metamacros.h"
|
||||
|
||||
/**
|
||||
* \@onExit defines some code to be executed when the current scope exits. The
|
||||
* code must be enclosed in braces and terminated with a semicolon, and will be
|
||||
* executed regardless of how the scope is exited, including from exceptions,
|
||||
* \c goto, \c return, \c break, and \c continue.
|
||||
*
|
||||
* Provided code will go into a block to be executed later. Keep this in mind as
|
||||
* it pertains to memory management, restrictions on assignment, etc. Because
|
||||
* the code is used within a block, \c return is a legal (though perhaps
|
||||
* confusing) way to exit the cleanup block early.
|
||||
*
|
||||
* Multiple \@onExit statements in the same scope are executed in reverse
|
||||
* lexical order. This helps when pairing resource acquisition with \@onExit
|
||||
* statements, as it guarantees teardown in the opposite order of acquisition.
|
||||
*
|
||||
* @note This statement cannot be used within scopes defined without braces
|
||||
* (like a one line \c if). In practice, this is not an issue, since \@onExit is
|
||||
* a useless construct in such a case anyways.
|
||||
*/
|
||||
#define onExit \
|
||||
rac_keywordify \
|
||||
__strong rac_cleanupBlock_t metamacro_concat(rac_exitBlock_, __LINE__) __attribute__((cleanup(rac_executeCleanupBlock), unused)) = ^
|
||||
|
||||
/**
|
||||
* Creates \c __weak shadow variables for each of the variables provided as
|
||||
* arguments, which can later be made strong again with #strongify.
|
||||
*
|
||||
* This is typically used to weakly reference variables in a block, but then
|
||||
* ensure that the variables stay alive during the actual execution of the block
|
||||
* (if they were live upon entry).
|
||||
*
|
||||
* See #strongify for an example of usage.
|
||||
*/
|
||||
#define weakify(...) \
|
||||
rac_keywordify \
|
||||
metamacro_foreach_cxt(rac_weakify_,, __weak, __VA_ARGS__)
|
||||
|
||||
/**
|
||||
* Like #weakify, but uses \c __unsafe_unretained instead, for targets or
|
||||
* classes that do not support weak references.
|
||||
*/
|
||||
#define unsafeify(...) \
|
||||
rac_keywordify \
|
||||
metamacro_foreach_cxt(rac_weakify_,, __unsafe_unretained, __VA_ARGS__)
|
||||
|
||||
/**
|
||||
* Strongly references each of the variables provided as arguments, which must
|
||||
* have previously been passed to #weakify.
|
||||
*
|
||||
* The strong references created will shadow the original variable names, such
|
||||
* that the original names can be used without issue (and a significantly
|
||||
* reduced risk of retain cycles) in the current scope.
|
||||
*
|
||||
* @code
|
||||
|
||||
id foo = [[NSObject alloc] init];
|
||||
id bar = [[NSObject alloc] init];
|
||||
|
||||
@weakify(foo, bar);
|
||||
|
||||
// this block will not keep 'foo' or 'bar' alive
|
||||
BOOL (^matchesFooOrBar)(id) = ^ BOOL (id obj){
|
||||
// but now, upon entry, 'foo' and 'bar' will stay alive until the block has
|
||||
// finished executing
|
||||
@strongify(foo, bar);
|
||||
|
||||
return [foo isEqual:obj] || [bar isEqual:obj];
|
||||
};
|
||||
|
||||
* @endcode
|
||||
*/
|
||||
#define strongify(...) \
|
||||
rac_keywordify \
|
||||
_Pragma("clang diagnostic push") \
|
||||
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
|
||||
metamacro_foreach(rac_strongify_,, __VA_ARGS__) \
|
||||
_Pragma("clang diagnostic pop")
|
||||
|
||||
/*** implementation details follow ***/
|
||||
typedef void (^rac_cleanupBlock_t)();
|
||||
|
||||
static inline void rac_executeCleanupBlock (__strong rac_cleanupBlock_t *block) {
|
||||
(*block)();
|
||||
}
|
||||
|
||||
#define rac_weakify_(INDEX, CONTEXT, VAR) \
|
||||
CONTEXT __typeof__(VAR) metamacro_concat(VAR, _weak_) = (VAR);
|
||||
|
||||
#define rac_strongify_(INDEX, VAR) \
|
||||
__strong __typeof__(VAR) VAR = metamacro_concat(VAR, _weak_);
|
||||
|
||||
// Details about the choice of backing keyword:
|
||||
//
|
||||
// The use of @try/@catch/@finally can cause the compiler to suppress
|
||||
// return-type warnings.
|
||||
// The use of @autoreleasepool {} is not optimized away by the compiler,
|
||||
// resulting in superfluous creation of autorelease pools.
|
||||
//
|
||||
// Since neither option is perfect, and with no other alternatives, the
|
||||
// compromise is to use @autorelease in DEBUG builds to maintain compiler
|
||||
// analysis, and to use @try/@catch otherwise to avoid insertion of unnecessary
|
||||
// autorelease pools.
|
||||
#if DEBUG
|
||||
#define rac_keywordify autoreleasepool {}
|
||||
#else
|
||||
#define rac_keywordify try {} @catch (...) {}
|
||||
#endif
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
//
|
||||
// NSArray+RACSequenceAdditions.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2012-10-29.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSequence;
|
||||
|
||||
@interface NSArray (RACSequenceAdditions)
|
||||
|
||||
/// Creates and returns a sequence corresponding to the receiver.
|
||||
///
|
||||
/// Mutating the receiver will not affect the sequence after it's been created.
|
||||
@property (nonatomic, copy, readonly) RACSequence *rac_sequence;
|
||||
|
||||
@end
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
//
|
||||
// NSControl+RACCommandSupport.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Josh Abernathy on 3/3/12.
|
||||
// Copyright (c) 2012 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@class RACCommand;
|
||||
|
||||
@interface NSControl (RACCommandSupport)
|
||||
|
||||
/// Sets the control's command. When the control is clicked, the command is
|
||||
/// executed with the sender of the event. The control's enabledness is bound
|
||||
/// to the command's `canExecute`.
|
||||
///
|
||||
/// Note: this will reset the control's target and action.
|
||||
@property (nonatomic, strong) RACCommand *rac_command;
|
||||
|
||||
@end
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
//
|
||||
// NSControl+RACTextSignalSupport.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-03-08.
|
||||
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
@interface NSControl (RACTextSignalSupport)
|
||||
|
||||
/// Observes a text-based control for changes.
|
||||
///
|
||||
/// Using this method on a control without editable text is considered undefined
|
||||
/// behavior.
|
||||
///
|
||||
/// Returns a signal which sends the current string value of the receiver, then
|
||||
/// the new value any time it changes.
|
||||
- (RACSignal *)rac_textSignal;
|
||||
|
||||
@end
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
//
|
||||
// NSData+RACSupport.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Josh Abernathy on 5/11/12.
|
||||
// Copyright (c) 2012 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACScheduler;
|
||||
@class RACSignal;
|
||||
|
||||
@interface NSData (RACSupport)
|
||||
|
||||
// Read the data at the URL using -[NSData initWithContentsOfURL:options:error:].
|
||||
// Sends the data or the error.
|
||||
//
|
||||
// scheduler - cannot be nil.
|
||||
+ (RACSignal *)rac_readContentsOfURL:(NSURL *)URL options:(NSDataReadingOptions)options scheduler:(RACScheduler *)scheduler;
|
||||
|
||||
@end
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
//
|
||||
// NSDictionary+RACSequenceAdditions.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2012-10-29.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSequence;
|
||||
|
||||
@interface NSDictionary (RACSequenceAdditions)
|
||||
|
||||
/// Creates and returns a sequence of RACTuple key/value pairs. The key will be
|
||||
/// the first element in the tuple, and the value will be the second.
|
||||
///
|
||||
/// Mutating the receiver will not affect the sequence after it's been created.
|
||||
@property (nonatomic, copy, readonly) RACSequence *rac_sequence;
|
||||
|
||||
/// Creates and returns a sequence corresponding to the keys in the receiver.
|
||||
///
|
||||
/// Mutating the receiver will not affect the sequence after it's been created.
|
||||
@property (nonatomic, copy, readonly) RACSequence *rac_keySequence;
|
||||
|
||||
/// Creates and returns a sequence corresponding to the values in the receiver.
|
||||
///
|
||||
/// Mutating the receiver will not affect the sequence after it's been created.
|
||||
@property (nonatomic, copy, readonly) RACSequence *rac_valueSequence;
|
||||
|
||||
@end
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
//
|
||||
// NSEnumerator+RACSequenceAdditions.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Uri Baghin on 07/01/2013.
|
||||
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSequence;
|
||||
|
||||
@interface NSEnumerator (RACSequenceAdditions)
|
||||
|
||||
/// Creates and returns a sequence corresponding to the receiver.
|
||||
///
|
||||
/// The receiver is exhausted lazily as the sequence is enumerated.
|
||||
@property (nonatomic, copy, readonly) RACSequence *rac_sequence;
|
||||
|
||||
@end
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
//
|
||||
// NSFileHandle+RACSupport.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Josh Abernathy on 5/10/12.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
@interface NSFileHandle (RACSupport)
|
||||
|
||||
// Read any available data in the background and send it. Completes when data
|
||||
// length is <= 0.
|
||||
- (RACSignal *)rac_readInBackground;
|
||||
|
||||
@end
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
//
|
||||
// NSIndexSet+RACSequenceAdditions.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Sergey Gavrilyuk on 12/17/13.
|
||||
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSequence;
|
||||
|
||||
@interface NSIndexSet (RACSequenceAdditions)
|
||||
|
||||
/// Creates and returns a sequence of indexes (as `NSNumber`s) corresponding to
|
||||
/// the receiver.
|
||||
///
|
||||
/// Mutating the receiver will not affect the sequence after it's been created.
|
||||
@property (nonatomic, copy, readonly) RACSequence *rac_sequence;
|
||||
|
||||
@end
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
//
|
||||
// NSNotificationCenter+RACSupport.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Josh Abernathy on 5/10/12.
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
@interface NSNotificationCenter (RACSupport)
|
||||
|
||||
// Sends the NSNotification every time the notification is posted.
|
||||
- (RACSignal *)rac_addObserverForName:(NSString *)notificationName object:(id)object;
|
||||
|
||||
@end
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
//
|
||||
// NSObject+RACAppKitBindings.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Josh Abernathy on 4/17/12.
|
||||
// Copyright (c) 2012 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@class RACChannelTerminal;
|
||||
|
||||
@interface NSObject (RACAppKitBindings)
|
||||
|
||||
/// Invokes -rac_channelToBinding:options: without any options.
|
||||
- (RACChannelTerminal *)rac_channelToBinding:(NSString *)binding;
|
||||
|
||||
/// Applies a Cocoa binding to the receiver, then exposes a RACChannel-based
|
||||
/// interface for manipulating it.
|
||||
///
|
||||
/// Creating two of the same bindings on the same object will result in undefined
|
||||
/// behavior.
|
||||
///
|
||||
/// binding - The name of the binding. This must not be nil.
|
||||
/// options - Any options to pass to Cocoa Bindings. This may be nil.
|
||||
///
|
||||
/// Returns a RACChannelTerminal which will send future values from the receiver,
|
||||
/// and update the receiver when values are sent to the terminal.
|
||||
- (RACChannelTerminal *)rac_channelToBinding:(NSString *)binding options:(NSDictionary *)options;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSObject (RACAppKitBindingsDeprecated)
|
||||
|
||||
- (void)rac_bind:(NSString *)binding toObject:(id)object withKeyPath:(NSString *)keyPath __attribute__((deprecated("Use -rac_bind:options: instead")));
|
||||
- (void)rac_bind:(NSString *)binding toObject:(id)object withKeyPath:(NSString *)keyPath nilValue:(id)nilValue __attribute__((deprecated("Use -rac_bind:options: instead")));
|
||||
- (void)rac_bind:(NSString *)binding toObject:(id)object withKeyPath:(NSString *)keyPath transform:(id (^)(id value))transformBlock __attribute__((deprecated("Use -rac_bind:options: instead")));
|
||||
- (void)rac_bind:(NSString *)binding toObject:(id)object withNegatedKeyPath:(NSString *)keyPath __attribute__((deprecated("Use -rac_bind:options: instead")));
|
||||
|
||||
@end
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
//
|
||||
// NSObject+RACDeallocating.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Kazuo Koga on 2013/03/15.
|
||||
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACCompoundDisposable;
|
||||
@class RACDisposable;
|
||||
@class RACSignal;
|
||||
|
||||
@interface NSObject (RACDeallocating)
|
||||
|
||||
/// The compound disposable which will be disposed of when the receiver is
|
||||
/// deallocated.
|
||||
@property (atomic, readonly, strong) RACCompoundDisposable *rac_deallocDisposable;
|
||||
|
||||
/// Returns a signal that will complete immediately before the receiver is fully
|
||||
/// deallocated. If already deallocated when the signal is subscribed to,
|
||||
/// a `completed` event will be sent immediately.
|
||||
- (RACSignal *)rac_willDeallocSignal;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSObject (RACDeallocatingDeprecated)
|
||||
|
||||
- (RACSignal *)rac_didDeallocSignal __attribute__((deprecated("Use -rac_willDeallocSignal")));
|
||||
|
||||
- (void)rac_addDeallocDisposable:(RACDisposable *)disposable __attribute__((deprecated("Add disposables to -rac_deallocDisposable instead")));
|
||||
|
||||
@end
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
//
|
||||
// NSObject+RACLifting.h
|
||||
// ReactiveCocoa
|
||||
//
|
||||
// Created by Josh Abernathy on 10/13/12.
|
||||
// Copyright (c) 2012 GitHub, Inc. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class RACSignal;
|
||||
|
||||
@interface NSObject (RACLifting)
|
||||
|
||||
/// Lifts the selector on the receiver into the reactive world. The selector will
|
||||
/// be invoked whenever any signal argument sends a value, but only after each
|
||||
/// signal has sent an initial value.
|
||||
///
|
||||
/// It will replay the most recently sent value to new subscribers.
|
||||
///
|
||||
/// This does not support C arrays or unions.
|
||||
///
|
||||
/// selector - The selector on self to invoke.
|
||||
/// firstSignal - The signal corresponding to the first method argument. This
|
||||
/// must not be nil.
|
||||
/// ... - A list of RACSignals corresponding to the remaining arguments.
|
||||
/// There must be a non-nil signal for each method argument.
|
||||
///
|
||||
/// Examples
|
||||
///
|
||||
/// [button rac_liftSelector:@selector(setTitleColor:forState:) withSignals:textColorSignal, [RACSignal return:@(UIControlStateNormal)], nil];
|
||||
///
|
||||
/// Returns a signal which sends the return value from each invocation of the
|
||||
/// selector. If the selector returns void, it instead sends RACUnit.defaultUnit.
|
||||
/// It completes only after all the signal arguments complete.
|
||||
- (RACSignal *)rac_liftSelector:(SEL)selector withSignals:(RACSignal *)firstSignal, ... NS_REQUIRES_NIL_TERMINATION;
|
||||
|
||||
/// Like -rac_liftSelector:withSignals:, but accepts an array instead of
|
||||
/// a variadic list of arguments.
|
||||
- (RACSignal *)rac_liftSelector:(SEL)selector withSignalsFromArray:(NSArray *)signals;
|
||||
|
||||
/// Like -rac_liftSelector:withSignals:, but accepts a signal sending tuples of
|
||||
/// arguments instead of a variadic list of arguments.
|
||||
- (RACSignal *)rac_liftSelector:(SEL)selector withSignalOfArguments:(RACSignal *)arguments;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSObject (RACLiftingDeprecated)
|
||||
|
||||
- (RACSignal *)rac_liftSelector:(SEL)selector withObjects:(id)arg, ... __attribute__((deprecated("Use -rac_liftSelector:withSignals: instead")));
|
||||
- (RACSignal *)rac_liftSelector:(SEL)selector withObjectsFromArray:(NSArray *)args __attribute__((deprecated("Use -rac_liftSelector:withSignalsFromArray: instead")));
|
||||
- (RACSignal *)rac_liftBlock:(id)block withArguments:(id)arg, ... NS_REQUIRES_NIL_TERMINATION __attribute__((deprecated("Use +combineLatest:reduce: instead")));
|
||||
- (RACSignal *)rac_liftBlock:(id)block withArgumentsFromArray:(NSArray *)args __attribute__((deprecated("Use +combineLatest:reduce: instead")));
|
||||
|
||||
@end
|
||||
|
||||
@interface NSObject (RACLiftingUnavailable)
|
||||
|
||||
- (instancetype)rac_lift __attribute__((unavailable("Use -rac_liftSelector:withSignals: instead")));
|
||||
|
||||
@end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user