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

Update swiftformat #196

Merged
merged 1 commit into from
Mar 26, 2021
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
7 changes: 6 additions & 1 deletion .swiftformat
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# file options

--swiftversion 5.1
--swiftversion 5.2
--exclude .build

# format options
Expand All @@ -9,5 +9,10 @@
--patternlet inline
--stripunusedargs unnamed-only
--ifdef no-indent
--extensionacl on-declarations
--disable typeSugar
--disable andOperator
--disable wrapMultilineStatementBraces
--disable enumNamespaces

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please disable the enum namespaces

# rules
17 changes: 9 additions & 8 deletions Examples/LambdaFunctions/Sources/CurrencyExchange/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ struct ExchangeRatesCalculator {
monthIndex: Array<Date>.Index,
currencies: [String],
state: [Date: ExchangeRates],
callback: @escaping ((Result<[Date: ExchangeRates], Swift.Error>) -> Void)) {
callback: @escaping ((Result<[Date: ExchangeRates], Swift.Error>) -> Void))
{
if monthIndex == months.count {
return callback(.success(state))
}
Expand Down Expand Up @@ -145,16 +146,16 @@ struct ExchangeRatesCalculator {
dateFormatter.dateFormat = "dd/MMM/yy"
let interval: DateInterval?
if let period = try document.nodes(forXPath: "/exchangeRateMonthList/@Period").first?.stringValue,
period.count == 26 {
period.count == 26 {
// "01/Sep/2018 to 30/Sep/2018"
let startString = period[period.startIndex ..< period.index(period.startIndex, offsetBy: 11)]
let to = period[startString.endIndex ..< period.index(startString.endIndex, offsetBy: 4)]
let endString = period[to.endIndex ..< period.index(to.endIndex, offsetBy: 11)]
if let startDate = dateFormatter.date(from: String(startString)),
let startDay = calendar.dateInterval(of: .day, for: startDate),
to == " to ",
let endDate = dateFormatter.date(from: String(endString)),
let endDay = calendar.dateInterval(of: .day, for: endDate) {
let startDay = calendar.dateInterval(of: .day, for: startDate),
to == " to ",
let endDate = dateFormatter.date(from: String(endString)),
let endDay = calendar.dateInterval(of: .day, for: endDate) {
interval = DateInterval(start: startDay.start, end: endDay.end)
} else {
interval = nil
Expand All @@ -166,8 +167,8 @@ struct ExchangeRatesCalculator {
let ratesByCurrencyCode: [String: Decimal?] = Dictionary(uniqueKeysWithValues: try currencyCodes.map {
let xpathCurrency = $0.replacingOccurrences(of: "'", with: "&apos;")
if let rateString = try document.nodes(forXPath: "/exchangeRateMonthList/exchangeRate/currencyCode[text()='\(xpathCurrency)']/../rateNew/text()").first?.stringValue,
// We must parse the decimal data using the UK locale, not the system one.
let rate = Decimal(string: rateString, locale: self.locale) {
// We must parse the decimal data using the UK locale, not the system one.
let rate = Decimal(string: rateString, locale: self.locale) {
return ($0, rate)
} else {
return ($0, nil)
Expand Down
6 changes: 3 additions & 3 deletions Sources/AWSLambdaEvents/AppSync.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ public enum AppSync {
}
}

public extension AppSync {
enum Response<ResultType: Encodable>: Encodable {
extension AppSync {
public enum Response<ResultType: Encodable>: Encodable {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these are good actually 👍

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
Expand All @@ -165,5 +165,5 @@ public extension AppSync {
case dictionary([String: ResultType])
}

typealias JSONStringResponse = Response<String>
public typealias JSONStringResponse = Response<String>
}
4 changes: 2 additions & 2 deletions Sources/AWSLambdaEvents/Cloudwatch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ public protocol CloudwatchDetail: Decodable {
static var name: String { get }
}

public extension CloudwatchDetail {
var detailType: String {
extension CloudwatchDetail {
public var detailType: String {
Self.name
}
}
Expand Down
32 changes: 12 additions & 20 deletions Sources/AWSLambdaEvents/DynamoDB.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import struct Foundation.Date

// https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html
public struct DynamoDB {
public enum DynamoDB {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that is honestly crazy... a formatter changing types just because it feels like it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea this is nasty imo - is there an option to turn this off?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I think this pretty clever... It detect's that this is used as a namespace and makes it explicit:

enumNamespaces -> Converts types used for hosting only static members into enums.
https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md#enumnamespaces

Copy link
Contributor

@ktoso ktoso Mar 16, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's NOT up to a formatting tool to decide how I'm designing and using types. I.e. it's a struct because it will gain fields in the future etc.

We really should not allow this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, its clever, but it should a human decision to change a type not a formatting tool

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I disabled the matching swiftformat rule. Since this change is actually clever in this case, do we want to keep it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changing an enum to a struct is also API breaking...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@weissi we go the other way though. struct -> enum. just out of curiosity: in which way would enum -> struct be source breaking, if it is just about a namespace?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import enum Foo.Bar

will break. No tool should ever switch enum to or from struct (or class or something). The programmer needs to decide.

public struct Event: Decodable {
public let records: [EventRecord]

Expand Down Expand Up @@ -311,14 +311,12 @@ extension DynamoDB {
public init() {}

@inlinable public func decode<T: Decodable>(_ type: T.Type, from image: [String: AttributeValue])
throws -> T
{
throws -> T {
try self.decode(type, from: .map(image))
}

@inlinable public func decode<T: Decodable>(_ type: T.Type, from value: AttributeValue)
throws -> T
{
throws -> T {
let decoder = _DecoderImpl(userInfo: userInfo, from: value, codingPath: [])
return try decoder.decode(T.self)
}
Expand Down Expand Up @@ -511,7 +509,7 @@ extension DynamoDB {

func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws
-> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
return try self.decoderForKey(key).container(keyedBy: type)
try self.decoderForKey(key).container(keyedBy: type)
}

func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer {
Expand Down Expand Up @@ -557,8 +555,7 @@ extension DynamoDB {
}

@inline(__always) private func decodeFixedWidthInteger<T: FixedWidthInteger>(key: Self.Key)
throws -> T
{
throws -> T {
let value = try getValue(forKey: key)

guard case .number(let number) = value else {
Expand All @@ -577,8 +574,7 @@ extension DynamoDB {
}

@inline(__always) private func decodeLosslessStringConvertible<T: LosslessStringConvertible>(
key: Self.Key) throws -> T
{
key: Self.Key) throws -> T {
let value = try getValue(forKey: key)

guard case .number(let number) = value else {
Expand Down Expand Up @@ -677,7 +673,7 @@ extension DynamoDB {
}

func decode<T>(_: T.Type) throws -> T where T: Decodable {
return try T(from: self.impl)
try T(from: self.impl)
}

@inline(__always) private func createTypeMismatchError(type: Any.Type, value: AttributeValue) -> DecodingError {
Expand All @@ -688,8 +684,7 @@ extension DynamoDB {
}

@inline(__always) private func decodeFixedWidthInteger<T: FixedWidthInteger>() throws
-> T
{
-> T {
guard case .number(let number) = self.value else {
throw self.createTypeMismatchError(type: T.self, value: self.value)
}
Expand All @@ -705,8 +700,7 @@ extension DynamoDB {
}

@inline(__always) private func decodeLosslessStringConvertible<T: LosslessStringConvertible>()
throws -> T
{
throws -> T {
guard case .number(let number) = self.value else {
throw self.createTypeMismatchError(type: T.self, value: self.value)
}
Expand Down Expand Up @@ -850,7 +844,7 @@ extension DynamoDB {

mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws
-> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
return try self.impl.container(keyedBy: type)
try self.impl.container(keyedBy: type)
}

mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
Expand All @@ -869,8 +863,7 @@ extension DynamoDB {
}

@inline(__always) private mutating func decodeFixedWidthInteger<T: FixedWidthInteger>() throws
-> T
{
-> T {
defer {
currentIndex += 1
if currentIndex == count {
Expand All @@ -891,8 +884,7 @@ extension DynamoDB {
}

@inline(__always) private mutating func decodeLosslessStringConvertible<T: LosslessStringConvertible>()
throws -> T
{
throws -> T {
defer {
currentIndex += 1
if currentIndex == count {
Expand Down
22 changes: 11 additions & 11 deletions Sources/AWSLambdaRuntime/Lambda+Codable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,31 +79,31 @@ internal struct CodableVoidClosureWrapper<In: Decodable>: LambdaHandler {
}

/// Implementation of a`ByteBuffer` to `In` decoding
public extension EventLoopLambdaHandler where In: Decodable {
func decode(buffer: ByteBuffer) throws -> In {
extension EventLoopLambdaHandler where In: Decodable {
public func decode(buffer: ByteBuffer) throws -> In {
try self.decoder.decode(In.self, from: buffer)
}
}

/// Implementation of `Out` to `ByteBuffer` encoding
public extension EventLoopLambdaHandler where Out: Encodable {
func encode(allocator: ByteBufferAllocator, value: Out) throws -> ByteBuffer? {
extension EventLoopLambdaHandler where Out: Encodable {
public func encode(allocator: ByteBufferAllocator, value: Out) throws -> ByteBuffer? {
try self.encoder.encode(value, using: allocator)
}
}

/// Default `ByteBuffer` to `In` decoder using Foundation's JSONDecoder
/// Advanced users that want to inject their own codec can do it by overriding these functions.
public extension EventLoopLambdaHandler where In: Decodable {
var decoder: LambdaCodableDecoder {
extension EventLoopLambdaHandler where In: Decodable {
public var decoder: LambdaCodableDecoder {
Lambda.defaultJSONDecoder
}
}

/// Default `Out` to `ByteBuffer` encoder using Foundation's JSONEncoder
/// Advanced users that want to inject their own codec can do it by overriding these functions.
public extension EventLoopLambdaHandler where Out: Encodable {
var encoder: LambdaCodableEncoder {
extension EventLoopLambdaHandler where Out: Encodable {
public var encoder: LambdaCodableEncoder {
Lambda.defaultJSONEncoder
}
}
Expand All @@ -116,9 +116,9 @@ public protocol LambdaCodableEncoder {
func encode<T: Encodable>(_ value: T, using allocator: ByteBufferAllocator) throws -> ByteBuffer
}

private extension Lambda {
static let defaultJSONDecoder = JSONDecoder()
static let defaultJSONEncoder = JSONEncoder()
extension Lambda {
fileprivate static let defaultJSONDecoder = JSONDecoder()
fileprivate static let defaultJSONEncoder = JSONEncoder()
}

extension JSONDecoder: LambdaCodableDecoder {}
Expand Down
8 changes: 4 additions & 4 deletions Sources/AWSLambdaRuntimeCore/Lambda+String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ internal struct StringVoidClosureWrapper: LambdaHandler {
}
}

public extension EventLoopLambdaHandler where In == String {
extension EventLoopLambdaHandler where In == String {
/// Implementation of a `ByteBuffer` to `String` decoding
func decode(buffer: ByteBuffer) throws -> String {
public func decode(buffer: ByteBuffer) throws -> String {
var buffer = buffer
guard let string = buffer.readString(length: buffer.readableBytes) else {
fatalError("buffer.readString(length: buffer.readableBytes) failed")
Expand All @@ -97,9 +97,9 @@ public extension EventLoopLambdaHandler where In == String {
}
}

public extension EventLoopLambdaHandler where Out == String {
extension EventLoopLambdaHandler where Out == String {
/// Implementation of `String` to `ByteBuffer` encoding
func encode(allocator: ByteBufferAllocator, value: String) throws -> ByteBuffer? {
public func encode(allocator: ByteBufferAllocator, value: String) throws -> ByteBuffer? {
// FIXME: reusable buffer
var buffer = allocator.buffer(capacity: value.utf8.count)
buffer.writeString(value)
Expand Down
3 changes: 2 additions & 1 deletion Sources/AWSLambdaRuntimeCore/LambdaContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ extension Lambda {
clientContext: String? = nil,
logger: Logger,
eventLoop: EventLoop,
allocator: ByteBufferAllocator) {
allocator: ByteBufferAllocator)
{
self.requestID = requestID
self.traceID = traceID
self.invokedFunctionARN = invokedFunctionARN
Expand Down
28 changes: 14 additions & 14 deletions Sources/AWSLambdaRuntimeCore/LambdaHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,20 @@ public protocol LambdaHandler: EventLoopLambdaHandler {
func handle(context: Lambda.Context, event: In, callback: @escaping (Result<Out, Error>) -> Void)
}

internal extension Lambda {
static let defaultOffloadQueue = DispatchQueue(label: "LambdaHandler.offload")
extension Lambda {
internal static let defaultOffloadQueue = DispatchQueue(label: "LambdaHandler.offload")
}

public extension LambdaHandler {
extension LambdaHandler {
/// The queue on which `handle` is invoked on.
var offloadQueue: DispatchQueue {
public var offloadQueue: DispatchQueue {
Lambda.defaultOffloadQueue
}

/// `LambdaHandler` is offloading the processing to a `DispatchQueue`
/// This is slower but safer, in case the implementation blocks the `EventLoop`
/// Performance sensitive Lambdas should be based on `EventLoopLambdaHandler` which does not offload.
func handle(context: Lambda.Context, event: In) -> EventLoopFuture<Out> {
public func handle(context: Lambda.Context, event: In) -> EventLoopFuture<Out> {
let promise = context.eventLoop.makePromise(of: Out.self)
// FIXME: reusable DispatchQueue
self.offloadQueue.async {
Expand All @@ -62,8 +62,8 @@ public extension LambdaHandler {
}
}

public extension LambdaHandler {
func shutdown(context: Lambda.ShutdownContext) -> EventLoopFuture<Void> {
extension LambdaHandler {
public func shutdown(context: Lambda.ShutdownContext) -> EventLoopFuture<Void> {
let promise = context.eventLoop.makePromise(of: Void.self)
self.offloadQueue.async {
do {
Expand All @@ -78,7 +78,7 @@ public extension LambdaHandler {

/// Clean up the Lambda resources synchronously.
/// Concrete Lambda handlers implement this method to shutdown resources like `HTTPClient`s and database connections.
func syncShutdown(context: Lambda.ShutdownContext) throws {
public func syncShutdown(context: Lambda.ShutdownContext) throws {
// noop
}
}
Expand Down Expand Up @@ -126,9 +126,9 @@ public protocol EventLoopLambdaHandler: ByteBufferLambdaHandler {
func decode(buffer: ByteBuffer) throws -> In
}

public extension EventLoopLambdaHandler {
extension EventLoopLambdaHandler {
/// Driver for `ByteBuffer` -> `In` decoding and `Out` -> `ByteBuffer` encoding
func handle(context: Lambda.Context, event: ByteBuffer) -> EventLoopFuture<ByteBuffer?> {
public func handle(context: Lambda.Context, event: ByteBuffer) -> EventLoopFuture<ByteBuffer?> {
switch self.decodeIn(buffer: event) {
case .failure(let error):
return context.eventLoop.makeFailedFuture(CodecError.requestDecoding(error))
Expand Down Expand Up @@ -162,8 +162,8 @@ public extension EventLoopLambdaHandler {
}

/// Implementation of `ByteBuffer` to `Void` decoding
public extension EventLoopLambdaHandler where Out == Void {
func encode(allocator: ByteBufferAllocator, value: Void) throws -> ByteBuffer? {
extension EventLoopLambdaHandler where Out == Void {
public func encode(allocator: ByteBufferAllocator, value: Void) throws -> ByteBuffer? {
nil
}
}
Expand Down Expand Up @@ -194,8 +194,8 @@ public protocol ByteBufferLambdaHandler {
func shutdown(context: Lambda.ShutdownContext) -> EventLoopFuture<Void>
}

public extension ByteBufferLambdaHandler {
func shutdown(context: Lambda.ShutdownContext) -> EventLoopFuture<Void> {
extension ByteBufferLambdaHandler {
public func shutdown(context: Lambda.ShutdownContext) -> EventLoopFuture<Void> {
context.eventLoop.makeSucceededFuture(())
}
}
Expand Down
8 changes: 4 additions & 4 deletions Sources/AWSLambdaRuntimeCore/LambdaRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ extension Lambda {
}
}

private extension Lambda.Context {
convenience init(logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator, invocation: Lambda.Invocation) {
extension Lambda.Context {
fileprivate convenience init(logger: Logger, eventLoop: EventLoop, allocator: ByteBufferAllocator, invocation: Lambda.Invocation) {
self.init(requestID: invocation.requestID,
traceID: invocation.traceID,
invokedFunctionARN: invocation.invokedFunctionARN,
Expand Down Expand Up @@ -144,8 +144,8 @@ extension EventLoopFuture {
}
}

private extension Result {
var successful: Bool {
extension Result {
private var successful: Bool {
switch self {
case .success:
return true
Expand Down
Loading