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

Set up SwiftLint #693

Merged
merged 8 commits into from
Feb 26, 2024
Merged
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
13 changes: 11 additions & 2 deletions .buildkite/pipeline.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Nodes with values to reuse in the pipeline.
common_params:
plugins: &common_plugins
- automattic/a8c-ci-toolkit#3.0.1
- automattic/a8c-ci-toolkit#3.1.0
# Common environment values to use with the `env` key.
env: &common_env
IMAGE_ID: xcode-15.0.1
Expand Down Expand Up @@ -33,8 +33,17 @@ steps:
plugins: *common_plugins

#################
# Lint
# Linters
#################
- label: ":swift: SwiftLint"
command: run_swiftlint --strict
plugins: *common_plugins
notify:
- github_commit_status:
context: "SwiftLint"
agents:
queue: "default"

- label: "🧹 Lint"
key: "lint"
command: |
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,6 @@ vendor/
# https://github.com/johnno1962/injectionforxcode

iOSInjectionProject/

# SwiftLint Remote Config Cache
.swiftlint/RemoteConfigCache
10 changes: 7 additions & 3 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@
AllCops:
NewCops: enable

# Override the maximum line length
Layout/LineLength:
Max: 160

# Allow the Podspec filename to match the project
Naming/FileName:
Exclude:
- 'WordPressKit.podspec'

# Override the maximum line length
Layout/LineLength:
Max: 160
Metrics/BlockLength:
Exclude:
- 'fastlane/Fastfile'
20 changes: 20 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
swiftlint_version: 0.54.0

parent_config: https://raw.githubusercontent.com/Automattic/swiftlint-config/0f8ab6388bd8d15a04391825ab125f80cfb90704/.swiftlint.yml
remote_timeout: 10.0

opt_in_rules:
- overridden_super_call
- discarded_notification_center_observer
- weak_delegate
- vertical_whitespace
- duplicate_imports

overridden_super_call:
severity: error

discarded_notification_center_observer:
severity: error

weak_delegate:
severity: error
15 changes: 15 additions & 0 deletions Podfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ APP_IOS_DEPLOYMENT_TARGET = Gem::Version.new('13.0')

platform :ios, APP_IOS_DEPLOYMENT_TARGET

def swiftlint_version
require 'yaml'

YAML.load_file('.swiftlint.yml')['swiftlint_version']
end

def wordpresskit_pods
pod 'Alamofire', '~> 4.8.0'
pod 'WordPressShared', '~> 2.0.0-beta.2'
Expand All @@ -34,6 +40,10 @@ target 'WordPressKitTests' do
pod 'OCMock', '~> 3.4'
end

abstract_target 'Tools' do
pod 'SwiftLint', swiftlint_version
end

# Let Pods targets inherit deployment target from the app
post_install do |installer|
installer.pods_project.targets.each do |target|
Expand All @@ -43,4 +53,9 @@ post_install do |installer|
configuration.build_settings.delete(ios_deployment_key) if pod_ios_deployment_target <= APP_IOS_DEPLOYMENT_TARGET
end
end

yellow_marker = "\033[33m"
reset_marker = "\033[0m"
puts "#{yellow_marker}The abstract target warning below is expected. Feel free to ignore
it.#{reset_marker}"
end
6 changes: 5 additions & 1 deletion Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ PODS:
- OHHTTPStubs/OHPathHelpers (9.1.0)
- OHHTTPStubs/Swift (9.1.0):
- OHHTTPStubs/Default
- SwiftLint (0.54.0)
- UIDeviceIdentifier (2.3.0)
- WordPressShared (2.0.1)
- wpxmlrpc (0.10.0)
Expand All @@ -27,6 +28,7 @@ DEPENDENCIES:
- OCMock (~> 3.4)
- OHHTTPStubs (~> 9.0)
- OHHTTPStubs/Swift (~> 9.0)
- SwiftLint (= 0.54.0)
- UIDeviceIdentifier (~> 2.0)
- WordPressShared (~> 2.0.0-beta.2)
- wpxmlrpc (~> 0.10.0)
Expand All @@ -37,6 +39,7 @@ SPEC REPOS:
- NSObject-SafeExpectations
- OCMock
- OHHTTPStubs
- SwiftLint
- UIDeviceIdentifier
- WordPressShared
- wpxmlrpc
Expand All @@ -46,10 +49,11 @@ SPEC CHECKSUMS:
NSObject-SafeExpectations: c01c8881cbd97efad6f668286b913cd0b7d62ab5
OCMock: 300b1b1b9155cb6378660b981c2557448830bdc6
OHHTTPStubs: 90eac6d8f2c18317baeca36698523dc67c513831
SwiftLint: c1de071d9d08c8aba837545f6254315bc900e211
UIDeviceIdentifier: 442b65b4ff1832d4ca9c2a157815cb29ad981b17
WordPressShared: f93f99269258b46dad04f4e4dbf540ce2e5c1e66
wpxmlrpc: 68db063041e85d186db21f674adf08d9c70627fd

PODFILE CHECKSUM: 7998039b722f0fe77c684f509f0478349cf5fb9b
PODFILE CHECKSUM: a06b4d2f7183f40a91a0f219ca399141aee28c5f

COCOAPODS: 1.14.3
20 changes: 20 additions & 0 deletions WordPressKit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -2815,6 +2815,7 @@
9368C7761EC5EF1B0092CE8E /* Sources */,
9368C7771EC5EF1B0092CE8E /* Frameworks */,
9368C7791EC5EF1B0092CE8E /* Resources */,
3F391E242B577AD7007975C4 /* SwiftLint */,
);
buildRules = (
);
Expand Down Expand Up @@ -3229,6 +3230,25 @@
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
3F391E242B577AD7007975C4 /* SwiftLint */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = SwiftLint;
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "./Pods/SwiftLint/swiftlint lint\n";
};
50C31E8D1B97D5FA0D543935 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
Expand Down
6 changes: 3 additions & 3 deletions WordPressKit/AccountServiceRemoteREST+SocialService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ extension AccountServiceRemoteREST {
connectParameters: [String: AnyObject]? = nil,
oAuthClientID: String,
oAuthClientSecret: String,
success:@escaping (() -> Void),
failure:@escaping ((NSError) -> Void)) {
success: @escaping (() -> Void),
failure: @escaping ((NSError) -> Void)) {
let path = self.path(forEndpoint: "me/social-login/connect", withVersion: ._1_1)

var params = [
Expand Down Expand Up @@ -65,7 +65,7 @@ extension AccountServiceRemoteREST {
/// - oAuthClientSecret The WPCOM REST API client secret.
/// - success The block that will be executed on success.
/// - failure The block that will be executed on failure.
public func disconnectFromSocialService(_ service: SocialServiceName, oAuthClientID: String, oAuthClientSecret: String, success:@escaping(() -> Void), failure:@escaping((NSError) -> Void)) {
public func disconnectFromSocialService(_ service: SocialServiceName, oAuthClientID: String, oAuthClientSecret: String, success: @escaping(() -> Void), failure: @escaping((NSError) -> Void)) {
let path = self.path(forEndpoint: "me/social-login/disconnect", withVersion: ._1_1)
let params = [
"client_id": oAuthClientID,
Expand Down
2 changes: 1 addition & 1 deletion WordPressKit/ChecksumUtil.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation

public class ChecksumUtil {

/// Generates a checksum based on the encoded keys.
/// Generates a checksum based on the encoded keys.
static func checksum<T>(from codable: T) -> String where T: Encodable {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
Expand Down
4 changes: 2 additions & 2 deletions WordPressKit/GravatarServiceRemote.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ open class GravatarServiceRemote {
/// - success: A success block.
/// - failure: A failure block.
///
open func fetchProfile(_ email: String, success:@escaping ((_ profile: RemoteGravatarProfile) -> Void), failure:@escaping ((_ error: Error?) -> Void)) {
open func fetchProfile(_ email: String, success: @escaping ((_ profile: RemoteGravatarProfile) -> Void), failure: @escaping ((_ error: Error?) -> Void)) {
guard let hash = (email as NSString).md5() else {
assertionFailure()
return
Expand All @@ -31,7 +31,7 @@ open class GravatarServiceRemote {
/// - success: A success block.
/// - failure: A failure block.
///
open func fetchProfile(hash: String, success:@escaping ((_ profile: RemoteGravatarProfile) -> Void), failure:@escaping ((_ error: Error?) -> Void)) {
open func fetchProfile(hash: String, success: @escaping ((_ profile: RemoteGravatarProfile) -> Void), failure: @escaping ((_ error: Error?) -> Void)) {
let path = baseGravatarURL + hash + ".json"
guard let targetURL = URL(string: path) else {
assertionFailure()
Expand Down
6 changes: 5 additions & 1 deletion WordPressKit/HTTPAuthenticationAlertController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ open class HTTPAuthenticationAlertController {

private static func controllerForServerTrustChallenge(_ challenge: URLAuthenticationChallenge) -> UIAlertController {
let title = NSLocalizedString("Certificate error", comment: "Popup title for wrong SSL certificate.")
let message = String(format: NSLocalizedString("The certificate for this server is invalid. You might be connecting to a server that is pretending to be “%@” which could put your confidential information at risk.\n\nWould you like to trust the certificate anyway?", comment: ""), challenge.protectionSpace.host)
let localizedMessage = NSLocalizedString(
"The certificate for this server is invalid. You might be connecting to a server that is pretending to be “%@” which could put your confidential information at risk.\n\nWould you like to trust the certificate anyway?",
comment: "Message for when the certificate for the server is invalid. The %@ placeholder will be replaced the a host name, received from the API."
)
let message = String(format: localizedMessage, challenge.protectionSpace.host)
let controller = UIAlertController(title: title, message: message, preferredStyle: .alert)

let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button label"),
Expand Down
2 changes: 1 addition & 1 deletion WordPressKit/JetpackRestoreTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public struct JetpackRestoreTypes {
public var contents: Bool

public init(themes: Bool = true,
plugins: Bool = true ,
plugins: Bool = true,
uploads: Bool = true,
sqls: Bool = true,
roots: Bool = true,
Expand Down
1 change: 0 additions & 1 deletion WordPressKit/QR Login/QRLoginValidationResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ public struct QRLoginValidationResponse: Decodable {
/// This may be null if the browser could not be determined
public var browser: String?


/// The City, State the user has requested the login from
/// IE: Columbus, Ohio
public var location: String
Expand Down
12 changes: 6 additions & 6 deletions WordPressKit/WordPressComOAuthClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ public final class WordPressComOAuthClient: NSObject {

let builder = tokenRequestBuilder().body(form: form)
return await oauth2Session
.perform(request: builder)
.perform(request: builder)
.mapUnacceptableStatusCodeError(AuthenticationFailure.init(response:body:))
.mapSuccess { response in
let responseObject = try JSONSerialization.jsonObject(with: response.body)
Expand Down Expand Up @@ -282,7 +282,7 @@ public final class WordPressComOAuthClient: NSObject {
"wpcom_resend_otp": "true"
])
return await oauth2Session
.perform(request: builder)
.perform(request: builder)
.mapUnacceptableStatusCodeError(AuthenticationFailure.init(response:body:))
.mapSuccess { _ in () }
}
Expand Down Expand Up @@ -399,7 +399,7 @@ public final class WordPressComOAuthClient: NSObject {
)

return await socialSession
.perform(request: builder, errorType: AuthenticationFailure.self)
.perform(request: builder, errorType: AuthenticationFailure.self)
.mapUnacceptableStatusCodeError(AuthenticationFailure.init(response:body:))
.mapSuccess { response in
WPKitLogVerbose("Received Social Login Oauth response.")
Expand Down Expand Up @@ -489,7 +489,7 @@ public final class WordPressComOAuthClient: NSObject {
"two_step_nonce": twoStepNonce,
])
return await webAuthnSession
.perform(request: builder)
.perform(request: builder)
.mapUnacceptableStatusCodeError(AuthenticationFailure.init(response:body:))
.mapSuccess { response in
// Expect the parent data response object
Expand Down Expand Up @@ -589,7 +589,7 @@ public final class WordPressComOAuthClient: NSObject {
])

return await webAuthnSession
.perform(request: builder)
.perform(request: builder)
.mapUnacceptableStatusCodeError(AuthenticationFailure.init(response:body:))
.mapSuccess { response in
let responseObject = try? JSONSerialization.jsonObject(with: response.body)
Expand Down Expand Up @@ -645,7 +645,7 @@ public final class WordPressComOAuthClient: NSObject {
}
}

/// A helper method to get an instance of SocialLogin2FANonceInfo and populate
/// A helper method to get an instance of SocialLogin2FANonceInfo and populate
/// it with the supplied data.
///
/// - Parameters:
Expand Down
2 changes: 1 addition & 1 deletion WordPressKit/WordPressComServiceRemote+SiteCreation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public enum SiteCreationResult {
public typealias SiteCreationResultHandler = ((SiteCreationResult) -> Void)

/// Site creation services, exclusive to WordPress.com.
///
///
public extension WordPressComServiceRemote {

/// Initiates a request to create a new WPCOM site.
Expand Down
5 changes: 4 additions & 1 deletion WordPressKit/WordPressOrgXMLRPCValidator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ import Foundation
case .notWordPressError:
return NSLocalizedString("That doesn't look like a WordPress site.", comment: "Message to show to user when he tries to add a self-hosted site that isn't a WordPress site.")
case .mobilePluginRedirectedError:
return NSLocalizedString("You seem to have installed a mobile plugin from DudaMobile which is preventing the app to connect to your blog", comment: "")
return NSLocalizedString(
"You seem to have installed a mobile plugin from DudaMobile which is preventing the app to connect to your blog",
comment: "Error messaged show when a mobile plugin is redirecting traffict to their site, DudaMobile in particular"
)
case .invalid:
return NSLocalizedString("Couldn't connect to the WordPress site. There is no valid WordPress site at this address. Check the site address (URL) you entered.", comment: "Error message shown a URL points to a valid site but not a WordPress site.")
case .blocked:
Expand Down
3 changes: 0 additions & 3 deletions WordPressKitTests/IPLocationRemoteTests.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import XCTest
@testable import WordPressKit


final class IPLocationRemoteTests: XCTestCase {
var remote: IPLocationRemote!
let apiURL = URL(string: "https://public-api.wordpress.com/geo/")!
Expand Down Expand Up @@ -59,7 +58,6 @@ final class MockURLProtocol: URLProtocol {
return request
}


override func startLoading() {
guard let handler = MockURLProtocol.requestHandler else {
fatalError("Handler is unavailable.")
Expand All @@ -78,6 +76,5 @@ final class MockURLProtocol: URLProtocol {
}
}


override func stopLoading() { }
}
2 changes: 1 addition & 1 deletion WordPressKitTests/MediaLibraryTestSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ extension MediaLibraryTestSupport {
var content: String?
var paramName: String?

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {
elementPath.append(elementName)
}

Expand Down
4 changes: 2 additions & 2 deletions WordPressKitTests/RemoteTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,9 @@ extension RemoteTestCase {
/// Helper function that stubs ALL endpoints so that they return a CFNetworkErrors.cfurlErrorNotConnectedToInternet
/// error. In the response, prior to returning the error, XCTFail will also be called logging the endpoint
/// which was called.
///
///
/// - Note: Remember that order is important when stubbing requests with HTTPStubs. Therefore, it is important
/// this is called **before** stubbing out a specific endpoint you are testing. See:
/// this is called **before** stubbing out a specific endpoint you are testing. See:
/// https://github.com/AliSoftware/OHHTTPStubs/wiki/Usage-Examples#stack-multiple-stubs-and-remove-installed-stubs
///
func stubAllNetworkRequestsWithNotConnectedError() {
Expand Down
Loading