Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Add buildtool plugin for SPM swiftlint support #2104

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .swiftpm/xcode/xcshareddata/xcschemes/Amplify-Package.xcscheme
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,20 @@
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "SwiftLintPlugin"
BuildableName = "SwiftLintPlugin"
BlueprintName = "SwiftLintPlugin"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ extension AuthCategory: AuthCategoryBehavior {
}

public func resetPassword(for username: String, options: AuthResetPasswordRequest.Options? = nil) async throws -> AuthResetPasswordResult {
return try await plugin.resetPassword(for: username,options: options)
return try await plugin.resetPassword(for: username,options: options) // swiftlint:disable:this comma
}

public func confirmResetPassword(
Expand Down
2 changes: 1 addition & 1 deletion Amplify/Core/Support/Amplify+Publisher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public extension Amplify {
}
}
}
.handleEvents(receiveCancel: { task.cancel() } )
.handleEvents(receiveCancel: { task.cancel() } ) // swiftlint:disable:this closing_brace
.eraseToAnyPublisher()
}

Expand Down
2 changes: 1 addition & 1 deletion Amplify/Core/Support/AmplifyTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public protocol AmplifyInProcessReportingTask {
}

public extension AmplifyInProcessReportingTask where InProcess == Progress {
var progress : AmplifyAsyncSequence<InProcess> {
var progress : AmplifyAsyncSequence<InProcess> { // swiftlint:disable:this colon
get async {
await inProcess
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class EventRecorder: AnalyticsEventRecording {
func submitAllEvents() async throws -> [PinpointEvent] {
submittedEvents = []
let eventsBatch = try getBatchRecords()
if eventsBatch.count > 0 {
if eventsBatch.count > 0 { // swiftlint:disable:this empty_count
let endpointProfile = await endpointClient.currentEndpointProfile()
try await processBatch(eventsBatch, endpointProfile: endpointProfile)
}
Expand All @@ -96,7 +96,7 @@ class EventRecorder: AnalyticsEventRecording {
try await submit(pinpointEvents: eventBatch, endpointProfile: endpointProfile)
try storage.removeFailedEvents()
let nextEventsBatch = try getBatchRecords()
if nextEventsBatch.count > 0 {
if nextEventsBatch.count > 0 { // swiftlint:disable:this empty_count
try await processBatch(nextEventsBatch, endpointProfile: endpointProfile)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ struct InitializeAuthConfiguration: Action {
if case .amplifyCredentials(let fetchedCredentials) = data {
credentials = fetchedCredentials
}
}
} // swiftlint:disable:this statement_position
catch KeychainStoreError.itemNotFound {
logVerbose("No existing session found.", environment: environment)
}
} // swiftlint:disable:this statement_position
catch {
logError("Error when loading amplify credentials: \(error)", environment: environment)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ struct MigrateLegacyCredentialStore: Action {

/// Legacy Keys
private let AWSCredentialsProviderClassKey = "AWSCognitoCredentialsProvider"
private let UserPoolClassKey = "AWSCognitoIdentityUserPool"
private let UserPoolClassKey = "AWSCognitoIdentityUserPool" // swiftlint:disable:this identifier_name
private let AWSCredentialsProviderKeychainAccessKeyId = "accessKey"
private let AWSCredentialsProviderKeychainSecretAccessKey = "secretKey"
private let AWSCredentialsProviderKeychainSessionToken = "sessionKey"
private let AWSCredentialsProviderKeychainExpiration = "expiration"
private let AWSCredentialsProviderKeychainIdentityId = "identityId"

private let FederationProviderKey = "federationProvider"
private let LoginsMapKey = "loginsMap"
private let FederationProviderKey = "federationProvider" // swiftlint:disable:this identifier_name
private let LoginsMapKey = "loginsMap" // swiftlint:disable:this identifier_name

private let AWSCognitoAuthUserPoolCurrentUser = "currentUser"
private let AWSCognitoAuthUserAccessToken = "accessToken"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ extension VerifyDevicePasswordSRP {
do {
let dateStr = stateData.clientTimestamp.utcString
let clientClass = type(of: srpClient)
let u = try clientClass.calculateUHexValue(
let u = try clientClass.calculateUHexValue( // swiftlint:disable:this identifier_name
clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue,
serverPublicKeyHexValue: serverPublicBHexString)
// HKDF
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ extension VerifyPasswordSRP {
let strippedPoolId = strippedPoolId(poolId)
let dateStr = stateData.clientTimestamp.utcString
let clientClass = type(of: srpClient)
let u = try clientClass.calculateUHexValue(
let u = try clientClass.calculateUHexValue( // swiftlint:disable:this identifier_name
clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue,
serverPublicKeyHexValue: serverPublicBHexString)
// HKDF
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ struct AmplifySRPClient: SRPClientBehavior {
let client: SRPClientState

init(NHexValue: String, gHexValue: String) throws {
guard let N = BigInt(NHexValue, radix: 16),
let g = BigInt(gHexValue, radix: 16)
guard let N = BigInt(NHexValue, radix: 16), // swiftlint:disable:this identifier_name
let g = BigInt(gHexValue, radix: 16) // swiftlint:disable:this identifier_name
else {
throw SRPError.numberConversion
}
Expand All @@ -36,7 +36,7 @@ struct AmplifySRPClient: SRPClientBehavior {
return srpKeys
}

func calculateSharedSecret(username: String,
func calculateSharedSecret(username: String,
password: String,
saltHexValue: String,
clientPrivateKeyHexValue: String,
Expand Down Expand Up @@ -78,7 +78,7 @@ struct AmplifySRPClient: SRPClientBehavior {
let signedClientPublicKey = AmplifyBigIntHelper.getSignedData(num: clientPublicNum)
let signedServerPublicKey = AmplifyBigIntHelper.getSignedData(num: serverPublicNum)

let u = SRPClientState.calculcateU(publicClientKey: signedClientPublicKey,
let u = SRPClientState.calculcateU(publicClientKey: signedClientPublicKey, // swiftlint:disable:this identifier_name
publicServerKey: signedServerPublicKey)

return u.asString(radix: 16)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ extension SignInError {
case .service(let serviceError, _) = cognitoError,
case .passwordResetRequiredException = serviceError {
return true
} else if let cognitoError = serviceError as? SdkError<InitiateAuthOutputError>,
} else if let cognitoError = serviceError as? SdkError<InitiateAuthOutputError>, // swiftlint:disable:this statement_position
case .client(let clientError, _) = cognitoError,
case .retryError(let retryError) = clientError,
let cognitoServiceError = retryError as? SdkError<InitiateAuthOutputError>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ extension AuthenticationState {

init() { }

func resolve(
func resolve( // swiftlint:disable:this cyclomatic_complexity
oldState: StateType,
byApplying event: StateMachineEvent
) -> StateResolution<StateType> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ extension AuthorizationState {

init() { }

func resolve(
func resolve( // swiftlint:disable:this function_body_length cyclomatic_complexity
oldState: StateType,
byApplying event: StateMachineEvent
) -> StateResolution<StateType> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ extension RefreshSessionState {

var defaultState: RefreshSessionState = .notStarted

func resolve(oldState: RefreshSessionState,
func resolve(oldState: RefreshSessionState, // swiftlint:disable:this cyclomatic_complexity
byApplying event: StateMachineEvent) -> StateResolution<RefreshSessionState> {

switch oldState {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ extension SignInState {
typealias StateType = SignInState
let defaultState = SignInState.notStarted

func resolve(
func resolve( // swiftlint:disable:this cyclomatic_complexity function_body_length
oldState: SignInState,
byApplying event: StateMachineEvent)
-> StateResolution<SignInState> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ public class CascadeDeleteOperation<M: Model>: AsynchronousOperation {

let associatedModelIds = queriedModels.map { $0.1.identifier(schema: modelSchema).stringValue }
associatedModels.append(contentsOf: queriedModels)
associatedModels.append(contentsOf: await recurseQueryAssociatedModels(modelSchema: associatedModelSchema, ids: associatedModelIds))
associatedModels.append(contentsOf: await recurseQueryAssociatedModels(modelSchema: associatedModelSchema, ids: associatedModelIds)) // swiftlint:disable:this comma
}
return associatedModels
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester {

/// Accepts a mutation event without a version, applies the latest version from the MutationSyncMetadata table,
/// writes the updated mutation event to the local database, then submits it to `mutationEventSubject`
func submit(mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) {
func submit(mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) { // swiftlint:disable:this return_arrow_whitespace
Task {
log.verbose("\(#function): \(mutationEvent)")

Expand All @@ -32,7 +32,7 @@ extension AWSMutationDatabaseAdapter: MutationEventIngester {
/// rejects the event with an error
func resolveConflictsThenSave(mutationEvent: MutationEvent,
storageAdapter: StorageEngineAdapter,
completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) {
completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) { // swiftlint:disable:this return_arrow_whitespace

// We don't want to query MutationSync<AnyModel> because a) we already have the model, and b) delete mutations
// are submitted *after* the delete has already been applied to the local data store, meaning there is no model
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ import Combine

/// Ingests MutationEvents from and writes them to the MutationEvent persistent store
protocol MutationEventIngester: AnyObject {
func submit(mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void)
func submit(mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) // swiftlint:disable:this return_arrow_whitespace
}
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ class RemoteSyncEngine: RemoteSyncEngineBehavior {
}
}

func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) {
func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) { // swiftlint:disable:this return_arrow_whitespace
mutationEventIngester.submit(mutationEvent: mutationEvent, completion: completion)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ protocol RemoteSyncEngineBehavior: AnyObject {

/// Submits a new mutation for synchronization to the remote API. The response will be handled by the appropriate
/// reconciliation queue
func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void)
func submit(_ mutationEvent: MutationEvent, completion: @escaping (Result<MutationEvent, DataStoreError>)->Void) // swiftlint:disable:this return_arrow_whitespace

var publisher: AnyPublisher<RemoteSyncEngineEvent, DataStoreError> { get }
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class AWSS3StorageService: AWSS3StorageServiceBehaviour, StorageServiceProxy {
let awsS3 = AWSS3Adapter(s3Client, config: clientConfig)
let preSignedURLBuilder = AWSS3PreSignedURLBuilderAdapter(config: clientConfig, bucket: bucket)

var _sessionConfiguration: URLSessionConfiguration
var _sessionConfiguration: URLSessionConfiguration // swiftlint:disable:this identifier_name
if let sessionConfiguration = sessionConfiguration {
_sessionConfiguration = sessionConfiguration
} else {
Expand Down
38 changes: 32 additions & 6 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ let swiftSettings: [SwiftSetting]? = [.define("DEV_PREVIEW_BUILD")]
let amplifyTargets: [Target] = [
.target(
name: "Amplify",
dependencies: ["SwiftLintPlugin"],
path: "Amplify",
exclude: [
"Info.plist",
Expand Down Expand Up @@ -86,6 +87,16 @@ let amplifyTargets: [Target] = [
exclude: [
"Info.plist"
]
),
.binaryTarget(
name: "SwiftLintBinary",
url: "https://github.com/realm/SwiftLint/releases/download/0.48.0/SwiftLintBinary-macos.artifactbundle.zip",
checksum: "9c255e797260054296f9e4e4cd7e1339a15093d75f7c4227b9568d63edddba50"
),
.plugin(
name: "SwiftLintPlugin",
capability: .buildTool(),
dependencies: ["SwiftLintBinary"]
)
]

Expand All @@ -95,7 +106,9 @@ let apiTargets: [Target] = [
dependencies: [
.target(name: "Amplify"),
.target(name: "AWSPluginsCore"),
.product(name: "AppSyncRealTimeClient", package: "aws-appsync-realtime-client-ios")],
.product(name: "AppSyncRealTimeClient", package: "aws-appsync-realtime-client-ios"),
.swiftLint
],
path: "AmplifyPlugins/API/Sources/AWSAPIPlugin",
exclude: [
"Info.plist",
Expand Down Expand Up @@ -139,7 +152,8 @@ let authTargets: [Target] = [
.target(name: "AWSPluginsCore"),
.product(name: "AWSClientRuntime", package: "aws-sdk-swift"),
.product(name: "AWSCognitoIdentityProvider", package: "aws-sdk-swift"),
.product(name: "AWSCognitoIdentity", package: "aws-sdk-swift")
.product(name: "AWSCognitoIdentity", package: "aws-sdk-swift"),
.swiftLint
],
path: "AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin",
swiftSettings: swiftSettings
Expand Down Expand Up @@ -181,7 +195,9 @@ let dataStoreTargets: [Target] = [
dependencies: [
.target(name: "Amplify"),
.target(name: "AWSPluginsCore"),
.product(name: "SQLite", package: "SQLite.swift")],
.product(name: "SQLite", package: "SQLite.swift"),
.swiftLint
],
path: "AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin",
exclude: [
"Info.plist",
Expand All @@ -208,7 +224,9 @@ let storageTargets: [Target] = [
dependencies: [
.target(name: "Amplify"),
.target(name: "AWSPluginsCore"),
.product(name: "AWSS3", package: "aws-sdk-swift")],
.product(name: "AWSS3", package: "aws-sdk-swift"),
.swiftLint
],
path: "AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin",
exclude: [
"Resources/Info.plist"
Expand All @@ -235,7 +253,9 @@ let geoTargets: [Target] = [
dependencies: [
.target(name: "Amplify"),
.target(name: "AWSPluginsCore"),
.product(name: "AWSLocation", package: "aws-sdk-swift")],
.product(name: "AWSLocation", package: "aws-sdk-swift"),
.swiftLint
],
path: "AmplifyPlugins/Geo/AWSLocationGeoPlugin",
exclude: [
"Resources/Info.plist"
Expand Down Expand Up @@ -264,7 +284,9 @@ let analyticsTargets: [Target] = [
.target(name: "AWSCognitoAuthPlugin"),
.target(name: "AWSPluginsCore"),
.product(name: "SQLite", package: "SQLite.swift"),
.product(name: "AWSPinpoint", package: "aws-sdk-swift")],
.product(name: "AWSPinpoint", package: "aws-sdk-swift"),
.swiftLint
],
path: "AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin"
),
.testTarget(
Expand Down Expand Up @@ -334,3 +356,7 @@ let package = Package(
dependencies: dependencies,
targets: targets
)

extension Target.Dependency {
static let swiftLint: Self = "SwiftLintPlugin"
}
36 changes: 36 additions & 0 deletions Plugins/SwiftLintPlugin/plugin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//

import PackagePlugin

@main
struct SwiftLintPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) async throws -> [Command] {
print(context.pluginWorkDirectory)
return [
.buildCommand(
displayName: "Linting \(target.name)",
executable: try context.tool(named: "swiftlint").path,
arguments: [
"lint",
"--in-process-sourcekit",
"--cache-path",
"\(context.pluginWorkDirectory)",
"--config",
"\(context.package.directory.string)/Plugins/SwiftLintPlugin/swiftlint.yml",
// "--path",
target.directory.string

],
environment: [:]
)
]
}
}
Loading