Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Include Swiftlint in the project
* Include the Run Script Phase to use Swiftlint in the project with the `.swiftlint.yml`
* Fix all the errors and warnings regarding Swiftlint violations
  • Loading branch information
Vkt0r committed Apr 21, 2019
commit 1e906791372dbcc27f05bfbc9478bde137fbb81d
18 changes: 17 additions & 1 deletion .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@

identifier_name:
min_length: # only min_length
warning: 2
error: 2 # only error
excluded: # excluded via string array
- ok
- Name
- DEFAULT_MIME_TYPE
- sin_port
- no_sig_pipe

disabled_rules:
- line_length
- statement_position
- trailing_whitespace
- variable_name_min_length

excluded: # paths to ignore during linting. Takes precedence over `included`.
- LinuxMain.swift
- Tests/XCTestManifests.swift
- Package.swift
60 changes: 30 additions & 30 deletions Sources/DemoServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import Foundation


// swiftlint:disable function_body_length
public func demoServer(_ publicDir: String) -> HttpServer {

print(publicDir)
Expand All @@ -32,17 +32,17 @@ public func demoServer(_ publicDir: String) -> HttpServer {

server["/magic"] = { .ok(.html("You asked for " + $0.path)) }

server["/test/:param1/:param2"] = { r in
server["/test/:param1/:param2"] = { request in
scopes {
html {
body {
h3 { inner = "Address: \(r.address ?? "unknown")" }
h3 { inner = "Url: \(r.path)" }
h3 { inner = "Method: \(r.method)" }
h3 { inner = "Address: \(request.address ?? "unknown")" }
h3 { inner = "Url: \(request.path)" }
h3 { inner = "Method: \(request.method)" }

h3 { inner = "Query:" }

table(r.queryParams) { param in
table(request.queryParams) { param in
tr {
td { inner = param.0 }
td { inner = param.1 }
Expand All @@ -51,7 +51,7 @@ public func demoServer(_ publicDir: String) -> HttpServer {

h3 { inner = "Headers:" }

table(r.headers) { header in
table(request.headers) { header in
tr {
td { inner = header.0 }
td { inner = header.1 }
Expand All @@ -60,15 +60,15 @@ public func demoServer(_ publicDir: String) -> HttpServer {

h3 { inner = "Route params:" }

table(r.params) { param in
table(request.params) { param in
tr {
td { inner = param.0 }
td { inner = param.1 }
}
}
}
}
}(r)
}(request)
}

server.GET["/upload"] = scopes {
Expand All @@ -92,9 +92,9 @@ public func demoServer(_ publicDir: String) -> HttpServer {
}
}

server.POST["/upload"] = { r in
server.POST["/upload"] = { request in
var response = ""
for multipart in r.parseMultiPartFormData() {
for multipart in request.parseMultiPartFormData() {
guard let name = multipart.name, let fileName = multipart.fileName else { continue }
response += "Name: \(name) File name: \(fileName) Size: \(multipart.body.count)<br>"
}
Expand Down Expand Up @@ -134,8 +134,8 @@ public func demoServer(_ publicDir: String) -> HttpServer {
}
}

server.POST["/login"] = { r in
let formFields = r.parseUrlencodedForm()
server.POST["/login"] = { request in
let formFields = request.parseUrlencodedForm()
return HttpResponse.ok(.html(formFields.map({ "\($0.0) = \($0.1)" }).joined(separator: "<br>")))
}

Expand All @@ -150,32 +150,32 @@ public func demoServer(_ publicDir: String) -> HttpServer {
}
}

server["/raw"] = { r in
server["/raw"] = { _ in
return HttpResponse.raw(200, "OK", ["XXX-Custom-Header": "value"], { try $0.write([UInt8]("test".utf8)) })
}

server["/redirect/permanently"] = { r in
server["/redirect/permanently"] = { _ in
return .movedPermanently("http://www.google.com")
}

server["/redirect/temporarily"] = { r in
server["/redirect/temporarily"] = { _ in
return .movedTemporarily("http://www.google.com")
}

server["/long"] = { r in
server["/long"] = { _ in
var longResponse = ""
for k in 0..<1000 { longResponse += "(\(k)),->" }
for index in 0..<1000 { longResponse += "(\(index)),->" }
return .ok(.html(longResponse))
}

server["/wildcard/*/test/*/:param"] = { r in
return .ok(.html(r.path))
server["/wildcard/*/test/*/:param"] = { request in
return .ok(.html(request.path))
}

server["/stream"] = { r in
return HttpResponse.raw(200, "OK", nil, { w in
for i in 0...100 {
try w.write([UInt8]("[chunk \(i)]".utf8))
server["/stream"] = { _ in
return HttpResponse.raw(200, "OK", nil, { writer in
for index in 0...100 {
try writer.write([UInt8]("[chunk \(index)]".utf8))
}
})
}
Expand All @@ -184,20 +184,20 @@ public func demoServer(_ publicDir: String) -> HttpServer {
session.writeText(text)
}, binary: { (session, binary) in
session.writeBinary(binary)
}, pong: { (session, pong) in
}, pong: { (_, _) in
// Got a pong frame
}, connected: { (session) in
}, connected: { _ in
// New client connected
}, disconnected: { (session) in
}, disconnected: { _ in
// Client disconnected
})

server.notFoundHandler = { r in
server.notFoundHandler = { _ in
return .movedPermanently("https://github.com/404")
}

server.middleware.append { r in
print("Middleware: \(r.address ?? "unknown address") -> \(r.method) -> \(r.path)")
server.middleware.append { request in
print("Middleware: \(request.address ?? "unknown address") -> \(request.method) -> \(request.path)")
return nil
}

Expand Down
16 changes: 8 additions & 8 deletions Sources/Files.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import Foundation

public func shareFile(_ path: String) -> ((HttpRequest) -> HttpResponse) {
return { r in
return { _ in
if let file = try? path.openForReading() {
return .raw(200, "OK", [:], { writer in
try? writer.write(file)
Expand All @@ -20,8 +20,8 @@ public func shareFile(_ path: String) -> ((HttpRequest) -> HttpResponse) {
}

public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String] = ["index.html", "default.html"]) -> ((HttpRequest) -> HttpResponse) {
return { r in
guard let fileRelativePath = r.params.first else {
return { request in
guard let fileRelativePath = request.params.first else {
return .notFound
}
if fileRelativePath.value.isEmpty {
Expand All @@ -35,7 +35,7 @@ public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String]
}
}
if let file = try? (directoryPath + String.pathSeparator + fileRelativePath.value).openForReading() {
let mimeType = fileRelativePath.value.mimeType();
let mimeType = fileRelativePath.value.mimeType()

return .raw(200, "OK", ["Content-Type": mimeType], { writer in
try? writer.write(file)
Expand All @@ -47,8 +47,8 @@ public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String]
}

public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) {
return { r in
guard let (_, value) = r.params.first else {
return { request in
guard let (_, value) = request.params.first else {
return HttpResponse.notFound
}
let filePath = dir + String.pathSeparator + value
Expand All @@ -66,15 +66,15 @@ public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) {
tr {
td {
a {
href = r.path + "/" + file
href = request.path + "/" + file
inner = file
}
}
}
}
}
}
}(r)
}(request)
} else {
guard let file = try? filePath.openForReading() else {
return .notFound
Expand Down
32 changes: 16 additions & 16 deletions Sources/HttpParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import Foundation

enum HttpParserError: Error {
case InvalidStatusLine(String)
case invalidStatusLine(String)
}

public class HttpParser {
Expand All @@ -19,7 +19,7 @@ public class HttpParser {
let statusLine = try socket.readLine()
let statusLineTokens = statusLine.components(separatedBy: " ")
if statusLineTokens.count < 3 {
throw HttpParserError.InvalidStatusLine(statusLine)
throw HttpParserError.invalidStatusLine(statusLine)
}
let request = HttpRequest()
request.method = statusLineTokens[0]
Expand Down Expand Up @@ -53,27 +53,27 @@ public class HttpParser {
#endif

return query.components(separatedBy: "&")
.reduce([(String, String)]()) { (c, s) -> [(String, String)] in
.reduce([(String, String)]()) { (result, stringValue) -> [(String, String)] in
#if compiler(>=5.0)
guard let nameEndIndex = s.firstIndex(of: "=") else {
return c
guard let nameEndIndex = stringValue.firstIndex(of: "=") else {
return result
}
#else
guard let nameEndIndex = s.index(of: "=") else {
return c
guard let nameEndIndex = stringValue.index(of: "=") else {
return result
}
#endif
guard let name = String(s[s.startIndex..<nameEndIndex]).removingPercentEncoding else {
return c
guard let name = String(stringValue[stringValue.startIndex..<nameEndIndex]).removingPercentEncoding else {
return result
}
let valueStartIndex = s.index(nameEndIndex, offsetBy: 1)
guard valueStartIndex < s.endIndex else {
return c + [(name, "")]
let valueStartIndex = stringValue.index(nameEndIndex, offsetBy: 1)
guard valueStartIndex < stringValue.endIndex else {
return result + [(name, "")]
}
guard let value = String(s[valueStartIndex..<s.endIndex]).removingPercentEncoding else {
return c + [(name, "")]
guard let value = String(stringValue[valueStartIndex..<stringValue.endIndex]).removingPercentEncoding else {
return result + [(name, "")]
}
return c + [(name, value)]
return result + [(name, value)]
}
}

Expand All @@ -83,7 +83,7 @@ public class HttpParser {

private func readHeaders(_ socket: Socket) throws -> [String: String] {
var headers = [String: String]()
while case let headerLine = try socket.readLine() , !headerLine.isEmpty {
while case let headerLine = try socket.readLine(), !headerLine.isEmpty {
let headerTokens = headerLine.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: true).map(String.init)
if let name = headerTokens.first, let value = headerTokens.last {
headers[name.lowercased()] = value.trimmingCharacters(in: .whitespaces)
Expand Down
7 changes: 4 additions & 3 deletions Sources/HttpRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class HttpRequest {
return (name.replacingOccurrences(of: "+", with: " "),
value.replacingOccurrences(of: "+", with: " "))
}
return ("","")
return ("", "")
}
}

Expand Down Expand Up @@ -86,7 +86,7 @@ public class HttpRequest {
guard let contentType = contentTypeHeaderTokens.first, contentType == "multipart/form-data" else {
return []
}
var boundary: String? = nil
var boundary: String?
contentTypeHeaderTokens.forEach({
let tokens = $0.components(separatedBy: "=")
if let key = tokens.first, key == "boundary" && tokens.count == 2 {
Expand Down Expand Up @@ -142,13 +142,14 @@ public class HttpRequest {
return String(bytes: temp, encoding: String.Encoding.utf8)
}

// swiftlint:disable identifier_name
static let CR = UInt8(13)
static let NL = UInt8(10)

private func nextMultiPartBody(_ generator: inout IndexingIterator<[UInt8]>, boundary: String) -> [UInt8]? {
var body = [UInt8]()
let boundaryArray = [UInt8](boundary.utf8)
var matchOffset = 0;
var matchOffset = 0
while let x = generator.next() {
matchOffset = ( x == boundaryArray[matchOffset] ? matchOffset + 1 : 0 )
body.append(x)
Expand Down
Loading