Skip to content

Commit cb1385d

Browse files
committed
chore: use swift format to format code
1 parent bff7a1b commit cb1385d

14 files changed

Lines changed: 372 additions & 310 deletions

.swift-format

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
{
2+
"version" : 1,
3+
"indentation": {
4+
"spaces": 4
5+
},
6+
"tabWidth" : 4,
7+
"fileScopedDeclarationPrivacy": {
8+
"accessLevel": "private"
9+
},
10+
"indentConditionalCompilationBlocks": false,
11+
"indentSwitchCaseLabels": false,
12+
"indentBlankLines": false,
13+
"lineBreakAroundMultilineExpressionChainComponents": false,
14+
"lineBreakBeforeControlFlowKeywords": false,
15+
"lineBreakBeforeEachArgument": true,
16+
"lineBreakBeforeEachGenericRequirement": true,
17+
"lineBreakBetweenDeclarationAttributes": true,
18+
"lineLength": 120,
19+
"maximumBlankLines": 1,
20+
"respectsExistingLineBreaks": true,
21+
"multiElementCollectionTrailingCommas": true,
22+
"prioritizeKeepingFunctionOutputTogether": true,
23+
"reflowMultilineStringLiterals": {
24+
"never": { }
25+
},
26+
"spacesAroundRangeFormationOperators": false,
27+
"spacesBeforeEndOfLineComments": 2,
28+
"rules": {
29+
"AllPublicDeclarationsHaveDocumentation": false,
30+
"AlwaysUseLiteralForEmptyCollectionInit": false,
31+
"AlwaysUseLowerCamelCase": false,
32+
"AmbiguousTrailingClosureOverload": false,
33+
"BeginDocumentationCommentWithOneLineSummary": false,
34+
"DoNotUseSemicolons": false,
35+
"DontRepeatTypeInStaticProperties": false,
36+
"FileScopedDeclarationPrivacy": true,
37+
"FullyIndirectEnum": true,
38+
"GroupNumericLiterals": true,
39+
"IdentifiersMustBeASCII": true,
40+
"NeverForceUnwrap": false,
41+
"NeverUseForceTry": false,
42+
"NeverUseImplicitlyUnwrappedOptionals": false,
43+
"NoAccessLevelOnExtensionDeclaration": false,
44+
"NoAssignmentInExpressions": true,
45+
"NoBlockComments": false,
46+
"NoCasesWithOnlyFallthrough": true,
47+
"NoEmptyTrailingClosureParentheses": true,
48+
"NoLabelsInCasePatterns": true,
49+
"NoLeadingUnderscores": false,
50+
"NoParensAroundConditions": true,
51+
"NoPlaygroundLiterals": true,
52+
"NoVoidReturnOnFunctionSignature": true,
53+
"OmitExplicitReturns": false,
54+
"OneCasePerLine": true,
55+
"OneVariableDeclarationPerLine": true,
56+
"OnlyOneTrailingClosureArgument": true,
57+
"OrderedImports": true,
58+
"ReplaceForEachWithForLoop": true,
59+
"ReturnVoidInsteadOfEmptyTuple": true,
60+
"TypeNamesShouldBeCapitalized": true,
61+
"UseEarlyExits": false,
62+
"UseExplicitNilCheckInConditions": true,
63+
"UseLetInEveryBoundCaseVariable": false,
64+
"UseShorthandTypeNames": true,
65+
"UseSingleLinePropertyGetter": true,
66+
"UseSynthesizedInitializer": false,
67+
"UseTripleSlashForDocumentationComments": true,
68+
"UseWhereClausesInForLoops": false,
69+
"ValidateDocumentationComments": false
70+
},
71+
}

Package.swift

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import PackageDescription
66
let package = Package(
77
name: "GeocodingApi",
88
platforms: [
9-
.macOS(.v10_15)
9+
.macOS(.v10_15)
1010
],
1111
dependencies: [
1212
.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
@@ -17,16 +17,18 @@ let package = Package(
1717
name: "App",
1818
dependencies: [
1919
.product(name: "Vapor", package: "vapor"),
20-
"SwiftProtobuf"
20+
"SwiftProtobuf",
2121
],
2222
swiftSettings: [
2323
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release)),
2424
.unsafeFlags(["-enable-testing"], .when(configuration: .release)),
25-
.unsafeFlags(["-Ounchecked"], .when(configuration: .release))
26-
]),
25+
.unsafeFlags(["-Ounchecked"], .when(configuration: .release)),
26+
]
27+
),
2728
.target(name: "Run", dependencies: [.target(name: "App")]),
2829
.testTarget(
2930
name: "AppTests",
30-
dependencies: ["App"]),
31+
dependencies: ["App"]
32+
),
3133
]
3234
)

Sources/App/AlternateNames.swift

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import Foundation
22
import Vapor
33

4-
54
struct AlternateNames {
65
let alternativesPreferred: [Int32: [Int32: String]]
76
let postcodes: [Int32: [String]]
87
let languages: [String]
9-
8+
109
/**
1110
The table 'alternate names' :
1211
-----------------------------
@@ -25,36 +24,36 @@ struct AlternateNames {
2524
let start = Date()
2625
logger.info("Alternative names: Start loading")
2726
let tab = Character("\t").asciiValue!
28-
27+
2928
var languages = DeduplicatedStrings<Int32>()
3029
var alternateNames = [Int32: [AlternateName]]()
3130
var postcodes = [Int32: [String]]()
32-
31+
3332
data.forEachLine { line in
3433
if line.isEmpty {
3534
return
3635
}
3736
var offset = 0
38-
39-
let _ = line.seekUntil(value: tab, offset: &offset) // alternatenameid
37+
38+
let _ = line.seekUntil(value: tab, offset: &offset) // alternatenameid
4039
let geonameid = line.seekUntil(value: tab, offset: &offset).asciiToInt32
4140
let isolanguage = line.seekUntil(value: tab, offset: &offset)
4241
let alternateName = line.seekUntil(value: tab, offset: &offset).string
4342
let isPreferredName = line.seekUntil(value: tab, offset: &offset).asciiToInt8
4443
let isShortName = line.seekUntil(value: tab, offset: &offset).asciiToInt8
4544
let isColloquial = line.seekUntil(value: tab, offset: &offset).asciiToInt8
4645
//let isHistoric = line[line.seekUntil(value: tab, offset: &offset)].asciiToInt8
47-
46+
4847
let isolanguageString = isolanguage.string
49-
48+
5049
if isolanguageString == "link" || isolanguageString == "wkdt" || isolanguageString == "fr_1793" {
5150
return
5251
}
53-
54-
if isColloquial == 1 { //isHistoric == 1 ||
52+
53+
if isColloquial == 1 { //isHistoric == 1 ||
5554
return
5655
}
57-
56+
5857
if isolanguageString == "post" {
5958
if postcodes[geonameid] == nil {
6059
postcodes[geonameid] = [alternateName]
@@ -63,45 +62,45 @@ struct AlternateNames {
6362
}
6463
return
6564
}
66-
65+
6766
let alternateNameStruct = AlternateName(
6867
//geonameid: geonameid,
6968
languageId: languages.findOrAppend(isolanguage),
7069
alternateName: alternateName,
7170
isPreferredeName: isPreferredName != 0,
7271
isShortName: isShortName != 0
7372
)
74-
73+
7574
if alternateNames[geonameid] != nil {
7675
alternateNames[geonameid]?.append(alternateNameStruct)
7776
} else {
7877
alternateNames[geonameid] = [alternateNameStruct]
7978
}
8079
}
81-
80+
8281
var alternativesPreferred = [Int32: [Int32: String]]()
8382
alternativesPreferred.reserveCapacity(alternateNames.count)
8483
for (id, names) in alternateNames {
8584
/// For each langauge, find tthe most suitable alternativeName. Prefer short ones
86-
let languageIds = names.unique(of: {$0.languageId})
85+
let languageIds = names.unique(of: { $0.languageId })
8786
var res = [Int32: String]()
8887
res.reserveCapacity(languageIds.count)
8988
for languageId in languageIds {
90-
let perLanguage = names.filter({$0.languageId == languageId })
89+
let perLanguage = names.filter({ $0.languageId == languageId })
9190
res[languageId] = perLanguage.getPreferred()
9291
}
9392
alternativesPreferred[id] = res
9493
}
95-
94+
9695
self.languages = languages.strings
9796
self.alternativesPreferred = alternativesPreferred
9897
self.postcodes = postcodes
99-
98+
10099
logger.info("Alternative names: Finished loading in \(Date().timeIntervalSince(start)) seconds")
101100
}
102101
}
103102

104-
fileprivate struct AlternateName {
103+
private struct AlternateName {
105104
//let geonameid: Int32
106105
let languageId: Int32
107106
let alternateName: String
Lines changed: 42 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,30 @@
11
import Foundation
22
import Vapor
33

4-
54
extension GeocodingDatabase {
65
static let geonamesFile = URL(fileURLWithPath: "data/allCountries.txt")
76
static let alternateNamesFiles = URL(fileURLWithPath: "data/alternateNames.txt")
87
static let databaseFile = URL(fileURLWithPath: "data/database.bin")
9-
8+
109
/// Read geonames txt files and create an index protobuf file
1110
public static func createDatabase(logger: Logger) throws {
1211
logger.info("Create new geocoding database")
1312
let alternativeNamesData = try Data(contentsOf: alternateNamesFiles, options: [.mappedIfSafe, .uncached])
1413
let alternate = AlternateNames(data: alternativeNamesData, logger: logger)
15-
14+
1615
let geonamesData = try Data(contentsOf: geonamesFile, options: [.mappedIfSafe, .uncached])
1716
let geonames = GeocodingDatabase.Geonames(data: geonamesData, alternativeNames: alternate, logger: logger)
18-
17+
1918
let searchTree = GeocodingDatabase(geonames: geonames, logger: logger)
2019
let data: Data = try searchTree.serializedData()
2120
let start = Date()
2221
logger.info("Write database to disk")
2322
try data.write(to: databaseFile)
24-
logger.info("Database written in \(Date().timeIntervalSince(start)) seconds, size \(ByteCountFormatter().string(fromByteCount: Int64(data.count)))")
23+
logger.info(
24+
"Database written in \(Date().timeIntervalSince(start)) seconds, size \(ByteCountFormatter().string(fromByteCount: Int64(data.count)))"
25+
)
2526
}
26-
27+
2728
public static func loadOrCreate(logger: Logger) throws -> GeocodingDatabase {
2829
if !FileManager.default.fileExists(atPath: databaseFile.path) {
2930
try Self.createDatabase(logger: logger)
@@ -32,45 +33,63 @@ extension GeocodingDatabase {
3233
logger.info("Loading existing database...")
3334
let data = try Data(contentsOf: URL(fileURLWithPath: "data/database.bin"), options: [.mappedIfSafe, .uncached])
3435
let searchTree = try GeocodingDatabase(serializedBytes: data)
35-
logger.info("Finished loading in \(Date().timeIntervalSince(start)) seconds, \(searchTree.geonames.geonames.count) entries")
36+
logger.info(
37+
"Finished loading in \(Date().timeIntervalSince(start)) seconds, \(searchTree.geonames.geonames.count) entries"
38+
)
3639
return searchTree
3740
}
38-
41+
3942
/// Search for a string in the indexed location names and one language index
4043
public func search(_ searchString: String, languageId: Int32, maxCount: Int) -> [(Int32, Float)] {
4144
let stripped = searchString.folding(options: .diacriticInsensitive, locale: nil).lowercased()
4245
let results = PriorityQueue(length: maxCount)
4346
let onlyExact = searchString.count <= 2
4447
index.search(Substring(stripped), results: results, onlyExact: onlyExact, geonames: geonames.geonames)
45-
languageIndex[Int(languageId)].search(Substring(stripped), results: results, onlyExact: onlyExact, geonames: geonames.geonames)
46-
return results.queue.filter({$0.id > 0})
48+
languageIndex[Int(languageId)].search(
49+
Substring(stripped),
50+
results: results,
51+
onlyExact: onlyExact,
52+
geonames: geonames.geonames
53+
)
54+
return results.queue.filter({ $0.id > 0 })
4755
}
48-
56+
4957
/// Search for a string in the indexed location names and one language index
50-
public func proximity(latitude: Float, longitude: Float, maxCount: Int, maxDistanceKilometer: Float) -> [(Int32, Float)] {
51-
let results = geotree.knn(latitude: latitude, longitude: longitude, count: maxCount, maxDistanceKilometer: maxDistanceKilometer, elements: geonames.geonames)
52-
return results.filter({$0.id > 0})
58+
public func proximity(
59+
latitude: Float,
60+
longitude: Float,
61+
maxCount: Int,
62+
maxDistanceKilometer: Float
63+
) -> [(Int32, Float)] {
64+
let results = geotree.knn(
65+
latitude: latitude,
66+
longitude: longitude,
67+
count: maxCount,
68+
maxDistanceKilometer: maxDistanceKilometer,
69+
elements: geonames.geonames
70+
)
71+
return results.filter({ $0.id > 0 })
5372
}
5473

5574
public init(geonames: Geonames, logger: Logger) {
5675
logger.info("GeoTree: Start loading")
5776
let startTree = Date()
5877
self.geotree = GeoTree(elements: geonames.geonames, depth: nil)
5978
logger.info("GeoTree: Finished loading in \(Date().timeIntervalSince(startTree)) seconds")
60-
79+
6180
let start = Date()
6281
logger.info("SearchTree: Start loading")
63-
82+
6483
self.geonames = geonames
6584
var languageIndex = [SearchTreeLoader]()
6685
languageIndex.reserveCapacity(geonames.languages.count)
6786
for _ in geonames.languages {
6887
languageIndex.append(SearchTreeLoader())
6988
}
70-
let languageEmpty = geonames.languages.firstIndex(where: {$0 == ""})!
71-
let languageIata = geonames.languages.firstIndex(where: {$0 == "icao"})!
72-
let languageIcao = geonames.languages.firstIndex(where: {$0 == "iata"})!
73-
89+
let languageEmpty = geonames.languages.firstIndex(where: { $0 == "" })!
90+
let languageIata = geonames.languages.firstIndex(where: { $0 == "icao" })!
91+
let languageIcao = geonames.languages.firstIndex(where: { $0 == "iata" })!
92+
7493
logger.info("SearchTree: Prepare language trees")
7594
for (id, geoname) in geonames.geonames {
7695
if !geonames.includeInSearchIndex(featureCode: geoname.featureCode) {
@@ -83,8 +102,8 @@ extension GeocodingDatabase {
83102
languageIndex[Int(name.0)].add(name.1, id: id)
84103
}
85104
}
86-
self.languageIndex = languageIndex.map({$0.immutable()})
87-
105+
self.languageIndex = languageIndex.map({ $0.immutable() })
106+
88107
logger.info("SearchTree: Load main index")
89108
let index = SearchTreeLoader()
90109
for (id, geoname) in geonames.geonames {
@@ -102,7 +121,7 @@ extension GeocodingDatabase {
102121
}
103122
}
104123
self.index = index.immutable()
105-
124+
106125
logger.info("SearchTree: Finished loading in \(Date().timeIntervalSince(start)) seconds")
107126
}
108127
}

0 commit comments

Comments
 (0)