🎨 Apply swiftformat

This commit is contained in:
Ben Chatelain 2019-01-29 23:15:24 -07:00
parent 85079b5f7a
commit 8a96664a74
58 changed files with 155 additions and 157 deletions

View file

@ -19,7 +19,7 @@ func download(_ adamId: UInt64) -> MASError? {
} }
guard let storeAccount = account as? ISStoreAccount guard let storeAccount = account as? ISStoreAccount
else { fatalError("Unable to cast StoreAccount to ISStoreAccount") } else { fatalError("Unable to cast StoreAccount to ISStoreAccount") }
let purchase = SSPurchase(adamId: adamId, account: storeAccount) let purchase = SSPurchase(adamId: adamId, account: storeAccount)
var purchaseError: MASError? var purchaseError: MASError?

View file

@ -6,8 +6,8 @@
// Copyright (c) 2015 Andrew Naylor. All rights reserved. // Copyright (c) 2015 Andrew Naylor. All rights reserved.
// //
import StoreFoundation
import CommerceKit import CommerceKit
import StoreFoundation
extension ISStoreAccount: StoreAccount { extension ISStoreAccount: StoreAccount {
static var primaryAccountIsPresentAndSignedIn: Bool { static var primaryAccountIsPresentAndSignedIn: Bool {

View file

@ -31,7 +31,7 @@ import StoreFoundation
} }
} }
func downloadQueue(_ queue: CKDownloadQueue, changedWithAddition download: SSDownload) { func downloadQueue(_: CKDownloadQueue, changedWithAddition download: SSDownload) {
guard download.metadata.itemIdentifier == purchase.itemIdentifier else { guard download.metadata.itemIdentifier == purchase.itemIdentifier else {
return return
} }
@ -39,9 +39,9 @@ import StoreFoundation
printInfo("Downloading \(download.metadata.title)") printInfo("Downloading \(download.metadata.title)")
} }
func downloadQueue(_ queue: CKDownloadQueue, changedWithRemoval download: SSDownload) { func downloadQueue(_: CKDownloadQueue, changedWithRemoval download: SSDownload) {
guard download.metadata.itemIdentifier == purchase.itemIdentifier, guard download.metadata.itemIdentifier == purchase.itemIdentifier,
let status = download.status else { let status = download.status else {
return return
} }
@ -76,7 +76,7 @@ func progress(_ state: ProgressState) {
let completeLength = Int(state.percentComplete * Float(barLength)) let completeLength = Int(state.percentComplete * Float(barLength))
var bar = "" var bar = ""
for index in 0..<barLength { for index in 0 ..< barLength {
if index < completeLength { if index < completeLength {
bar += "#" bar += "#"
} else { } else {

View file

@ -15,11 +15,11 @@ typealias SSPurchaseCompletion =
extension SSPurchase { extension SSPurchase {
convenience init(adamId: UInt64, account: ISStoreAccount) { convenience init(adamId: UInt64, account: ISStoreAccount) {
self.init() self.init()
self.buyParameters = buyParameters =
"productType=C&price=0&salableAdamId=\(adamId)&pricingParameters=STDRDL&pg=default&appExtVrsId=0" "productType=C&price=0&salableAdamId=\(adamId)&pricingParameters=STDRDL&pg=default&appExtVrsId=0"
self.itemIdentifier = adamId itemIdentifier = adamId
self.accountIdentifier = account.dsID accountIdentifier = account.dsID
self.appleID = account.identifier appleID = account.identifier
let downloadMetadata = SSDownloadMetadata() let downloadMetadata = SSDownloadMetadata()
downloadMetadata.kind = "software" downloadMetadata.kind = "software"

View file

@ -18,7 +18,7 @@ public struct AccountCommand: CommandProtocol {
public init() {} public init() {}
/// Runs the command. /// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> { public func run(_: Options) -> Result<(), MASError> {
if let account = ISStoreAccount.primaryAccount { if let account = ISStoreAccount.primaryAccount {
print(String(describing: account.identifier)) print(String(describing: account.identifier))
} else { } else {

View file

@ -31,9 +31,9 @@ public struct HomeCommand: CommandProtocol {
public func run(_ options: HomeOptions) -> Result<(), MASError> { public func run(_ options: HomeOptions) -> Result<(), MASError> {
do { do {
guard let result = try storeSearch.lookup(app: options.appId) guard let result = try storeSearch.lookup(app: options.appId)
else { else {
print("No results found") print("No results found")
return .failure(.noSearchResultsFound) return .failure(.noSearchResultsFound)
} }
do { do {

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import Foundation import Foundation
import Result
/// Displays app details. Uses the iTunes Lookup API: /// Displays app details. Uses the iTunes Lookup API:
/// https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#lookup /// https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#lookup
@ -27,9 +27,9 @@ public struct InfoCommand: CommandProtocol {
public func run(_ options: InfoOptions) -> Result<(), MASError> { public func run(_ options: InfoOptions) -> Result<(), MASError> {
do { do {
guard let result = try storeSearch.lookup(app: options.appId) guard let result = try storeSearch.lookup(app: options.appId)
else { else {
print("No results found") print("No results found")
return .failure(.noSearchResultsFound) return .failure(.noSearchResultsFound)
} }
print(AppInfoFormatter.format(app: result)) print(AppInfoFormatter.format(app: result))

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import CommerceKit import CommerceKit
import Result
/// Installs previously purchased apps from the Mac App Store. /// Installs previously purchased apps from the Mac App Store.
public struct InstallCommand: CommandProtocol { public struct InstallCommand: CommandProtocol {
@ -54,7 +54,7 @@ public struct InstallOptions: OptionsProtocol {
public static func create(_ appIds: [Int]) -> (_ forceInstall: Bool) -> InstallOptions { public static func create(_ appIds: [Int]) -> (_ forceInstall: Bool) -> InstallOptions {
return { forceInstall in return { forceInstall in
return InstallOptions(appIds: appIds.map {UInt64($0)}, forceInstall: forceInstall) InstallOptions(appIds: appIds.map { UInt64($0) }, forceInstall: forceInstall)
} }
} }

View file

@ -25,7 +25,7 @@ public struct ListCommand: CommandProtocol {
} }
/// Runs the command. /// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> { public func run(_: Options) -> Result<(), MASError> {
let products = appLibrary.installedApps let products = appLibrary.installedApps
if products.isEmpty { if products.isEmpty {
print("No installed apps found") print("No installed apps found")

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import CommerceKit import CommerceKit
import Result
/// Command which installs the first search result. This is handy as many MAS titles /// Command which installs the first search result. This is handy as many MAS titles
/// can be long with embedded keywords. /// can be long with embedded keywords.
@ -89,7 +89,7 @@ public struct LuckyOptions: OptionsProtocol {
public static func create(_ appName: String) -> (_ forceInstall: Bool) -> LuckyOptions { public static func create(_ appName: String) -> (_ forceInstall: Bool) -> LuckyOptions {
return { forceInstall in return { forceInstall in
return LuckyOptions(appName: appName, forceInstall: forceInstall) LuckyOptions(appName: appName, forceInstall: forceInstall)
} }
} }

View file

@ -27,7 +27,7 @@ public struct OpenCommand: CommandProtocol {
public init(storeSearch: StoreSearch = MasStoreSearch(), public init(storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()) { openCommand: ExternalCommand = OpenSystemCommand()) {
self.storeSearch = storeSearch self.storeSearch = storeSearch
self.systemOpen = openCommand systemOpen = openCommand
} }
/// Runs the command. /// Runs the command.
@ -40,20 +40,20 @@ public struct OpenCommand: CommandProtocol {
} }
guard let appId = Int(options.appId) guard let appId = Int(options.appId)
else { else {
print("Invalid app ID") print("Invalid app ID")
return .failure(.noSearchResultsFound) return .failure(.noSearchResultsFound)
} }
guard let result = try storeSearch.lookup(app: appId) guard let result = try storeSearch.lookup(app: appId)
else { else {
print("No results found") print("No results found")
return .failure(.noSearchResultsFound) return .failure(.noSearchResultsFound)
} }
guard var url = URLComponents(string: result.trackViewUrl) guard var url = URLComponents(string: result.trackViewUrl)
else { else {
return .failure(.searchFailed) return .failure(.searchFailed)
} }
url.scheme = masScheme url.scheme = masScheme

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import CommerceKit import CommerceKit
import Result
/// Command which displays a list of installed apps which have available updates /// Command which displays a list of installed apps which have available updates
/// ready to be installed from the Mac App Store. /// ready to be installed from the Mac App Store.
@ -27,15 +27,15 @@ public struct OutdatedCommand: CommandProtocol {
} }
/// Runs the command. /// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> { public func run(_: Options) -> Result<(), MASError> {
let updateController = CKUpdateController.shared() let updateController = CKUpdateController.shared()
let updates = updateController?.availableUpdates() let updates = updateController?.availableUpdates()
for update in updates! { for update in updates! {
if let installed = appLibrary.installedApp(forBundleId: update.bundleID) { if let installed = appLibrary.installedApp(forBundleId: update.bundleID) {
// Display version of installed app compared to available update. // Display version of installed app compared to available update.
print(""" print("""
\(update.itemIdentifier) \(update.title) (\(installed.bundleVersion) -> \(update.bundleVersion)) \(update.itemIdentifier) \(update.title) (\(installed.bundleVersion) -> \(update.bundleVersion))
""") """)
} else { } else {
print("\(update.itemIdentifier) \(update.title) (unknown -> \(update.bundleVersion))") print("\(update.itemIdentifier) \(update.title) (unknown -> \(update.bundleVersion))")
} }

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import CommerceKit import CommerceKit
import Result
/// Kills several macOS processes as a means to reset the app store. /// Kills several macOS processes as a means to reset the app store.
public struct ResetCommand: CommandProtocol { public struct ResetCommand: CommandProtocol {
@ -21,22 +21,22 @@ public struct ResetCommand: CommandProtocol {
/// Runs the command. /// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> { public func run(_ options: Options) -> Result<(), MASError> {
/* /*
The "Reset Application" command in the Mac App Store debug menu performs The "Reset Application" command in the Mac App Store debug menu performs
the following steps the following steps
- killall Dock - killall Dock
- killall storeagent (storeagent no longer exists) - killall storeagent (storeagent no longer exists)
- rm com.apple.appstore download directory - rm com.apple.appstore download directory
- clear cookies (appears to be a no-op) - clear cookies (appears to be a no-op)
As storeagent no longer exists we will implement a slight variant and kill all As storeagent no longer exists we will implement a slight variant and kill all
App Store-associated processes App Store-associated processes
- storeaccountd - storeaccountd
- storeassetd - storeassetd
- storedownloadd - storedownloadd
- storeinstalld - storeinstalld
- storelegacy - storelegacy
*/ */
// Kill processes // Kill processes
let killProcs = [ let killProcs = [
@ -60,7 +60,7 @@ public struct ResetCommand: CommandProtocol {
kill.launch() kill.launch()
kill.waitUntilExit() kill.waitUntilExit()
if kill.terminationStatus != 0 && options.debug { if kill.terminationStatus != 0, options.debug {
let output = stderr.fileHandleForReading.readDataToEndOfFile() let output = stderr.fileHandleForReading.readDataToEndOfFile()
printInfo("killall failed:\r\n\(String(data: output, encoding: String.Encoding.utf8)!)") printInfo("killall failed:\r\n\(String(data: output, encoding: String.Encoding.utf8)!)")
} }

View file

@ -31,7 +31,7 @@ public struct SignInCommand: CommandProtocol {
printInfo("Signing in to Apple ID: \(options.username)") printInfo("Signing in to Apple ID: \(options.username)")
let password: String = { let password: String = {
if options.password == "" && !options.dialog { if options.password == "", !options.dialog {
return String(validatingUTF8: getpass("Password: "))! return String(validatingUTF8: getpass("Password: "))!
} }
return options.password return options.password
@ -56,8 +56,8 @@ public struct SignInOptions: OptionsProtocol {
static func create(username: String) -> (_ password: String) -> (_ dialog: Bool) -> SignInOptions { static func create(username: String) -> (_ password: String) -> (_ dialog: Bool) -> SignInOptions {
return { password in { dialog in return { password in { dialog in
return SignInOptions(username: username, password: password, dialog: dialog) SignInOptions(username: username, password: password, dialog: dialog)
}} } }
} }
public static func evaluate(_ mode: CommandMode) -> Result<SignInOptions, CommandantError<MASError>> { public static func evaluate(_ mode: CommandMode) -> Result<SignInOptions, CommandantError<MASError>> {

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import CommerceKit import CommerceKit
import Result
public struct SignOutCommand: CommandProtocol { public struct SignOutCommand: CommandProtocol {
public typealias Options = NoOptions<MASError> public typealias Options = NoOptions<MASError>
@ -18,7 +18,7 @@ public struct SignOutCommand: CommandProtocol {
public init() {} public init() {}
/// Runs the command. /// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> { public func run(_: Options) -> Result<(), MASError> {
if #available(macOS 10.13, *) { if #available(macOS 10.13, *) {
let accountService: ISAccountService = ISServiceProxy.genericShared().accountService let accountService: ISAccountService = ISServiceProxy.genericShared().accountService
accountService.signOut() accountService.signOut()

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import CommerceKit import CommerceKit
import Result
import StoreFoundation import StoreFoundation
/// Command which uninstalls apps managed by the Mac App Store. /// Command which uninstalls apps managed by the Mac App Store.
@ -64,7 +64,7 @@ public struct UninstallOptions: OptionsProtocol {
static func create(_ appId: Int) -> (_ dryRun: Bool) -> UninstallOptions { static func create(_ appId: Int) -> (_ dryRun: Bool) -> UninstallOptions {
return { dryRun in return { dryRun in
return UninstallOptions(appId: appId, dryRun: dryRun) UninstallOptions(appId: appId, dryRun: dryRun)
} }
} }

View file

@ -7,8 +7,8 @@
// //
import Commandant import Commandant
import Result
import CommerceKit import CommerceKit
import Result
/// Command which upgrades apps with new versions available in the Mac App Store. /// Command which upgrades apps with new versions available in the Mac App Store.
public struct UpgradeCommand: CommandProtocol { public struct UpgradeCommand: CommandProtocol {

View file

@ -31,13 +31,13 @@ public struct VendorCommand: CommandProtocol {
public func run(_ options: VendorOptions) -> Result<(), MASError> { public func run(_ options: VendorOptions) -> Result<(), MASError> {
do { do {
guard let result = try storeSearch.lookup(app: options.appId) guard let result = try storeSearch.lookup(app: options.appId)
else { else {
print("No results found") print("No results found")
return .failure(.noSearchResultsFound) return .failure(.noSearchResultsFound)
} }
guard let vendorWebsite = result.sellerUrl guard let vendorWebsite = result.sellerUrl
else { throw MASError.noVendorWebsite } else { throw MASError.noVendorWebsite }
do { do {
try openCommand.run(arguments: vendorWebsite) try openCommand.run(arguments: vendorWebsite)

View file

@ -18,7 +18,7 @@ public struct VersionCommand: CommandProtocol {
public init() {} public init() {}
/// Runs the command. /// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> { public func run(_: Options) -> Result<(), MASError> {
let plist = Bundle.main.infoDictionary let plist = Bundle.main.infoDictionary
if let versionString = plist?["CFBundleShortVersionString"] { if let versionString = plist?["CFBundleShortVersionString"] {
print(versionString) print(versionString)

View file

@ -17,7 +17,7 @@ public class MasAppLibrary: AppLibrary {
public lazy var installedApps: [SoftwareProduct] = { public lazy var installedApps: [SoftwareProduct] = {
var appList = [SoftwareProduct]() var appList = [SoftwareProduct]()
guard let products = softwareMap.allProducts() guard let products = softwareMap.allProducts()
else { return appList } else { return appList }
appList.append(contentsOf: products) appList.append(contentsOf: products)
return products return products
}() }()

View file

@ -22,17 +22,17 @@ public class MasStoreSearch: StoreSearch {
/// - Throws: Error if there is a problem with the network request. /// - Throws: Error if there is a problem with the network request.
public func search(for appName: String) throws -> SearchResultList { public func search(for appName: String) throws -> SearchResultList {
guard let url = searchURL(for: appName) guard let url = searchURL(for: appName)
else { throw MASError.urlEncoding } else { throw MASError.urlEncoding }
let result = networkManager.loadDataSync(from: url) let result = networkManager.loadDataSync(from: url)
// Unwrap network result // Unwrap network result
guard case let .success(data) = result guard case let .success(data) = result
else { else {
if case let .failure(error) = result { if case let .failure(error) = result {
throw error throw error
} }
throw MASError.noData throw MASError.noData
} }
do { do {
@ -50,24 +50,24 @@ public class MasStoreSearch: StoreSearch {
/// - Throws: Error if there is a problem with the network request. /// - Throws: Error if there is a problem with the network request.
public func lookup(app appId: Int) throws -> SearchResult? { public func lookup(app appId: Int) throws -> SearchResult? {
guard let url = lookupURL(forApp: appId) guard let url = lookupURL(forApp: appId)
else { throw MASError.urlEncoding } else { throw MASError.urlEncoding }
let result = networkManager.loadDataSync(from: url) let result = networkManager.loadDataSync(from: url)
// Unwrap network result // Unwrap network result
guard case let .success(data) = result guard case let .success(data) = result
else { else {
if case let .failure(error) = result { if case let .failure(error) = result {
throw error throw error
} }
throw MASError.noData throw MASError.noData
} }
do { do {
let results = try JSONDecoder().decode(SearchResultList.self, from: data) let results = try JSONDecoder().decode(SearchResultList.self, from: data)
guard let searchResult = results.results.first guard let searchResult = results.results.first
else { return nil } else { return nil }
return searchResult return searchResult
} catch { } catch {

View file

@ -41,7 +41,7 @@ public enum MASError: Error, CustomStringConvertible, Equatable {
"\nFor more info see: " + "\nFor more info see: " +
"https://github.com/mas-cli/mas/issues/164" "https://github.com/mas-cli/mas/issues/164"
case .signInFailed(let error): case let .signInFailed(error):
if let error = error { if let error = error {
return "Sign in failed: \(error.localizedDescription)" return "Sign in failed: \(error.localizedDescription)"
} else { } else {
@ -51,14 +51,14 @@ public enum MASError: Error, CustomStringConvertible, Equatable {
case .alreadySignedIn: case .alreadySignedIn:
return "Already signed in" return "Already signed in"
case .purchaseFailed(let error): case let .purchaseFailed(error):
if let error = error { if let error = error {
return "Download request failed: \(error.localizedDescription)" return "Download request failed: \(error.localizedDescription)"
} else { } else {
return "Download request failed" return "Download request failed"
} }
case .downloadFailed(let error): case let .downloadFailed(error):
if let error = error { if let error = error {
return "Download failed: \(error.localizedDescription)" return "Download failed: \(error.localizedDescription)"
} else { } else {

View file

@ -61,7 +61,7 @@ extension ExternalCommand {
try process.run() try process.run()
} catch { } catch {
printError("Unable to launch command") printError("Unable to launch command")
//return throw Error() // return throw Error()
} }
} else { } else {
process.launchPath = binaryPath process.launchPath = binaryPath

View file

@ -33,8 +33,7 @@ public struct SearchResult: Decodable {
trackCensoredName: String = "", trackCensoredName: String = "",
trackName: String = "", trackName: String = "",
trackViewUrl: String = "", trackViewUrl: String = "",
version: String = "" version: String = "") {
) {
self.bundleId = bundleId self.bundleId = bundleId
self.currentVersionReleaseDate = currentVersionReleaseDate self.currentVersionReleaseDate = currentVersionReleaseDate
self.fileSizeBytes = fileSizeBytes self.fileSizeBytes = fileSizeBytes

View file

@ -8,7 +8,7 @@
import Foundation import Foundation
/// Network abstraction /// Network abstraction
public class NetworkManager { public class NetworkManager {
enum NetworkError: Error { enum NetworkError: Error {
case timeout case timeout

View file

@ -14,10 +14,10 @@ enum NetworkResult {
extension NetworkResult: Equatable { extension NetworkResult: Equatable {
static func == (lhs: NetworkResult, rhs: NetworkResult) -> Bool { static func == (lhs: NetworkResult, rhs: NetworkResult) -> Bool {
switch (lhs, rhs) { switch (lhs, rhs) {
case (let .success(data1), let .success(data2)): case let (.success(data1), .success(data2)):
return data1 == data2 return data1 == data2
case (let .failure(error1), let .failure(error2)): case let (.failure(error1), .failure(error2)):
return error1.localizedDescription == error2.localizedDescription return error1.localizedDescription == error2.localizedDescription
// case (.none, .none): // case (.none, .none):

View file

@ -10,7 +10,7 @@ import Foundation
extension URLSession: NetworkSession { extension URLSession: NetworkSession {
@objc open func loadData(from url: URL, completionHandler: @escaping (Data?, Error?) -> Void) { @objc open func loadData(from url: URL, completionHandler: @escaping (Data?, Error?) -> Void) {
let task = dataTask(with: url) { (data, _, error) in let task = dataTask(with: url) { data, _, error in
completionHandler(data, error) completionHandler(data, error)
} }
task.resume() task.resume()

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class AccountCommandSpec: QuickSpec { class AccountCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class HomeCommandSpec: QuickSpec { class HomeCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class InfoCommandSpec: QuickSpec { class InfoCommandSpec: QuickSpec {
override func spec() { override func spec() {
@ -27,14 +27,14 @@ class InfoCommandSpec: QuickSpec {
let storeSearch = StoreSearchMock() let storeSearch = StoreSearchMock()
let cmd = InfoCommand(storeSearch: storeSearch) let cmd = InfoCommand(storeSearch: storeSearch)
let expectedOutput = """ let expectedOutput = """
Awesome App 1.0 [2.0] Awesome App 1.0 [2.0]
By: Awesome Dev By: Awesome Dev
Released: Jan 7, 2019 Released: Jan 7, 2019
Minimum OS: 10.14 Minimum OS: 10.14
Size: 1 KB Size: 1 KB
From: https://awesome.app From: https://awesome.app
""" """
describe("Info command") { describe("Info command") {
beforeEach { beforeEach {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class InstallCommandSpec: QuickSpec { class InstallCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class ListCommandSpec: QuickSpec { class ListCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class LuckyCommandSpec: QuickSpec { class LuckyCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class OpenCommandSpec: QuickSpec { class OpenCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class OutdatedCommandSpec: QuickSpec { class OutdatedCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class ResetCommandSpec: QuickSpec { class ResetCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class SearchCommandSpec: QuickSpec { class SearchCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class SignInCommandSpec: QuickSpec { class SignInCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class SignOutCommandSpec: QuickSpec { class SignOutCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class UninstallCommandSpec: QuickSpec { class UninstallCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class UpgradeCommandSpec: QuickSpec { class UpgradeCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class VendorCommandSpec: QuickSpec { class VendorCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class VersionCommandSpec: QuickSpec { class VersionCommandSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -15,13 +15,13 @@ class AppLibraryMock: AppLibrary {
/// ///
/// - Parameter bundleId: Bundle identifier of app. /// - Parameter bundleId: Bundle identifier of app.
/// - Returns: Software Product of app if found; nil otherwise. /// - Returns: Software Product of app if found; nil otherwise.
public func installedApp(forBundleId bundleId: String) -> SoftwareProduct? { public func installedApp(forBundleId _: String) -> SoftwareProduct? {
return nil return nil
} }
func uninstallApp(app: SoftwareProduct) throws { func uninstallApp(app: SoftwareProduct) throws {
if !installedApps.contains(where: { (product) -> Bool in if !installedApps.contains(where: { (product) -> Bool in
return app.itemIdentifier == product.itemIdentifier app.itemIdentifier == product.itemIdentifier
}) { throw MASError.notInstalled } }) { throw MASError.notInstalled }
// Special case for testing where we pretend the trash command failed // Special case for testing where we pretend the trash command failed

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class MasStoreSearchSpec: QuickSpec { class MasStoreSearchSpec: QuickSpec {
override func spec() { override func spec() {
@ -25,7 +25,7 @@ class MasStoreSearchSpec: QuickSpec {
expect(searchList.results.count) == 6 expect(searchList.results.count) == 6
} catch { } catch {
let maserror = error as! MASError let maserror = error as! MASError
if case .jsonParsing(let nserror) = maserror { if case let .jsonParsing(nserror) = maserror {
fail("\(maserror) \(nserror!)") fail("\(maserror) \(nserror!)")
} }
} }
@ -33,7 +33,7 @@ class MasStoreSearchSpec: QuickSpec {
} }
describe("store lookup") { describe("store lookup") {
it("can find slack") { it("can find slack") {
let appId = 803453959 let appId = 803_453_959
let networkSession = NetworkSessionMockFromFile(responseFile: "lookup/slack.json") let networkSession = NetworkSessionMockFromFile(responseFile: "lookup/slack.json")
let storeSearch = MasStoreSearch(networkManager: NetworkManager(session: networkSession)) let storeSearch = MasStoreSearch(networkManager: NetworkManager(session: networkSession))
@ -42,7 +42,7 @@ class MasStoreSearchSpec: QuickSpec {
lookup = try storeSearch.lookup(app: appId) lookup = try storeSearch.lookup(app: appId)
} catch { } catch {
let maserror = error as! MASError let maserror = error as! MASError
if case .jsonParsing(let nserror) = maserror { if case let .jsonParsing(nserror) = maserror {
fail("\(maserror) \(nserror!)") fail("\(maserror) \(nserror!)")
} }
} }

View file

@ -23,7 +23,7 @@ class StoreSearchMock: StoreSearch {
} }
guard let result = apps[appId] guard let result = apps[appId]
else { throw MASError.noSearchResultsFound } else { throw MASError.noSearchResultsFound }
return result return result
} }

View file

@ -6,14 +6,14 @@
// Copyright © 2019 mas-cli. All rights reserved. // Copyright © 2019 mas-cli. All rights reserved.
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
/// Protocol minimal implementation /// Protocol minimal implementation
struct StoreSearchForTesting: StoreSearch { struct StoreSearchForTesting: StoreSearch {
func lookup(app appId: Int) throws -> SearchResult? { return nil } func lookup(app _: Int) throws -> SearchResult? { return nil }
func search(for appName: String) throws -> SearchResultList { return SearchResultList(resultCount: 0, results: []) } func search(for _: String) throws -> SearchResultList { return SearchResultList(resultCount: 0, results: []) }
} }
class StoreSearchSpec: QuickSpec { class StoreSearchSpec: QuickSpec {
@ -25,14 +25,14 @@ class StoreSearchSpec: QuickSpec {
let appName = "myapp" let appName = "myapp"
let urlString = storeSearch.searchURLString(forApp: appName) let urlString = storeSearch.searchURLString(forApp: appName)
expect(urlString) == expect(urlString) ==
"https://itunes.apple.com/search?entity=macSoftware&term=\(appName)&attribute=allTrackTerm" "https://itunes.apple.com/search?entity=macSoftware&term=\(appName)&attribute=allTrackTerm"
} }
it("contains the encoded app name") { it("contains the encoded app name") {
let appName = "My App" let appName = "My App"
let appNameEncoded = "My%20App" let appNameEncoded = "My%20App"
let urlString = storeSearch.searchURLString(forApp: appName) let urlString = storeSearch.searchURLString(forApp: appName)
expect(urlString) == expect(urlString) ==
"https://itunes.apple.com/search?entity=macSoftware&term=\(appNameEncoded)&attribute=allTrackTerm" "https://itunes.apple.com/search?entity=macSoftware&term=\(appNameEncoded)&attribute=allTrackTerm"
} }
// Find a character that causes addingPercentEncoding(withAllowedCharacters to return nil // Find a character that causes addingPercentEncoding(withAllowedCharacters to return nil
xit("is nil when app name cannot be url encoded") { xit("is nil when app name cannot be url encoded") {

View file

@ -7,8 +7,8 @@
// //
@testable import MasKit @testable import MasKit
import XCTest
import Foundation import Foundation
import XCTest
class MASErrorTestCase: XCTestCase { class MASErrorTestCase: XCTestCase {
private let errorDomain = "MAS" private let errorDomain = "MAS"
@ -21,8 +21,8 @@ class MASErrorTestCase: XCTestCase {
var localizedDescription: String { var localizedDescription: String {
get { return "dummy value" } get { return "dummy value" }
set { set {
NSError.setUserInfoValueProvider(forDomain: errorDomain) { (error: Error, userInfoKey: String) -> Any? in NSError.setUserInfoValueProvider(forDomain: errorDomain) { (_: Error, _: String) -> Any? in
return newValue newValue
} }
} }
} }

View file

@ -25,7 +25,7 @@ extension Bundle {
guard let path = self.path(forResource: fileName.fileNameWithoutExtension, guard let path = self.path(forResource: fileName.fileNameWithoutExtension,
ofType: fileName.fileExtension, ofType: fileName.fileExtension,
inDirectory: "JSON") inDirectory: "JSON")
else { fatalError("Unable to load file \(fileName)") } else { fatalError("Unable to load file \(fileName)") }
return URL(fileURLWithPath: path) return URL(fileURLWithPath: path)
} }

View file

@ -7,9 +7,9 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Quick
import Nimble import Nimble
import Quick
import Result
class SearchResultsFormatterSpec: QuickSpec { class SearchResultsFormatterSpec: QuickSpec {
override func spec() { override func spec() {

View file

@ -23,7 +23,7 @@ class NetworkSessionMock: NetworkSession {
/// - url: unused /// - url: unused
/// - completionHandler: Closure which is delivered both data and error properties (only one should be non-nil) /// - completionHandler: Closure which is delivered both data and error properties (only one should be non-nil)
/// - Returns: Mock data task /// - Returns: Mock data task
func dataTask(with url: URL, completionHandler: @escaping CompletionHandler) -> URLSessionDataTask { func dataTask(with _: URL, completionHandler: @escaping CompletionHandler) -> URLSessionDataTask {
let data = self.data let data = self.data
let error = self.error let error = self.error
@ -37,7 +37,7 @@ class NetworkSessionMock: NetworkSession {
/// - Parameters: /// - Parameters:
/// - url: unused /// - url: unused
/// - completionHandler: Closure which is delivered either data or an error. /// - completionHandler: Closure which is delivered either data or an error.
@objc func loadData(from url: URL, completionHandler: @escaping (Data?, Error?) -> Void) { @objc func loadData(from _: URL, completionHandler: @escaping (Data?, Error?) -> Void) {
completionHandler(data, error) completionHandler(data, error)
} }
} }

View file

@ -25,9 +25,9 @@ class NetworkSessionMockFromFile: NetworkSessionMock {
/// - Parameters: /// - Parameters:
/// - url: unused /// - url: unused
/// - completionHandler: Closure which is delivered either data or an error. /// - completionHandler: Closure which is delivered either data or an error.
@objc override func loadData(from url: URL, completionHandler: @escaping (Data?, Error?) -> Void) { @objc override func loadData(from _: URL, completionHandler: @escaping (Data?, Error?) -> Void) {
guard let fileURL = Bundle.jsonResponse(fileName: responseFile) guard let fileURL = Bundle.jsonResponse(fileName: responseFile)
else { fatalError("Unable to load file \(responseFile)") } else { fatalError("Unable to load file \(responseFile)") }
do { do {
let data = try Data(contentsOf: fileURL, options: .mappedIfSafe) let data = try Data(contentsOf: fileURL, options: .mappedIfSafe)

View file

@ -10,13 +10,12 @@ import Foundation
/// Delegate for network requests initiated from tests. /// Delegate for network requests initiated from tests.
class TestURLSessionDelegate: NSObject, URLSessionDelegate { class TestURLSessionDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, func urlSession(_: URLSession,
didReceive challenge: URLAuthenticationChallenge, didReceive challenge: URLAuthenticationChallenge,
completionHandler: (URLSession.AuthChallengeDisposition, completionHandler: (URLSession.AuthChallengeDisposition,
URLCredential?) -> Void) { URLCredential?) -> Void) {
// For example, you may want to override this to accept some self-signed certs here. // For example, you may want to override this to accept some self-signed certs here.
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
Constants.selfSignedHosts.contains(challenge.protectionSpace.host) { Constants.selfSignedHosts.contains(challenge.protectionSpace.host) {
// Allow the self-signed cert. // Allow the self-signed cert.
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)

View file

@ -14,7 +14,7 @@ extension URLSessionConfiguration {
/// newly created session configuration object, customised /// newly created session configuration object, customised
/// from the default to your requirements. /// from the default to your requirements.
class func testSessionConfiguration() -> URLSessionConfiguration { class func testSessionConfiguration() -> URLSessionConfiguration {
let config = self.default let config = `default`
// Eg we think 60s is too long a timeout time. // Eg we think 60s is too long a timeout time.
config.timeoutIntervalForRequest = 20 config.timeoutIntervalForRequest = 20

View file

@ -7,8 +7,8 @@
// //
@testable import MasKit @testable import MasKit
import Result
import Nimble import Nimble
import Result
/// Nimble predicate for result enum success case, no associated value /// Nimble predicate for result enum success case, no associated value
func beSuccess() -> Predicate<Result<(), MASError>> { func beSuccess() -> Predicate<Result<(), MASError>> {

View file

@ -6,8 +6,8 @@
// Copyright © 2019 mas-cli. All rights reserved. // Copyright © 2019 mas-cli. All rights reserved.
// //
import Quick
import Nimble import Nimble
import Quick
class OutputListenerSpec: QuickSpec { class OutputListenerSpec: QuickSpec {
override func spec() { override func spec() {
@ -31,9 +31,9 @@ class OutputListenerSpec: QuickSpec {
output.openConsolePipe() output.openConsolePipe()
let expectedOutput = """ let expectedOutput = """
hi there hi there
""" """
print("hi there") print("hi there")

View file

@ -40,7 +40,7 @@ let cool = yTown(5) { $0 == 6 }
// Use full variable names when closures are more complex // Use full variable names when closures are more complex
let cool = yTown(5) { foo in let cool = yTown(5) { foo in
if foo > 5 && foo < 0 { if foo > 5, foo < 0 {
return true return true
} else { } else {
return false return false
@ -81,7 +81,7 @@ case let .failure(error):
// Group methods into specific extensions for each level of access control // Group methods into specific extensions for each level of access control
private extension MyClass { private extension MyClass {
func doSomethingPrivate() { } func doSomethingPrivate() {}
} }
// MARK: Breaking up long lines // MARK: Breaking up long lines
@ -94,7 +94,7 @@ guard statementThatShouldBeTrue else { return }
// move else to next line // move else to next line
guard let oneItem = somethingFailable(), guard let oneItem = somethingFailable(),
let secondItem = somethingFailable2() let secondItem = somethingFailable2()
else { return } else { return }
// If the return in else is long, move to next line // If the return in else is long, move to next line
guard let something = somethingFailable() else { guard let something = somethingFailable() else {

View file

@ -6,9 +6,9 @@
// Copyright © 2015 Andrew Naylor. All rights reserved. // Copyright © 2015 Andrew Naylor. All rights reserved.
// //
import MasKit
import Commandant import Commandant
import Foundation import Foundation
import MasKit
public struct StderrOutputStream: TextOutputStream { public struct StderrOutputStream: TextOutputStream {
public mutating func write(_ string: String) { public mutating func write(_ string: String) {