🧹 Lint with swift-format

This commit is contained in:
Chris Araman 2021-03-21 22:25:18 -07:00
parent 09d2e6d43d
commit df9730d65f
No known key found for this signature in database
GPG key ID: BB4499D9E11B61E0
58 changed files with 354 additions and 225 deletions

41
.swift-format Normal file
View file

@ -0,0 +1,41 @@
{
"indentation" : {
"spaces" : 4
},
"lineLength" : 120,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLowerCamelCase" : true,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : true,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : false,
"NeverUseForceTry" : false,
"NeverUseImplicitlyUnwrappedOptionals" : false,
"NoAccessLevelOnExtensionDeclaration" : false,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : true,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"UseLetInEveryBoundCaseVariable" : true,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : true,
"UseSynthesizedInitializer" : true,
"UseTripleSlashForDocumentationComments" : true,
"ValidateDocumentationComments" : false
},
"version" : 1
}

View file

@ -5,7 +5,7 @@
# https://github.com/nicklockwood/SwiftFormat#config-file
#
--exclude Carthage/
--exclude Carthage/,docs/
# Disabled rules
--disable blankLinesAroundMark
@ -15,4 +15,5 @@
# Rule options
--commas inline
--importgrouping testable-top
--guardelse same-line
--importgrouping testable-last

View file

@ -8,3 +8,9 @@
excluded:
- Carthage
- docs
opening_brace:
allow_multiline_func: true
trailing_comma:
mandatory_comma: true

View file

@ -21,7 +21,7 @@ func download(_ adamId: UInt64, purchase: Bool = false) -> MASError? {
}
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, purchase: purchase)
var purchaseError: MASError?

View file

@ -20,8 +20,9 @@ import StoreFoundation
func downloadQueue(_ queue: CKDownloadQueue, statusChangedFor download: SSDownload) {
guard download.metadata.itemIdentifier == purchase.itemIdentifier,
let status = download.status else {
return
let status = download.status
else {
return
}
if status.isFailed || status.isCancelled {
@ -41,8 +42,9 @@ import StoreFoundation
func downloadQueue(_: CKDownloadQueue, changedWithRemoval download: SSDownload) {
guard download.metadata.itemIdentifier == purchase.itemIdentifier,
let status = download.status else {
return
let status = download.status
else {
return
}
clearLine()
@ -76,7 +78,7 @@ func progress(_ state: ProgressState) {
let completeLength = Int(state.percentComplete * Float(barLength))
var bar = ""
for index in 0 ..< barLength {
for index in 0..<barLength {
if index < completeLength {
bar += "#"
} else {

View file

@ -21,7 +21,7 @@ extension SSPurchase {
"price": 0,
"salableAdamId": adamId,
"pg": "default",
"appExtVrsId": 0
"appExtVrsId": 0,
]
if purchase {
@ -33,9 +33,11 @@ extension SSPurchase {
parameters["pricingParameters"] = "STDRDL"
}
buyParameters = parameters.map { key, value in
return "\(key)=\(value)"
}.joined(separator: "&")
buyParameters =
parameters.map { key, value in
return "\(key)=\(value)"
}
.joined(separator: "&")
itemIdentifier = adamId
accountIdentifier = account.dsID

View file

@ -20,8 +20,10 @@ public struct HomeCommand: CommandProtocol {
private var openCommand: ExternalCommand
/// Designated initializer.
public init(storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()) {
public init(
storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()
) {
self.storeSearch = storeSearch
self.openCommand = openCommand
}

View file

@ -28,8 +28,10 @@ public struct LuckyCommand: CommandProtocol {
/// Internal initializer.
/// - Parameter appLibrary: AppLibrary manager.
/// - Parameter storeSearch: Search manager.
init(appLibrary: AppLibrary = MasAppLibrary(),
storeSearch: StoreSearch = MasStoreSearch()) {
init(
appLibrary: AppLibrary = MasAppLibrary(),
storeSearch: StoreSearch = MasStoreSearch()
) {
self.appLibrary = appLibrary
self.storeSearch = storeSearch
}
@ -67,14 +69,15 @@ public struct LuckyCommand: CommandProtocol {
/// - Returns: Result of the operation.
fileprivate func install(_ appId: UInt64, options: Options) -> Result<(), MASError> {
// Try to download applications with given identifiers and collect results
let downloadResults = [appId].compactMap { (appId) -> MASError? in
if let product = appLibrary.installedApp(forId: appId), !options.forceInstall {
printWarning("\(product.appName) is already installed")
return nil
}
let downloadResults = [appId]
.compactMap { (appId) -> MASError? in
if let product = appLibrary.installedApp(forId: appId), !options.forceInstall {
printWarning("\(product.appName) is already installed")
return nil
}
return download(appId)
}
return download(appId)
}
switch downloadResults.count {
case 0:

View file

@ -23,8 +23,10 @@ public struct OpenCommand: CommandProtocol {
private var systemOpen: ExternalCommand
/// Designated initializer.
public init(storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()) {
public init(
storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()
) {
self.storeSearch = storeSearch
systemOpen = openCommand
}
@ -39,20 +41,20 @@ public struct OpenCommand: CommandProtocol {
}
guard let appId = Int(options.appId)
else {
print("Invalid app ID")
return .failure(.noSearchResultsFound)
else {
print("Invalid app ID")
return .failure(.noSearchResultsFound)
}
guard let result = try storeSearch.lookup(app: appId)
else {
print("No results found")
return .failure(.noSearchResultsFound)
else {
print("No results found")
return .failure(.noSearchResultsFound)
}
guard var url = URLComponents(string: result.trackViewUrl)
else {
return .failure(.searchFailed)
else {
return .failure(.searchFailed)
}
url.scheme = masScheme

View file

@ -37,14 +37,16 @@ public struct OutdatedCommand: CommandProtocol {
do {
if let storeApp = try storeSearch.lookup(app: installedApp.itemIdentifier.intValue) {
if installedApp.bundleVersion != storeApp.version {
print("""
\(installedApp.itemIdentifier) \(installedApp.appName) (\(installedApp.bundleVersion) -> \(storeApp.version))
""")
print(
"""
\(installedApp.itemIdentifier) \(installedApp.appName) (\(installedApp.bundleVersion) -> \(storeApp.version))
""")
}
} else {
printWarning("""
Identifier \(installedApp.itemIdentifier) not found in store. Was expected to identify \(installedApp.appName).
""")
printWarning(
"""
Identifier \(installedApp.itemIdentifier) not found in store. Was expected to identify \(installedApp.appName).
""")
}
} catch {
// Bubble up MASErrors

View file

@ -44,7 +44,7 @@ public struct ResetCommand: CommandProtocol {
"storeassetd",
"storedownloadd",
"storeinstalld",
"storelegacy"
"storelegacy",
]
let kill = Process()

View file

@ -54,9 +54,7 @@ public struct SignInOptions: OptionsProtocol {
let dialog: Bool
static func create(username: String) -> (_ password: String) -> (_ dialog: Bool) -> SignInOptions {
return { password in { dialog in
SignInOptions(username: username, password: password, dialog: dialog)
} }
{ password in { dialog in SignInOptions(username: username, password: password, dialog: dialog) } }
}
public static func evaluate(_ mode: CommandMode) -> Result<SignInOptions, CommandantError<MASError>> {

View file

@ -34,19 +34,19 @@ public struct UpgradeCommand: CommandProtocol {
public func run(_ options: Options) -> Result<(), MASError> {
do {
let apps =
try (
options.apps.count == 0
? appLibrary.installedApps
: options.apps.compactMap {
if let appId = UInt64($0) {
// if argument a UInt64, lookup app by id using argument
return appLibrary.installedApp(forId: appId)
} else {
// if argument not a UInt64, lookup app by name using argument
return appLibrary.installedApp(named: $0)
}
}
).compactMap {(installedApp: SoftwareProduct) -> SoftwareProduct? in
try
(options.apps.count == 0
? appLibrary.installedApps
: options.apps.compactMap {
if let appId = UInt64($0) {
// if argument a UInt64, lookup app by id using argument
return appLibrary.installedApp(forId: appId)
} else {
// if argument not a UInt64, lookup app by name using argument
return appLibrary.installedApp(named: $0)
}
})
.compactMap { (installedApp: SoftwareProduct) -> SoftwareProduct? in
// only upgrade apps whose local version differs from the store version
if let storeApp = try storeSearch.lookup(app: installedApp.itemIdentifier.intValue) {
return storeApp.version != installedApp.bundleVersion
@ -63,7 +63,7 @@ public struct UpgradeCommand: CommandProtocol {
}
print("Upgrading \(apps.count) outdated application\(apps.count > 1 ? "s" : ""):")
print(apps.map {"\($0.appName) (\($0.bundleVersion))"}.joined(separator: ", "))
print(apps.map { "\($0.appName) (\($0.bundleVersion))" }.joined(separator: ", "))
var updatedAppCount = 0
var failedUpgradeResults = [MASError]()

View file

@ -20,8 +20,10 @@ public struct VendorCommand: CommandProtocol {
private var openCommand: ExternalCommand
/// Designated initializer.
public init(storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()) {
public init(
storeSearch: StoreSearch = MasStoreSearch(),
openCommand: ExternalCommand = OpenSystemCommand()
) {
self.storeSearch = storeSearch
self.openCommand = openCommand
}
@ -30,13 +32,13 @@ public struct VendorCommand: CommandProtocol {
public func run(_ options: VendorOptions) -> Result<(), MASError> {
do {
guard let result = try storeSearch.lookup(app: options.appId)
else {
print("No results found")
return .failure(.noSearchResultsFound)
else {
print("No results found")
return .failure(.noSearchResultsFound)
}
guard let vendorWebsite = result.sellerUrl
else { throw MASError.noVendorWebsite }
else { throw MASError.noVendorWebsite }
do {
try openCommand.run(arguments: vendorWebsite)

View file

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

View file

@ -39,10 +39,12 @@ extension MASError: CustomStringConvertible {
return "Not signed in"
case .signInDisabled:
return "The 'signin' command has been disabled on this macOS version. " +
"Please sign into the Mac App Store app manually." +
"\nFor more info see: " +
"https://github.com/mas-cli/mas/issues/164"
return """
The 'signin' command has been disabled on this macOS version. \
Please sign into the Mac App Store app manually.
For more info see: \
https://github.com/mas-cli/mas/issues/164
"""
case let .signInFailed(error):
if let error = error {

View file

@ -18,8 +18,9 @@ struct AppInfoFormatter {
let headline = [
"\(app.trackName)",
"\(app.version)",
"[\(app.price ?? 0)]"
].joined(separator: " ")
"[\(app.price ?? 0)]",
]
.joined(separator: " ")
return [
headline,
@ -27,8 +28,9 @@ struct AppInfoFormatter {
"Released: \(humanReadableDate(app.currentVersionReleaseDate))",
"Minimum OS: \(app.minimumOsVersion)",
"Size: \(humanReadableSize(app.fileSizeBytes ?? "0"))",
"From: \(app.trackViewUrl)"
].joined(separator: "\n")
"From: \(app.trackViewUrl)",
]
.joined(separator: "\n")
}
/// Formats a file size.

View file

@ -20,8 +20,10 @@ struct AppListFormatter {
/// - Returns: Multiliune text outoutp.
static func format(products: [SoftwareProduct]) -> String {
// find longest appName for formatting, default 50
let maxLength = products.map { $0.appNameOrBbundleIdentifier }
.max(by: { $1.count > $0.count })?.count
let maxLength =
products.map { $0.appNameOrBbundleIdentifier }
.max(by: { $1.count > $0.count })?
.count
?? nameColumnMinWidth
var output: String = ""

View file

@ -16,7 +16,8 @@ struct SearchResultFormatter {
/// - Returns: Multiliune text outoutp.
static func format(results: [SearchResult], includePrice: Bool = false) -> String {
// find longest appName for formatting, default 50
let maxLength = results.map { $0.trackName }.max(by: { $1.count > $0.count })?.count
let maxLength =
results.map { $0.trackName }.max(by: { $1.count > $0.count })?.count
?? 50
var output: String = ""

View file

@ -21,19 +21,21 @@ public struct SearchResult: Decodable {
public var trackViewUrl: String
public var version: String
init(bundleId: String = "",
currentVersionReleaseDate: String = "",
fileSizeBytes: String = "0",
formattedPrice: String = "Free",
minimumOsVersion: String = "",
price: Double = 0.0,
sellerName: String = "",
sellerUrl: String = "",
trackId: Int = 0,
trackCensoredName: String = "",
trackName: String = "",
trackViewUrl: String = "",
version: String = "") {
init(
bundleId: String = "",
currentVersionReleaseDate: String = "",
fileSizeBytes: String = "0",
formattedPrice: String = "Free",
minimumOsVersion: String = "",
price: Double = 0.0,
sellerName: String = "",
sellerUrl: String = "",
trackId: Int = 0,
trackCensoredName: String = "",
trackName: String = "",
trackViewUrl: String = "",
version: String = ""
) {
self.bundleId = bundleId
self.currentVersionReleaseDate = currentVersionReleaseDate
self.fileSizeBytes = fileSizeBytes

View file

@ -30,7 +30,8 @@ public class NetworkManager {
/// - completionHandler: Closure where result is delivered.
func loadData(from url: URL, completionHandler: @escaping (NetworkResult) -> Void) {
session.loadData(from: url) { (data: Data?, error: Error?) in
let result: NetworkResult = data != nil
let result: NetworkResult =
data != nil
? .success(data!)
: .failure(error!)
completionHandler(result)

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class AccountCommandSpec: QuickSpec {
override func spec() {
describe("Account command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class HomeCommandSpec: QuickSpec {
override func spec() {
let result = SearchResult(
@ -27,15 +28,19 @@ class HomeCommandSpec: QuickSpec {
}
it("fails to open app with invalid ID") {
let result = cmd.run(HomeCommand.Options(appId: -999))
expect(result).to(beFailure { error in
expect(error) == .searchFailed
})
expect(result)
.to(
beFailure { error in
expect(error) == .searchFailed
})
}
it("can't find app with unknown ID") {
let result = cmd.run(HomeCommand.Options(appId: 999))
expect(result).to(beFailure { error in
expect(error) == .noSearchResultsFound
})
expect(result)
.to(
beFailure { error in
expect(error) == .noSearchResultsFound
})
}
it("opens app on MAS Preview") {
storeSearch.apps[result.trackId] = result

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class InfoCommandSpec: QuickSpec {
override func spec() {
let result = SearchResult(
@ -26,14 +27,14 @@ class InfoCommandSpec: QuickSpec {
let storeSearch = StoreSearchMock()
let cmd = InfoCommand(storeSearch: storeSearch)
let expectedOutput = """
Awesome App 1.0 [2.0]
By: Awesome Dev
Released: 2019-01-07
Minimum OS: 10.14
Size: 1 KB
From: https://awesome.app
Awesome App 1.0 [2.0]
By: Awesome Dev
Released: 2019-01-07
Minimum OS: 10.14
Size: 1 KB
From: https://awesome.app
"""
"""
describe("Info command") {
beforeEach {
@ -41,15 +42,19 @@ class InfoCommandSpec: QuickSpec {
}
it("fails to open app with invalid ID") {
let result = cmd.run(InfoCommand.Options(appId: -999))
expect(result).to(beFailure { error in
expect(error) == .searchFailed
})
expect(result)
.to(
beFailure { error in
expect(error) == .searchFailed
})
}
it("can't find app with unknown ID") {
let result = cmd.run(InfoCommand.Options(appId: 999))
expect(result).to(beFailure { error in
expect(error) == .noSearchResultsFound
})
expect(result)
.to(
beFailure { error in
expect(error) == .noSearchResultsFound
})
}
it("displays app details") {
storeSearch.apps[result.trackId] = result

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class InstallCommandSpec: QuickSpec {
override func spec() {
describe("install command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class ListCommandSpec: QuickSpec {
override func spec() {
describe("list command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class LuckyCommandSpec: QuickSpec {
override func spec() {
describe("lucky command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2019 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class OpenCommandSpec: QuickSpec {
override func spec() {
let result = SearchResult(
@ -27,15 +28,19 @@ class OpenCommandSpec: QuickSpec {
}
it("fails to open app with invalid ID") {
let result = cmd.run(OpenCommand.Options(appId: "-999"))
expect(result).to(beFailure { error in
expect(error) == .searchFailed
})
expect(result)
.to(
beFailure { error in
expect(error) == .searchFailed
})
}
it("can't find app with unknown ID") {
let result = cmd.run(OpenCommand.Options(appId: "999"))
expect(result).to(beFailure { error in
expect(error) == .noSearchResultsFound
})
expect(result)
.to(
beFailure { error in
expect(error) == .noSearchResultsFound
})
}
it("opens app in MAS") {
storeSearch.apps[result.trackId] = result

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class OutdatedCommandSpec: QuickSpec {
override func spec() {
describe("outdated command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2020 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class PurchaseCommandSpec: QuickSpec {
override func spec() {
describe("purchase command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class ResetCommandSpec: QuickSpec {
override func spec() {
describe("reset command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class SearchCommandSpec: QuickSpec {
override func spec() {
let result = SearchResult(
@ -36,9 +37,11 @@ class SearchCommandSpec: QuickSpec {
let search = SearchCommand(storeSearch: storeSearch)
let searchOptions = SearchOptions(appName: "nonexistent", price: false)
let result = search.run(searchOptions)
expect(result).to(beFailure { error in
expect(error) == .noSearchResultsFound
})
expect(result)
.to(
beFailure { error in
expect(error) == .noSearchResultsFound
})
}
}
}

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class SignInCommandSpec: QuickSpec {
override func spec() {
describe("signn command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class SignOutCommandSpec: QuickSpec {
override func spec() {
describe("signout command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class UninstallCommandSpec: QuickSpec {
override func spec() {
describe("uninstall command") {
@ -32,9 +33,11 @@ class UninstallCommandSpec: QuickSpec {
}
it("can't remove a missing app") {
let result = uninstall.run(options)
expect(result).to(beFailure { error in
expect(error) == .notInstalled
})
expect(result)
.to(
beFailure { error in
expect(error) == .notInstalled
})
}
it("finds an app") {
mockLibrary.installedApps.append(app)
@ -51,9 +54,11 @@ class UninstallCommandSpec: QuickSpec {
}
it("can't remove a missing app") {
let result = uninstall.run(options)
expect(result).to(beFailure { error in
expect(error) == .notInstalled
})
expect(result)
.to(
beFailure { error in
expect(error) == .notInstalled
})
}
it("removes an app") {
mockLibrary.installedApps.append(app)
@ -62,14 +67,16 @@ class UninstallCommandSpec: QuickSpec {
expect(result).to(beSuccess())
}
it("fails if there is a problem with the trash command") {
var brokenUninstall = app // make mutable copy
var brokenUninstall = app // make mutable copy
brokenUninstall.bundlePath = "/dev/null"
mockLibrary.installedApps.append(brokenUninstall)
let result = uninstall.run(options)
expect(result).to(beFailure { error in
expect(error) == .uninstallFailed
})
expect(result)
.to(
beFailure { error in
expect(error) == .uninstallFailed
})
}
}
}

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class UpgradeCommandSpec: QuickSpec {
override func spec() {
describe("upgrade command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2019 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class VendorCommandSpec: QuickSpec {
override func spec() {
let result = SearchResult(
@ -27,15 +28,19 @@ class VendorCommandSpec: QuickSpec {
}
it("fails to open app with invalid ID") {
let result = cmd.run(VendorCommand.Options(appId: -999))
expect(result).to(beFailure { error in
expect(error) == .searchFailed
})
expect(result)
.to(
beFailure { error in
expect(error) == .searchFailed
})
}
it("can't find app with unknown ID") {
let result = cmd.run(VendorCommand.Options(appId: 999))
expect(result).to(beFailure { error in
expect(error) == .noSearchResultsFound
})
expect(result)
.to(
beFailure { error in
expect(error) == .noSearchResultsFound
})
}
it("opens vendor app page in browser") {
storeSearch.apps[result.trackId] = result

View file

@ -6,10 +6,11 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class VersionCommandSpec: QuickSpec {
override func spec() {
describe("version command") {

View file

@ -22,7 +22,9 @@ class AppLibraryMock: AppLibrary {
func uninstallApp(app: SoftwareProduct) throws {
if !installedApps.contains(where: { (product) -> Bool in
app.itemIdentifier == product.itemIdentifier
}) { throw MASError.notInstalled }
}) {
throw MASError.notInstalled
}
// Special case for testing where we pretend the trash command failed
if app.bundlePath == "/dev/null" {

View file

@ -6,10 +6,11 @@
// Copyright © 2020 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class MasAppLibrarySpec: QuickSpec {
override func spec() {
let library = MasAppLibrary(softwareMap: SoftwareMapMock(products: apps))
@ -35,9 +36,7 @@ let myApp = SoftwareProductMock(
bundleVersion: "",
itemIdentifier: 1234)
var apps: [SoftwareProduct] = [
myApp
]
var apps: [SoftwareProduct] = [myApp]
// MARK: - SoftwareMapMock
struct SoftwareMapMock: SoftwareMap {

View file

@ -6,10 +6,11 @@
// Copyright © 2019 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class MasStoreSearchSpec: QuickSpec {
override func spec() {
describe("store") {

View file

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

View file

@ -5,10 +5,11 @@
// Created by Ben Chatelain on 1/11/19.
// Copyright © 2019 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
/// Protocol minimal implementation
struct StoreSearchForTesting: StoreSearch {
func lookup(app _: Int) throws -> SearchResult? { return nil }
@ -23,15 +24,14 @@ class StoreSearchSpec: QuickSpec {
it("contains the app name") {
let appName = "myapp"
let urlString = storeSearch.searchURLString(forApp: appName)
expect(urlString) ==
"https://itunes.apple.com/search?media=software&entity=macSoftware&term=\(appName)"
expect(urlString) == "https://itunes.apple.com/search?media=software&entity=macSoftware&term=\(appName)"
}
it("contains the encoded app name") {
let appName = "My App"
let appNameEncoded = "My%20App"
let urlString = storeSearch.searchURLString(forApp: appName)
expect(urlString) ==
"https://itunes.apple.com/search?media=software&entity=macSoftware&term=\(appNameEncoded)"
expect(urlString)
== "https://itunes.apple.com/search?media=software&entity=macSoftware&term=\(appNameEncoded)"
}
// Find a character that causes addingPercentEncoding(withAllowedCharacters to return nil
xit("is nil when app name cannot be url encoded") {

View file

@ -6,10 +6,11 @@
// Copyright © 2018 Andrew Naylor. All rights reserved.
//
@testable import MasKit
import Foundation
import XCTest
@testable import MasKit
class MASErrorTestCase: XCTestCase {
private let errorDomain = "MAS"
var error: MASError!

View file

@ -32,10 +32,12 @@ extension Bundle {
/// - Parameter fileName: Name of file to locate.
/// - Returns: URL to file.
func url(for fileName: String) -> URL? {
guard let path = self.path(forResource: fileName.fileNameWithoutExtension,
ofType: fileName.fileExtension,
inDirectory: "JSON")
else { fatalError("Unable to load file \(fileName)") }
guard
let path = self.path(
forResource: fileName.fileNameWithoutExtension,
ofType: fileName.fileExtension,
inDirectory: "JSON")
else { fatalError("Unable to load file \(fileName)") }
return URL(fileURLWithPath: path)
}

View file

@ -6,10 +6,11 @@
// Copyright © 2020 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class OpenSystemCommandSpec: QuickSpec {
override func spec() {
describe("open system command") {

View file

@ -6,10 +6,11 @@
// Copyright © 2020 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class AppListsFormatterSpec: QuickSpec {
override func spec() {
// static func reference
@ -25,14 +26,14 @@ class AppListsFormatterSpec: QuickSpec {
expect(output) == ""
}
it("can format a single product") {
products = [SoftwareProductMock(
let product = SoftwareProductMock(
appName: "Awesome App",
bundleIdentifier: "",
bundlePath: "",
bundleVersion: "19.2.1",
itemIdentifier: 12345
)]
let output = format(products)
)
let output = format([product])
expect(output) == "12345 Awesome App (19.2.1)"
}
it("can format two products") {
@ -50,11 +51,10 @@ class AppListsFormatterSpec: QuickSpec {
bundlePath: "",
bundleVersion: "1.2.0",
itemIdentifier: 67890
)
),
]
let output = format(products)
expect(output) ==
"12345 Awesome App (19.2.1)\n67890 Even Better App (1.2.0)"
expect(output) == "12345 Awesome App (19.2.1)\n67890 Even Better App (1.2.0)"
}
}
}

View file

@ -6,10 +6,11 @@
// Copyright © 2019 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
import Quick
@testable import MasKit
class SearchResultsFormatterSpec: QuickSpec {
override func spec() {
// static func reference
@ -25,23 +26,23 @@ class SearchResultsFormatterSpec: QuickSpec {
expect(output) == ""
}
it("can format a single result") {
results = [SearchResult(
let result = SearchResult(
price: 9.87,
trackId: 12345,
trackName: "Awesome App",
version: "19.2.1"
)]
let output = format(results, false)
)
let output = format([result], false)
expect(output) == " 12345 Awesome App (19.2.1)"
}
it("can format a single result with price") {
results = [SearchResult(
let result = SearchResult(
price: 9.87,
trackId: 12345,
trackName: "Awesome App",
version: "19.2.1"
)]
let output = format(results, true)
)
let output = format([result], true)
expect(output) == " 12345 Awesome App $ 9.87 (19.2.1)"
}
it("can format a two results") {
@ -57,11 +58,10 @@ class SearchResultsFormatterSpec: QuickSpec {
trackId: 67890,
trackName: "Even Better App",
version: "1.2.0"
)
),
]
let output = format(results, false)
expect(output) ==
" 12345 Awesome App (19.2.1)\n 67890 Even Better App (1.2.0)"
expect(output) == " 12345 Awesome App (19.2.1)\n 67890 Even Better App (1.2.0)"
}
it("can format a two results with prices") {
results = [
@ -76,11 +76,11 @@ class SearchResultsFormatterSpec: QuickSpec {
trackId: 67890,
trackName: "Even Better App",
version: "1.2.0"
)
),
]
let output = format(results, true)
expect(output) ==
" 12345 Awesome App $ 9.87 (19.2.1)\n 67890 Even Better App $ 0.01 (1.2.0)"
expect(output)
== " 12345 Awesome App $ 9.87 (19.2.1)\n 67890 Even Better App $ 0.01 (1.2.0)"
}
}
}

View file

@ -6,9 +6,10 @@
// Copyright © 2020 mas-cli. All rights reserved.
//
@testable import MasKit
import Quick
import Nimble
import Quick
@testable import MasKit
class SearchResultListSpec: QuickSpec {
override func spec() {

View file

@ -6,9 +6,10 @@
// Copyright © 2020 mas-cli. All rights reserved.
//
@testable import MasKit
import Quick
import Nimble
import Quick
@testable import MasKit
class SearchResultSpec: QuickSpec {
override func spec() {

View file

@ -6,9 +6,10 @@
// Copyright © 2019 mas-cli. All rights reserved.
//
@testable import MasKit
import XCTest
@testable import MasKit
class NetworkManagerTests: XCTestCase {
func testSuccessfulAsyncResponse() {
// Setup our objects

View file

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

View file

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

View file

@ -6,14 +6,14 @@
// Copyright © 2018 mas-cli. All rights reserved.
//
@testable import MasKit
import Nimble
@testable import MasKit
/// Nimble predicate for result enum success case, no associated value
func beSuccess() -> Predicate<Result<(), MASError>> {
return Predicate.define("be <success>") { expression, message in
if let actual = try expression.evaluate(),
case .success = actual {
if case .success = try expression.evaluate() {
return PredicateResult(status: .matches, message: message)
}
return PredicateResult(status: .fail, message: message)
@ -23,8 +23,7 @@ func beSuccess() -> Predicate<Result<(), MASError>> {
/// Nimble predicate for result enum failure with associated error
func beFailure(test: @escaping (MASError) -> Void = { _ in }) -> Predicate<Result<(), MASError>> {
return Predicate.define("be <failure>") { expression, message in
if let actual = try expression.evaluate(),
case let .failure(error) = actual {
if case let .failure(error) = try expression.evaluate() {
test(error)
return PredicateResult(status: .matches, message: message)
}

View file

@ -65,9 +65,10 @@ extension OutputListener {
// Restore stdout
freopen("/dev/stdout", "a", stdout)
[inputPipe.fileHandleForReading, outputPipe.fileHandleForWriting].forEach { file in
file.closeFile()
}
[inputPipe.fileHandleForReading, outputPipe.fileHandleForWriting]
.forEach { file in
file.closeFile()
}
}
}

View file

@ -31,9 +31,9 @@ class OutputListenerSpec: QuickSpec {
output.openConsolePipe()
let expectedOutput = """
hi there
hi there
"""
"""
print("hi there")

View file

@ -8,8 +8,10 @@
// https://medium.com/@merowing_/stop-weak-strong-dance-in-swift-3aec6d3563d4
func strongify<Context: AnyObject, Arguments>(_ context: Context?,
closure: @escaping (Context, Arguments) -> Void) -> (Arguments) -> Void {
func strongify<Context: AnyObject, Arguments>(
_ context: Context?,
closure: @escaping (Context, Arguments) -> Void
) -> (Arguments) -> Void {
return { [weak context] arguments in
guard let strongContext = context else { return }
closure(strongContext, arguments)

View file

@ -13,6 +13,9 @@ git diff --check
echo
echo "--> 🕊️ Swift"
for SOURCE in mas MasKit MasKitTests; do
swift-format format --in-place --configuration .swift-format --recursive ${SOURCE}
done
swiftlint lint --fix --strict
echo