Skip to content

Commit

Permalink
Adopt swift-format (#12)
Browse files Browse the repository at this point in the history
- Update to `swift-tools-version:6.0`
- Adopt `swift-format`
- Switch from custom `.unixPath()` to Foundation's `.path`
- Add more tests

---------

Co-authored-by: Mahdi Bahrami <[email protected]>
  • Loading branch information
fpseverino and MahdiBM authored Sep 29, 2024
1 parent af8b8d0 commit 939492b
Show file tree
Hide file tree
Showing 52 changed files with 1,175 additions and 620 deletions.
9 changes: 9 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ on:
push: { branches: [ main ] }

jobs:
lint:
runs-on: ubuntu-latest
container: swift:noble
steps:
- name: Check out PassKit
uses: actions/checkout@v4
- name: Run format lint check
run: swift format lint --strict --recursive --parallel .

unit-tests:
uses: vapor/ci/.github/workflows/run-unit-tests.yml@main
secrets:
Expand Down
3 changes: 2 additions & 1 deletion .spi.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
version: 1
builder:
configs:
- documentation_targets: [PassKit, Passes, Orders]
- documentation_targets: [PassKit, Passes, Orders]
swift_version: 6.0
70 changes: 70 additions & 0 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"fileScopedDeclarationPrivacy": {
"accessLevel": "private"
},
"indentation": {
"spaces": 4
},
"indentConditionalCompilationBlocks": true,
"indentSwitchCaseLabels": false,
"lineBreakAroundMultilineExpressionChainComponents": false,
"lineBreakBeforeControlFlowKeywords": false,
"lineBreakBeforeEachArgument": false,
"lineBreakBeforeEachGenericRequirement": false,
"lineLength": 100,
"maximumBlankLines": 1,
"multiElementCollectionTrailingCommas": true,
"noAssignmentInExpressions": {
"allowedFunctions": [
"XCTAssertNoThrow"
]
},
"prioritizeKeepingFunctionOutputTogether": false,
"respectsExistingLineBreaks": true,
"rules": {
"AllPublicDeclarationsHaveDocumentation": false,
"AlwaysUseLiteralForEmptyCollectionInit": 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": true,
"NoAssignmentInExpressions": true,
"NoBlockComments": true,
"NoCasesWithOnlyFallthrough": true,
"NoEmptyTrailingClosureParentheses": true,
"NoLabelsInCasePatterns": true,
"NoLeadingUnderscores": false,
"NoParensAroundConditions": true,
"NoPlaygroundLiterals": true,
"NoVoidReturnOnFunctionSignature": true,
"OmitExplicitReturns": false,
"OneCasePerLine": true,
"OneVariableDeclarationPerLine": true,
"OnlyOneTrailingClosureArgument": true,
"OrderedImports": true,
"ReplaceForEachWithForLoop": true,
"ReturnVoidInsteadOfEmptyTuple": true,
"TypeNamesShouldBeCapitalized": true,
"UseEarlyExits": false,
"UseExplicitNilCheckInConditions": true,
"UseLetInEveryBoundCaseVariable": true,
"UseShorthandTypeNames": true,
"UseSingleLinePropertyGetter": true,
"UseSynthesizedInitializer": true,
"UseTripleSlashForDocumentationComments": true,
"UseWhereClausesInForLoops": false,
"ValidateDocumentationComments": false
},
"spacesAroundRangeFormationOperators": false,
"tabWidth": 8,
"version": 1
}
30 changes: 14 additions & 16 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
// swift-tools-version:5.10
// swift-tools-version:6.0
import PackageDescription

let package = Package(
name: "PassKit",
platforms: [
.macOS(.v13)
.macOS(.v14)
],
products: [
.library(name: "Passes", targets: ["Passes"]),
.library(name: "Orders", targets: ["Orders"]),
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.103.1"),
.package(url: "https://github.com/vapor/vapor.git", from: "4.105.2"),
.package(url: "https://github.com/vapor/fluent.git", from: "4.11.0"),
.package(url: "https://github.com/vapor/apns.git", from: "4.2.0"),
.package(url: "https://github.com/vapor-community/Zip.git", from: "2.2.0"),
.package(url: "https://github.com/vapor-community/Zip.git", from: "2.2.3"),
.package(url: "https://github.com/apple/swift-certificates.git", from: "1.5.0"),
// used in tests
.package(url: "https://github.com/vapor/fluent-sqlite-driver.git", from: "4.7.4"),
Expand All @@ -34,14 +34,14 @@ let package = Package(
.target(
name: "Passes",
dependencies: [
.target(name: "PassKit"),
.target(name: "PassKit")
],
swiftSettings: swiftSettings
),
.target(
name: "Orders",
dependencies: [
.target(name: "PassKit"),
.target(name: "PassKit")
],
swiftSettings: swiftSettings
),
Expand All @@ -54,7 +54,7 @@ let package = Package(
.product(name: "FluentSQLiteDriver", package: "fluent-sqlite-driver"),
],
resources: [
.copy("Templates"),
.copy("Templates")
],
swiftSettings: swiftSettings
),
Expand All @@ -67,18 +67,16 @@ let package = Package(
.product(name: "FluentSQLiteDriver", package: "fluent-sqlite-driver"),
],
resources: [
.copy("Templates"),
.copy("Templates")
],
swiftSettings: swiftSettings
),
]
)

var swiftSettings: [SwiftSetting] { [
.enableUpcomingFeature("ExistentialAny"),
.enableUpcomingFeature("ConciseMagicFile"),
.enableUpcomingFeature("ForwardTrailingClosures"),
.enableUpcomingFeature("DisableOutwardActorInference"),
.enableUpcomingFeature("StrictConcurrency"),
.enableExperimentalFeature("StrictConcurrency=complete"),
] }
var swiftSettings: [SwiftSetting] {
[
.enableUpcomingFeature("ExistentialAny"),
.enableUpcomingFeature("FullTypedThrows"),
]
}
22 changes: 11 additions & 11 deletions Sources/Orders/DTOs/OrderJSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,35 @@ public struct OrderJSON {
public protocol Properties: Encodable {
/// The date and time when the customer created the order, in RFC 3339 format.
var createdAt: String { get }

/// A unique order identifier scoped to your order type identifier.
///
/// In combination with the order type identifier, this uniquely identifies an order within the system and isn’t displayed to the user.
var orderIdentifier: String { get }

/// A URL where the customer can manage the order.
var orderManagementURL: String { get }

/// The type of order this bundle represents.
///
/// Currently the only supported value is `ecommerce`.
var orderType: OrderType { get }

/// An identifier for the order type associated with the order.
///
/// The value must correspond with your signing certificate and isn’t displayed to the user.
var orderTypeIdentifier: String { get }

/// A high-level status of the order, used for display purposes.
///
/// The system considers orders with status `completed` or `cancelled` closed.
var status: OrderStatus { get }

/// The version of the schema used for the order.
///
/// The current version is `1`.
var schemaVersion: SchemaVersion { get }

/// The date and time when the order was last updated, in RFC 3339 format.
///
/// This should equal the `createdAt` time, if the order hasn’t had any updates.
Expand All @@ -58,10 +58,10 @@ extension OrderJSON {
public protocol Merchant: Encodable {
/// The localized display name of the merchant.
var displayName: String { get }

/// The Apple Merchant Identifier for this merchant, generated at `developer.apple.com`.
var merchantIdentifier: String { get }

/// The URL for the merchant’s website or landing page.
var url: String { get }
}
Expand All @@ -74,10 +74,10 @@ extension OrderJSON {
public protocol Barcode: Encodable {
/// The format of the barcode.
var format: BarcodeFormat { get }

/// The contents of the barcode.
var message: String { get }

/// The text encoding of the barcode message.
///
/// Typically this is `iso-8859-1`, but you may specify an alternative encoding if required.
Expand Down
14 changes: 9 additions & 5 deletions Sources/Orders/Middleware/AppleOrderMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@
// Created by Francesco Paolo Severino on 30/06/24.
//

import Vapor
import FluentKit
import Vapor

struct AppleOrderMiddleware<O: OrderModel>: AsyncMiddleware {
func respond(to request: Request, chainingTo next: any AsyncResponder) async throws -> Response {
guard let auth = request.headers["Authorization"].first?.replacingOccurrences(of: "AppleOrder ", with: ""),
let _ = try await O.query(on: request.db)
func respond(
to request: Request, chainingTo next: any AsyncResponder
) async throws -> Response {
guard
let auth = request.headers["Authorization"].first?.replacingOccurrences(
of: "AppleOrder ", with: ""),
(try await O.query(on: request.db)
.filter(\._$authenticationToken == auth)
.first()
.first()) != nil
else {
throw Abort(.unauthorized)
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Orders/Models/Concrete Models/Order.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
// Created by Francesco Paolo Severino on 30/06/24.
//

import Foundation
import FluentKit
import Foundation

/// The `Model` that stores Wallet orders.
final public class Order: OrderModel, @unchecked Sendable {
Expand Down Expand Up @@ -35,7 +35,7 @@ final public class Order: OrderModel, @unchecked Sendable {
@Field(key: Order.FieldKeys.authenticationToken)
public var authenticationToken: String

public required init() { }
public required init() {}

public required init(orderTypeIdentifier: String, authenticationToken: String) {
self.orderTypeIdentifier = orderTypeIdentifier
Expand Down
4 changes: 3 additions & 1 deletion Sources/Orders/Models/Concrete Models/OrdersDevice.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ extension OrdersDevice: AsyncMigration {
.field(.id, .int, .identifier(auto: true))
.field(OrdersDevice.FieldKeys.pushToken, .string, .required)
.field(OrdersDevice.FieldKeys.deviceLibraryIdentifier, .string, .required)
.unique(on: OrdersDevice.FieldKeys.pushToken, OrdersDevice.FieldKeys.deviceLibraryIdentifier)
.unique(
on: OrdersDevice.FieldKeys.pushToken, OrdersDevice.FieldKeys.deviceLibraryIdentifier
)
.create()
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/Orders/Models/Concrete Models/OrdersErrorLog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
// Created by Francesco Paolo Severino on 30/06/24.
//

import struct Foundation.Date
import FluentKit
import PassKit

import struct Foundation.Date

/// The `Model` that stores Wallet orders error logs.
final public class OrdersErrorLog: ErrorLogModel, @unchecked Sendable {
/// The schema name of the error log model.
Expand Down
10 changes: 8 additions & 2 deletions Sources/Orders/Models/Concrete Models/OrdersRegistration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,14 @@ extension OrdersRegistration: AsyncMigration {
public func prepare(on database: any Database) async throws {
try await database.schema(Self.schema)
.field(.id, .int, .identifier(auto: true))
.field(OrdersRegistration.FieldKeys.deviceID, .int, .required, .references(DeviceType.schema, .id, onDelete: .cascade))
.field(OrdersRegistration.FieldKeys.orderID, .uuid, .required, .references(OrderType.schema, .id, onDelete: .cascade))
.field(
OrdersRegistration.FieldKeys.deviceID, .int, .required,
.references(DeviceType.schema, .id, onDelete: .cascade)
)
.field(
OrdersRegistration.FieldKeys.orderID, .uuid, .required,
.references(OrderType.schema, .id, onDelete: .cascade)
)
.create()
}

Expand Down
7 changes: 4 additions & 3 deletions Sources/Orders/Models/OrderDataModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ public protocol OrderDataModel: Model {
var order: OrderType { get set }
}

internal extension OrderDataModel {
extension OrderDataModel {
var _$order: Parent<OrderType> {
guard let mirror = Mirror(reflecting: self).descendant("_order"),
let order = mirror as? Parent<OrderType> else {
fatalError("order property must be declared using @Parent")
let order = mirror as? Parent<OrderType>
else {
fatalError("order property must be declared using @Parent")
}

return order
Expand Down
Loading

0 comments on commit 939492b

Please sign in to comment.