Skip to content

Commit 9c2a1c4

Browse files
authored
Setup linting (#16)
1 parent 32739f7 commit 9c2a1c4

12 files changed

+155
-88
lines changed

.swiftlint.yml

Lines changed: 88 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,92 @@
1-
disabled_rules: # rule identifiers to exclude from running
2-
- line_length
3-
- trailing_whitespace
4-
- todo # temporarily disabled. In general they should be treated as warnings
5-
# - type_body_length # temporarily disabled.
6-
# - file_length # temporarily disabled
7-
- statement_position # wish we could support both uncuddled_else and default (but not others)
8-
- trailing_comma
9-
- syntactic_sugar
10-
- redundant_optional_initialization
11-
- redundant_void_return
12-
- large_tuple # this is flagging closure argument declarations, seems like a mistake
13-
opt_in_rules: # some rules are only opt-in
14-
- empty_count
15-
# - missing_docs
16-
# - force_unwrapping
17-
# Find all the available rules by running:
18-
# swiftlint rules
19-
# included: # paths to include during linting. `--path` is ignored if present.
20-
# # - Source
21-
excluded: # paths to ignore during linting. Takes precedence over `included`.
22-
# - Carthage
23-
- LaunchDarkly/GeneratedCode
24-
- Pods
25-
- _iOS/Pods
26-
# - Source/ExcludedFolder
27-
# - Source/ExcludedFile.swift
1+
# See sub-configurations at `Source/.swiftlint.yml` and `Tests/.swiftlint.yml`.
282

29-
# configurable rules can be customized from this configuration file
30-
# binary rules can set their severity level
3+
disabled_rules:
4+
- identifier_name
5+
- weak_delegate
316

32-
# force_cast: warning # implicitly
33-
# force_try:
34-
# severity: warning # explicitly
35-
# # rules that have both warning and error levels, can set just the warning level
36-
# # implicitly
37-
# # line_length: 110
38-
# # they can set both implicitly with an array
39-
#
7+
opt_in_rules:
8+
- anyobject_protocol
9+
- array_init
10+
- attributes
11+
- closure_body_length
12+
- closure_end_indentation
13+
- closure_spacing
14+
- collection_alignment
15+
- conditional_returns_on_newline
16+
- contains_over_filter_count
17+
- contains_over_filter_is_empty
18+
- contains_over_first_not_nil
19+
- contains_over_range_nil_comparison
20+
- discouraged_object_literal
21+
- discouraged_optional_boolean
22+
- discouraged_optional_collection
23+
- empty_collection_literal
24+
- empty_count
25+
- empty_string
26+
- empty_xctest_method
27+
- enum_case_associated_values_count
28+
- expiring_todo
29+
- explicit_init
30+
- explicit_self
31+
- extension_access_modifier
32+
- fallthrough
33+
- fatal_error_message
34+
- file_header
35+
- file_name_no_space
36+
- first_where
37+
- flatmap_over_map_reduce
38+
- function_default_parameter_at_end
39+
- identical_operands
40+
- implicit_return
41+
- joined_default_parameter
42+
- last_where
43+
- legacy_multiple
44+
- legacy_random
45+
- let_var_whitespace
46+
- literal_expression_end_indentation
47+
- missing_docs
48+
- modifier_order
49+
- no_grouping_extension
50+
- nslocalizedstring_key
51+
- nslocalizedstring_require_bundle
52+
- number_separator
53+
- object_literal
54+
- operator_usage_whitespace
55+
- optional_enum_case_matching
56+
- overridden_super_call
57+
- override_in_extension
58+
- pattern_matching_keywords
59+
- prefer_self_type_over_type_of_self
60+
- prefixed_toplevel_constant
61+
- private_action
62+
- private_outlet
63+
- prohibited_interface_builder
64+
- prohibited_super_call
65+
- raw_value_for_camel_cased_codable_enum
66+
- reduce_into
67+
- redundant_nil_coalescing
68+
- required_enum_case
69+
- single_test_class
70+
- sorted_first_last
71+
- static_operator
72+
- strict_fileprivate
73+
- strong_iboutlet
74+
- switch_case_on_newline
75+
- toggle_bool
76+
- trailing_closure
77+
- unavailable_function
78+
- unneeded_parentheses_in_closure_argument
79+
- unowned_variable_capture
80+
- untyped_error_in_catch
81+
- unused_declaration
82+
- unused_import
83+
- vertical_parameter_alignment_on_call
84+
- vertical_whitespace_closing_braces
85+
- vertical_whitespace_opening_braces
86+
- yoda_condition
4087

41-
# Set doesn't have isEmpty so using count seems to be our ownly option
42-
empty_count: warning
88+
included:
89+
- Source
90+
- Tests
4391

44-
function_body_length:
45-
warning: 50
46-
error: 70
47-
type_body_length:
48-
- 300 # warning
49-
- 500 # error
50-
# or they can set both explicitly
51-
file_length:
52-
warning: 1000
53-
error: 1500
54-
identifier_name:
55-
min_length: # only min_length
56-
error: 3 # only error
57-
max_length: # warning and error
58-
warning: 50
59-
error: 60
60-
excluded: # excluded via string array
61-
- id
62-
- URL
63-
- url
64-
- obj
65-
- key
66-
- all
67-
- tag
68-
- lhs
69-
- rhs
70-
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle)
92+
reporter: "xcode"

LDSwiftEventSource.xcodeproj/project.pbxproj

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@
143143
isa = PBXNativeTarget;
144144
buildConfigurationList = B49B5E0D24667D42008BF867 /* Build configuration list for PBXNativeTarget "LDSwiftEventSource" */;
145145
buildPhases = (
146+
B46C1C6B24CF348B00283630 /* Linter Script */,
146147
B49B5DF724667D41008BF867 /* Headers */,
147148
B49B5DF824667D41008BF867 /* Sources */,
148149
B49B5DF924667D41008BF867 /* Frameworks */,
@@ -229,6 +230,28 @@
229230
};
230231
/* End PBXResourcesBuildPhase section */
231232

233+
/* Begin PBXShellScriptBuildPhase section */
234+
B46C1C6B24CF348B00283630 /* Linter Script */ = {
235+
isa = PBXShellScriptBuildPhase;
236+
buildActionMask = 2147483647;
237+
files = (
238+
);
239+
inputFileListPaths = (
240+
);
241+
inputPaths = (
242+
);
243+
name = "Linter Script";
244+
outputFileListPaths = (
245+
);
246+
outputPaths = (
247+
);
248+
runOnlyForDeploymentPostprocessing = 0;
249+
shellPath = /bin/sh;
250+
shellScript = "echo `pwd`\nif which mint >/dev/null; then\n /usr/bin/xcrun --sdk macosx mint run realm/SwiftLint\nelse\n echo \"warning: mint not installed, available from https://github.com/yonaskolb/Mint\"\nfi\n";
251+
showEnvVarsInLog = 0;
252+
};
253+
/* End PBXShellScriptBuildPhase section */
254+
232255
/* Begin PBXSourcesBuildPhase section */
233256
B49B5DF824667D41008BF867 /* Sources */ = {
234257
isa = PBXSourcesBuildPhase;

Mintfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

Package.swift

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ let package = Package(
1111
.tvOS(.v10)
1212
],
1313
products: [
14-
// Products define the executables and libraries produced by a package, and make them visible to other packages.
1514
.library(
1615
name: "LDSwiftEventSource",
1716
type: .dynamic,
@@ -23,8 +22,6 @@ let package = Package(
2322
],
2423
dependencies: [],
2524
targets: [
26-
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
27-
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
2825
.target(
2926
name: "LDSwiftEventSource",
3027
path: "Source"),

Source/.swiftlint.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
disabled_rules:
2+
3+
opt_in_rules:
4+
- force_unwrapping
5+
- implicitly_unwrapped_optional

Source/EventParser.swift

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import Foundation
22

3-
typealias ConnectionHandler = (setReconnectionTime: (TimeInterval) -> (), setLastEventId: (String) -> ())
3+
typealias ConnectionHandler = (setReconnectionTime: (TimeInterval) -> Void, setLastEventId: (String) -> Void)
44

55
class EventParser {
66
private struct Constants {
@@ -58,7 +58,8 @@ class EventParser {
5858
if value.allSatisfy(("0"..."9").contains), let reconnectionTime = Int64(value) {
5959
connectionHandler.setReconnectionTime(Double(reconnectionTime) * 0.001)
6060
}
61-
default: break
61+
default:
62+
break
6263
}
6364
}
6465

@@ -78,6 +79,6 @@ class EventParser {
7879
private extension Array {
7980
/// Returns the element at the specified index if it is within bounds, otherwise nil.
8081
subscript (safe index: Index) -> Element? {
81-
return index >= startIndex && index < endIndex ? self[index] : nil
82+
index >= startIndex && index < endIndex ? self[index] : nil
8283
}
8384
}

Source/LDSwiftEventSource.swift

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import FoundationNetworking
88
import os.log
99
#endif
1010

11+
/**
12+
Provides an EventSource client for consuming Server-Sent Events.
13+
14+
See the [Server-Sent Events spec](https://html.spec.whatwg.org/multipage/server-sent-events.html) for more details.
15+
*/
1116
public class EventSource {
1217
private let esDelegate: EventSourceDelegate
1318

@@ -42,17 +47,19 @@ public class EventSource {
4247

4348
/// Struct describing the configuration of the EventSource
4449
public struct Config {
50+
/// The EventHandler called in response to activity on the stream.
4551
public let handler: EventHandler
52+
/// The URL of the request used when connecting to the EventSource API.
4653
public let url: URL
4754

4855
/// The method to use for the EventSource connection
4956
public var method: String = "GET"
5057
/// Optional body to be sent with the initial request
51-
public var body: Data? = nil
58+
public var body: Data?
5259
/// Error handler that can determine whether to proceed or shutdown.
5360
public var connectionErrorHandler: ConnectionErrorHandler = { _ in .proceed }
5461
/// An initial value for the last-event-id to be set on the initial request
55-
public var lastEventId: String? = nil
62+
public var lastEventId: String?
5663
/// Additional headers to be set on the request
5764
public var headers: [String: String] = [:]
5865
/// Provides the ability to add conditional headers
@@ -77,7 +84,6 @@ public class EventSource {
7784
}
7885

7986
class EventSourceDelegate: NSObject, URLSessionDataDelegate {
80-
8187
#if !os(Linux)
8288
private let logger: OSLog = OSLog(subsystem: "com.launchdarkly.swift-eventsource", category: "LDEventSource")
8389
#endif
@@ -93,8 +99,9 @@ class EventSourceDelegate: NSObject, URLSessionDataDelegate {
9399
private var connectedTime: Date?
94100

95101
private var reconnectionAttempts: Int = 0
96-
private var errorHandlerAction: ConnectionErrorAction? = nil
102+
private var errorHandlerAction: ConnectionErrorAction?
97103
private let utf8LineParser: UTF8LineParser = UTF8LineParser()
104+
// swiftlint:disable:next implicitly_unwrapped_optional
98105
private var eventParser: EventParser!
99106
private var sessionTask: URLSessionDataTask?
100107

@@ -109,7 +116,7 @@ class EventSourceDelegate: NSObject, URLSessionDataDelegate {
109116
guard self.readyState == .raw
110117
else {
111118
#if !os(Linux)
112-
os_log("Start method called on this already-started EventSource object. Doing nothing", log: self.logger, type: .info)
119+
os_log("start() called on already-started EventSource object. Returning", log: self.logger, type: .info)
113120
#endif
114121
return
115122
}
@@ -139,7 +146,7 @@ class EventSourceDelegate: NSObject, URLSessionDataDelegate {
139146
let sessionConfig = URLSessionConfiguration.default
140147
sessionConfig.httpAdditionalHeaders = ["Accept": "text/event-stream", "Cache-Control": "no-cache"]
141148
sessionConfig.timeoutIntervalForRequest = self.config.idleTimeout
142-
let session = URLSession.init(configuration: sessionConfig, delegate: self, delegateQueue: nil)
149+
let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
143150
var urlRequest = URLRequest(url: self.config.url,
144151
cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData,
145152
timeoutInterval: self.config.idleTimeout)
@@ -194,7 +201,7 @@ class EventSourceDelegate: NSObject, URLSessionDataDelegate {
194201
self.connectedTime = nil
195202

196203
let maxSleep = min(config.maxReconnectTime, reconnectTime * pow(2.0, Double(reconnectionAttempts)))
197-
let sleep = maxSleep / 2 + Double.random(in: 0...(maxSleep/2))
204+
let sleep = maxSleep / 2 + Double.random(in: 0...(maxSleep / 2))
198205

199206
#if !os(Linux)
200207
os_log("Waiting %.3f seconds before reconnecting...", log: logger, type: .info, sleep)
@@ -239,6 +246,7 @@ class EventSourceDelegate: NSObject, URLSessionDataDelegate {
239246
os_log("initial reply received", log: logger, type: .debug)
240247
#endif
241248

249+
// swiftlint:disable:next force_cast
242250
let httpResponse = response as! HTTPURLResponse
243251
if (200..<300).contains(httpResponse.statusCode) {
244252
connectedTime = Date()

Source/UTF8LineParser.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ class UTF8LineParser {
3737

3838
Decode: while true {
3939
switch utf8Parser.parseScalar(from: &dataIter) {
40-
case .valid(let v):
41-
let scalar = Unicode.UTF8.decode(v)
40+
case .valid(let scalarResult):
41+
let scalar = Unicode.UTF8.decode(scalarResult)
4242
if seenCr {
4343
lines.append(currentString)
4444
currentString = ""

Tests/.swiftlint.yml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
disabled_rules:
2+
3+
opt_in_rules:
4+
# Must specify even though enabled by default to update configuration of rule below.
5+
- line_length
6+
7+
# Provide a little extra lenience for test code line length.
8+
line_length:
9+
warning: 140
10+
11+
excluded:
12+
# Autogenerated manifest of tests
13+
- XCTestManifests.swift

Tests/EventParserTests.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,15 @@ class MockEventHandler: EventHandler {
2828
}
2929

3030
final class EventParserTests: XCTestCase {
31-
var receivedReconnectionTime: TimeInterval? = nil
32-
var receivedLastEventId: String? = nil
31+
var receivedReconnectionTime: TimeInterval?
32+
var receivedLastEventId: String?
3333
lazy var connectionHandler: ConnectionHandler = { (setReconnectionTime: { self.receivedReconnectionTime = $0 },
3434
setLastEventId: { self.receivedLastEventId = $0 }) }()
3535
let eventHandler = MockEventHandler()
3636
var parser: EventParser!
3737

3838
override func setUp() {
39+
super.setUp()
3940
receivedReconnectionTime = nil
4041
receivedLastEventId = nil
4142
eventHandler.reset()

0 commit comments

Comments
 (0)