Skip to content

Commit

Permalink
Merge pull request #593 from rgoldberg/592-lint-cleanup
Browse files Browse the repository at this point in the history
Additional linting / cleanup code
  • Loading branch information
rgoldberg authored Oct 23, 2024
2 parents e62169e + c36a797 commit bb67ea5
Show file tree
Hide file tree
Showing 47 changed files with 411 additions and 256 deletions.
95 changes: 58 additions & 37 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -1,41 +1,62 @@
{
"indentation" : {
"spaces" : 4
"indentConditionalCompilationBlocks": false,
"indentation": {
"spaces": 4
},
"lineLength" : 120,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLowerCamelCase" : true,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : false,
"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
"lineBreakAroundMultilineExpressionChainComponents": true,
"lineBreakBeforeControlFlowKeywords": false,
"lineBreakBeforeEachArgument": true,
"lineBreakBeforeEachGenericRequirement": true,
"lineBreakBetweenDeclarationAttributes": true,
"lineLength": 120,
"maximumBlankLines": 1,
"multiElementCollectionTrailingCommas": true,
"prioritizeKeepingFunctionOutputTogether": true,
"respectsExistingLineBreaks": true,
"rules": {
"AllPublicDeclarationsHaveDocumentation": true,
"AlwaysUseLiteralForEmptyCollectionInit": true,
"AlwaysUseLowerCamelCase": true,
"AmbiguousTrailingClosureOverload": true,
"BeginDocumentationCommentWithOneLineSummary": true,
"DoNotUseSemicolons": true,
"DontRepeatTypeInStaticProperties": true,
"FileScopedDeclarationPrivacy": true,
"FullyIndirectEnum": true,
"GroupNumericLiterals": true,
"IdentifiersMustBeASCII": true,
"NeverForceUnwrap": true,
"NeverUseForceTry": true,
"NeverUseImplicitlyUnwrappedOptionals": true,
"NoAccessLevelOnExtensionDeclaration": true,
"NoAssignmentInExpressions": true,
"NoBlockComments": true,
"NoCasesWithOnlyFallthrough": true,
"NoEmptyTrailingClosureParentheses": true,
"NoLabelsInCasePatterns": true,
"NoLeadingUnderscores": true,
"NoParensAroundConditions": true,
"NoPlaygroundLiterals": true,
"NoVoidReturnOnFunctionSignature": true,
"OmitExplicitReturns": true,
"OneCasePerLine": true,
"OneVariableDeclarationPerLine": true,
"OnlyOneTrailingClosureArgument": true,
"OrderedImports": true,
"ReplaceForEachWithForLoop": true,
"ReturnVoidInsteadOfEmptyTuple": true,
"TypeNamesShouldBeCapitalized": true,
"UseEarlyExits": true,
"UseLetInEveryBoundCaseVariable": true,
"UseShorthandTypeNames": true,
"UseSingleLinePropertyGetter": true,
"UseSynthesizedInitializer": true,
"UseTripleSlashForDocumentationComments": true,
"UseWhereClausesInForLoops": true,
"ValidateDocumentationComments": true
},
"version" : 1
"spacesAroundRangeFormationOperators": false,
"spacesBeforeEndOfLineComments": 1,
"TrailingComma": false,
"version": 1
}
21 changes: 16 additions & 5 deletions .swiftformat
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,33 @@
# https://github.com/nicklockwood/SwiftFormat#config-file
#

--exclude docs/

# Disabled rules
--disable blankLinesAroundMark
--disable consecutiveSpaces
--disable hoistAwait
--disable hoistPatternLet
--disable hoistTry

# Enable later
--disable indent
--disable trailingCommas

# Enabled rules (disabled by default)
--enable trailingClosures
#--enable acronyms
#--enable blankLinesBetweenImports
--enable blockComments
--enable docComments
--enable isEmpty
--enable noExplicitOwnership
#--enable organizeDeclarations
--enable redundantProperty
--enable sortSwitchCases
--enable wrapConditionalBodies
--enable wrapEnumCases
--enable wrapMultilineConditionalAssignment
--enable wrapSwitchCases

# Rule options
--commas always
--extensionacl on-declarations
--importgrouping testable-last
--lineaftermarks false
--ranges no-space
41 changes: 35 additions & 6 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,40 @@
# https://github.com/realm/SwiftLint#configuration
#
---
opt_in_rules:
- all
disabled_rules:
- non_optional_string_data_conversion
- balanced_xctest_lifecycle
- closure_body_length
- contrasted_opening_brace
- explicit_acl
- explicit_enum_raw_value
- explicit_top_level_acl
- explicit_type_interface
- file_header
- file_name
- final_test_case
- force_unwrapping
- function_body_length
- inert_defer
- legacy_objc_type
- no_grouping_extension
- number_separator
- one_declaration_per_file
- prefer_nimble
- prefixed_toplevel_constant
- quick_discouraged_call
- quick_discouraged_pending_test
- required_deinit
- sorted_enum_cases
- trailing_comma
excluded:
- docs
opening_brace:
ignore_multiline_function_signatures: true
ignore_multiline_statement_conditions: true
- unused_capture_list
- vertical_whitespace_between_cases
file_types_order:
order: [
[main_type],
[supporting_type],
[extension],
[preview_provider],
[library_content_provider]
]
35 changes: 20 additions & 15 deletions Sources/mas/AppStore/Downloader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,36 @@ import StoreFoundation

/// Downloads a list of apps, one after the other, printing progress to the console.
///
/// - Parameter appIDs: The IDs of the apps to be downloaded
/// - Parameter purchase: Flag indicating whether the apps needs to be purchased.
/// Only works for free apps. Defaults to false.
/// - Parameters:
/// - appIDs: The IDs of the apps to be downloaded
/// - purchase: Flag indicating whether the apps needs to be purchased.
/// Only works for free apps. Defaults to false.
/// - Returns: A promise that completes when the downloads are complete. If any fail,
/// the promise is rejected with the first error, after all remaining downloads are attempted.
/// the promise is rejected with the first error, after all remaining downloads are attempted.
func downloadAll(_ appIDs: [AppID], purchase: Bool = false) -> Promise<Void> {
var firstError: Error?
return appIDs.reduce(Guarantee<Void>.value(())) { previous, appID in
previous.then {
downloadWithRetries(appID, purchase: purchase).recover { error in
if firstError == nil {
firstError = error
}
return
appIDs
.reduce(Guarantee.value(())) { previous, appID in
previous.then {
downloadWithRetries(appID, purchase: purchase)
.recover { error in
if firstError == nil {
firstError = error
}
}
}
}
}.done {
if let error = firstError {
throw error
.done {
if let error = firstError {
throw error
}
}
}
}

private func downloadWithRetries(_ appID: AppID, purchase: Bool = false, attempts: Int = 3) -> Promise<Void> {
SSPurchase().perform(appID: appID, purchase: purchase)
.recover { error -> Promise<Void> in
.recover { error in
guard attempts > 1 else {
throw error
}
Expand Down
47 changes: 27 additions & 20 deletions Sources/mas/AppStore/ISStoreAccount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,35 @@ import CommerceKit
import PromiseKit
import StoreFoundation

private let timeout = 30.0

extension ISStoreAccount: StoreAccount {
static var primaryAccount: Promise<ISStoreAccount> {
if #available(macOS 10.13, *) {
return race(
Promise<ISStoreAccount> { seal in
ISServiceProxy.genericShared().accountService.primaryAccount { storeAccount in
seal.fulfill(storeAccount)
}
Promise { seal in
ISServiceProxy.genericShared().accountService
.primaryAccount { storeAccount in
seal.fulfill(storeAccount)
}
},
after(seconds: 30).then {
Promise(error: MASError.notSignedIn)
}
after(seconds: timeout)
.then {
Promise(error: MASError.notSignedIn)
}
)
} else {
return .value(CKAccountStore.shared().primaryAccount)
}

return .value(CKAccountStore.shared().primaryAccount)
}

static func signIn(username: String, password: String, systemDialog: Bool) -> Promise<ISStoreAccount> {
// swift-format-ignore: UseEarlyExits
if #available(macOS 10.13, *) {
// Signing in is no longer possible as of High Sierra.
// https://github.com/mas-cli/mas/issues/164
return Promise(error: MASError.notSupported)
// swiftlint:disable:next superfluous_else
} else {
return
primaryAccount
Expand All @@ -43,7 +49,7 @@ extension ISStoreAccount: StoreAccount {

let password =
password.isEmpty && !systemDialog
? String(validatingUTF8: getpass("Password: "))!
? String(validatingUTF8: getpass("Password: ")) ?? ""
: password

guard !password.isEmpty || systemDialog else {
Expand All @@ -68,19 +74,20 @@ extension ISStoreAccount: StoreAccount {

if systemDialog {
return signInPromise
} else {
context.demoMode = true
context.demoAccountName = username
context.demoAccountPassword = password
context.demoAutologinMode = true
}

return race(
signInPromise,
after(seconds: 30).then {
context.demoMode = true
context.demoAccountName = username
context.demoAccountPassword = password
context.demoAutologinMode = true

return race(
signInPromise,
after(seconds: timeout)
.then {
Promise(error: MASError.signInFailed(error: nil))
}
)
}
)
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/mas/AppStore/PurchaseDownloadObserver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import CommerceKit
import StoreFoundation

@objc class PurchaseDownloadObserver: NSObject, CKDownloadQueueObserver {
@objc
class PurchaseDownloadObserver: NSObject, CKDownloadQueueObserver {
let purchase: SSPurchase
var completionHandler: (() -> Void)?
var errorHandler: ((MASError) -> Void)?
Expand Down Expand Up @@ -64,6 +65,7 @@ struct ProgressState {
let phase: String

var percentage: String {
// swiftlint:disable:next no_magic_numbers
String(format: "%.1f%%", floor(percentComplete * 1000) / 10)
}
}
Expand Down
24 changes: 12 additions & 12 deletions Sources/mas/AppStore/SSPurchase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ extension SSPurchase {
if purchase {
parameters["macappinstalledconfirmed"] = 1
parameters["pricingParameters"] = "STDQ"

} else {
parameters["pricingParameters"] = "STDRDL"
}
Expand Down Expand Up @@ -63,19 +62,20 @@ extension SSPurchase {

private func perform() -> Promise<Void> {
Promise<SSPurchase> { seal in
CKPurchaseController.shared().perform(self, withOptions: 0) { purchase, _, error, response in
if let error {
seal.reject(MASError.purchaseFailed(error: error as NSError?))
return
}
CKPurchaseController.shared()
.perform(self, withOptions: 0) { purchase, _, error, response in
if let error {
seal.reject(MASError.purchaseFailed(error: error as NSError?))
return
}

guard response?.downloads.isEmpty == false, let purchase else {
seal.reject(MASError.noDownloads)
return
}
guard response?.downloads.isEmpty == false, let purchase else {
seal.reject(MASError.noDownloads)
return
}

seal.fulfill(purchase)
}
seal.fulfill(purchase)
}
}
.then { purchase in
let observer = PurchaseDownloadObserver(purchase: purchase)
Expand Down
Loading

0 comments on commit bb67ea5

Please sign in to comment.