Skip to content

Commit

Permalink
Merge pull request #128 from Automattic/add/swiftlint
Browse files Browse the repository at this point in the history
Add Swiftlint
  • Loading branch information
oguzkocer authored Mar 26, 2020
2 parents 81ffc90 + 1aef80f commit 6add300
Show file tree
Hide file tree
Showing 11 changed files with 106 additions and 25 deletions.
4 changes: 4 additions & 0 deletions .hound.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
fail_on_violations: true

swiftlint:
config_file: .swiftlint.yml
78 changes: 78 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Project configuration
excluded:
- Pods
- Scripts
- vendor

# Rules
whitelist_rules:
# Colons should be next to the identifier when specifying a type.
- colon

# There should be no space before and one after any comma.
- comma

# if,for,while,do statements shouldn't wrap their conditionals in parentheses.
- control_statement

# Arguments can be omitted when matching enums with associated types if they
# are not used.
- empty_enum_arguments

# Prefer `() -> ` over `Void -> `.
- empty_parameters

# MARK comment should be in valid format.
- mark

# Opening braces should be preceded by a single space and on the same line as
# the declaration.
- opening_brace

# Files should have a single trailing newline.
- trailing_newline

# Lines should not have trailing semicolons.
- trailing_semicolon

# Lines should not have trailing whitespace.
- trailing_whitespace

- custom_rules

# Rules configuration

control_statement:
severity: error

custom_rules:

natural_content_alignment:
name: "Natural Content Alignment"
regex: '\.contentHorizontalAlignment(\s*)=(\s*)(\.left|\.right)'
message: "Forcing content alignment left or right can affect the Right-to-Left layout. Use naturalContentHorizontalAlignment instead."
severity: warning

natural_text_alignment:
name: "Natural Text Alignment"
regex: '\.textAlignment(\s*)=(\s*).left'
message: "Forcing text alignment to left can affect the Right-to-Left layout. Consider setting it to `natural`"
severity: warning

inverse_text_alignment:
name: "Inverse Text Alignment"
regex: '\.textAlignment(\s*)=(\s*).right'
message: "When forcing text alignment to the right, be sure to handle the Right-to-Left layout case properly, and then silence this warning with this line `// swiftlint:disable:next inverse_text_alignment`"
severity: warning

localization_comment:
name: "Localization Comment"
regex: 'NSLocalizedString([^,]+,\s+comment:\s*"")'
message: "Localized strings should include a description giving context for how the string is used."
severity: warning

string_interpolation_in_localized_string:
name: "String Interpolation in Localized String"
regex: 'NSLocalizedString\("[^"]*\\\(\S*\)'
message: "Localized strings must not use interpolated variables. Instead, use `String(format:`"
severity: error
6 changes: 3 additions & 3 deletions Automattic-Tracks-iOS/Crash Logging/CrashLogging.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class CrashLogging {
get {
return threadSafeDispatchQueue.sync { _isStarted }
}
set{
set {
threadSafeDispatchQueue.sync { _isStarted = newValue }
}
}
Expand Down Expand Up @@ -107,7 +107,7 @@ public extension CrashLogging {
- userInfo: A dictionary containing additional data about this error.
- level: The level of severity to report in Sentry (`.error` by default)
*/
static func logError(_ error: Error, userInfo: [String : Any]? = nil, level: SentrySeverity = .error) {
static func logError(_ error: Error, userInfo: [String: Any]? = nil, level: SentrySeverity = .error) {
let event = Event(level: .error)
event.message = error.localizedDescription
event.extra = userInfo ?? (error as NSError).userInfo
Expand All @@ -127,7 +127,7 @@ public extension CrashLogging {
- properties: A dictionary containing additional information about this error
- level: The level of severity to report in Sentry (`.error` by default)
*/
static func logMessage(_ message: String, properties: [String : Any]? = nil, level: SentrySeverity = .info) {
static func logMessage(_ message: String, properties: [String: Any]? = nil, level: SentrySeverity = .info) {

let event = Event(level: level)
event.message = message
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ public protocol CrashLoggingDataProvider {
var buildType: String { get }
var releaseName: String { get }
var currentUser: TracksUser? { get }
var additionalUserData: [String : Any] { get }
var additionalUserData: [String: Any] { get }
}

/// Default implementations of common protocol properties
public extension CrashLoggingDataProvider {

var releaseName: String {
return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
}

var additionalUserData: [String : Any] {
var additionalUserData: [String: Any] {
return [ : ]
}
}
4 changes: 2 additions & 2 deletions Automattic-Tracks-iOS/Crash Logging/TestHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ internal extension CrashLogging {
var cachedUser: TracksUser? {
guard
let context = currentContext,
let userData = context["user"] as? [String : Any]
let userData = context["user"] as? [String: Any]
else { return nil }

let userID = userData["id"] as? String
Expand All @@ -42,7 +42,7 @@ internal extension CrashLogging {
}

/// Refresh the context from disk, then return it
var currentContext: [String : Any]? {
var currentContext: [String: Any]? {
Client.shared?.perform(Selector(("restoreContextBeforeCrash")))
return Client.shared?.lastContext
}
Expand Down
2 changes: 1 addition & 1 deletion Automattic-Tracks-iOS/Model/TracksUser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ internal extension TracksUser {
return user
}

func sentryUser(withData additionalUserData: [String : Any]) -> Sentry.User {
func sentryUser(withData additionalUserData: [String: Any]) -> Sentry.User {
let user = self.sentryUser
user.extra = additionalUserData
return user
Expand Down
2 changes: 1 addition & 1 deletion Automattic-Tracks-iOSTests/Test Helpers/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Sodium
extension String {
static func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
return String((0..<length).map { _ in letters.randomElement()! })
}

var base64Decoded: Bytes {
Expand Down
2 changes: 1 addition & 1 deletion Automattic-Tracks-iOSTests/Tests/CrashLoggingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ private extension CrashLoggingTests {
var testUser: TracksUser { return TracksUser(userID: "foo", email: "bar", username: "baz") }
}

private class MockCrashLoggingDataProvider : CrashLoggingDataProvider {
private class MockCrashLoggingDataProvider: CrashLoggingDataProvider {
var sentryDSN: String = ""
var userHasOptedOut: Bool = false
var buildType: String = "test"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class TracksServiceRemoteTests: XCTestCase {

subject = TracksServiceRemote()
}

override func tearDown() {
super.tearDown()

Expand All @@ -28,7 +28,7 @@ class TracksServiceRemoteTests: XCTestCase {
return HTTPStubsResponse(data: stubData!, statusCode: 200, headers: ["Content-Type": "application/json"])
}

subject.sendBatch(of: events, withSharedProperties: [NSObject : AnyObject]()) {
subject.sendBatch(of: events, withSharedProperties: [NSObject: AnyObject]()) {
error in
expect.fulfill()

Expand All @@ -48,7 +48,7 @@ class TracksServiceRemoteTests: XCTestCase {
return HTTPStubsResponse(data: stubData!, statusCode: 200, headers: ["Content-Type": "application/json"])
}

subject.sendBatch(of: events, withSharedProperties: [NSObject : AnyObject]()) {
subject.sendBatch(of: events, withSharedProperties: [NSObject: AnyObject]()) {
error in
expect.fulfill()
XCTAssertNotNil(error)
Expand All @@ -72,7 +72,7 @@ class TracksServiceRemoteTests: XCTestCase {
return HTTPStubsResponse(data: stubData!, statusCode: 500, headers: ["Content-Type": "application/json"])
}

subject.sendBatch(of: events, withSharedProperties: [NSObject : AnyObject]()) {
subject.sendBatch(of: events, withSharedProperties: [NSObject: AnyObject]()) {
error in
expect.fulfill()
XCTAssertNotNil(error)
Expand Down
1 change: 0 additions & 1 deletion TracksDemo/TracksDemo Mac/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,3 @@ class AppDelegate: NSObject, NSApplicationDelegate {


}

18 changes: 9 additions & 9 deletions TracksDemo/TracksDemo Mac/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ class ViewController: NSViewController {

@IBOutlet var progressView: NSProgressIndicator!
@IBOutlet weak var queuedEventsLabel: NSTextField!

var sendInterval: TimeInterval {
get{ return tracksService?.queueSendInterval ?? 10 }
get { return tracksService?.queueSendInterval ?? 10 }
set { tracksService?.queueSendInterval = newValue}
}

Expand All @@ -32,7 +32,7 @@ class ViewController: NSViewController {
NotificationCenter.default.removeObserver(self)
}

//MARK: - IB Action Methods
// MARK: - IB Action Methods
@IBAction func didClickTrackEvent(_ sender: NSButton) {
tracksService?.trackEventName("test_event")
}
Expand Down Expand Up @@ -62,13 +62,13 @@ class ViewController: NSViewController {
if sender.state == .on {
resetTimer()
}
else{
else {
timer.invalidate()
}
}

//MARK: – Fetched Results Controller
private func setupFetchedResultsController(){
// MARK: – Fetched Results Controller
private func setupFetchedResultsController() {
let fetchRequest = NSFetchRequest<TracksEventCoreData>(entityName: "TracksEvent")
fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "date", ascending: true) ]

Expand All @@ -80,15 +80,15 @@ class ViewController: NSViewController {

self.fetchedResultsController.delegate = self

do{
do {
try self.fetchedResultsController.performFetch()
}
catch let err {
debugPrint("Error fetching Tracks Events: \(err.localizedDescription)")
}
}

//MARK: - Timer
// MARK: - Timer
private lazy var timer = Timer()
private var startTime: Date!

Expand All @@ -114,7 +114,7 @@ class ViewController: NSViewController {
progressView.doubleValue = progress * 100
}

//MARK: - Helpers
// MARK: - Helpers
private func updateObjectCountLabel() {
let count = fetchedResultsController.fetchedObjects?.count ?? 0
queuedEventsLabel.stringValue = "Number of events queued: \(count)"
Expand Down

0 comments on commit 6add300

Please sign in to comment.