Skip to content

Commit 16a0b63

Browse files
committed
Migrate from TOMLKit to TOMLDecoder
TOMLDecoder supports TOML 1.1.0. TOML 1.1.0 finaly allows newlines in inline tables which is a much better syntax than double square brackets. I'd love to update the ./docs to prefer inline tables over double square brackets, but pygments color syntax highlighter doesn't still support it (we use pygments to highlight TOML snippets in the docs) We need to wait for this PR to land: pygments/pygments#3027 And then the Ruby library to be updated: https://github.com/pygments/pygments.rb The other motivation is that TOMLDecoder source code seems to be more disciplined _closes #975 _closes #1064
1 parent 86b5218 commit 16a0b63

File tree

8 files changed

+124
-103
lines changed

8 files changed

+124
-103
lines changed

Package.resolved

Lines changed: 5 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Package.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ let package = Package(
1919
dependencies: [
2020
.package(path: "./ShellParserGenerated"),
2121
.package(url: "https://github.com/InerziaSoft/ISSoundAdditions.git", exact: "2.0.1"),
22-
.package(url: "https://github.com/LebJe/TOMLKit.git", exact: "0.5.5"),
22+
.package(url: "https://github.com/dduan/TOMLDecoder", exact: "0.4.4"),
2323
.package(url: "https://github.com/apple/swift-collections.git", exact: "1.3.0"),
2424
.package(url: "https://github.com/soffes/HotKey.git", exact: "0.2.1"),
2525
],
@@ -45,7 +45,7 @@ let package = Package(
4545
.product(name: "HotKey", package: "HotKey"),
4646
.product(name: "ISSoundAdditions", package: "ISSoundAdditions"),
4747
.product(name: "ShellParserGenerated", package: "ShellParserGenerated"),
48-
.product(name: "TOMLKit", package: "TOMLKit"),
48+
.product(name: "TOMLDecoder", package: "TOMLDecoder"),
4949
.target(name: "Common"),
5050
.target(name: "PrivateApi"),
5151
],

Sources/AppBundle/config/parseConfig.swift

Lines changed: 30 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import AppKit
22
import Common
33
import HotKey
4-
import TOMLKit
4+
import TOMLDecoder
55
import OrderedCollections
66

77
@MainActor
@@ -173,48 +173,31 @@ func parseCommandOrCommands(_ raw: Json) -> Parsed<[any Command]> {
173173
}
174174
}
175175

176-
extension TOMLValueConvertible {
177-
func toJsonRecursive(_ backtrace: ConfigBacktrace) -> ParsedConfig<Json> {
178-
switch self.type {
179-
// Vector
180-
case .table: return table.orDie().tomlTableToJsonRecursive(backtrace).map(Json.dict)
181-
case .array:
182-
let array = array.orDie()
183-
var json = Json.JsonArray()
184-
for (index, tomlValue) in array.enumerated() {
185-
let jsonResultValue = tomlValue.toJsonRecursive(backtrace + .index(index))
186-
switch jsonResultValue {
187-
case .success(let jsonValue): json.append(jsonValue)
188-
case .failure(let fail): return .failure(fail)
189-
}
176+
func tomlAnyToParsedConfigRecursive(any: Any, _ backtrace: ConfigBacktrace) -> ParsedConfig<Json> {
177+
switch any {
178+
case let dict as [String: Any]:
179+
var json = Json.JsonDict()
180+
for (key, tomlValue) in dict {
181+
let jsonResultValue = tomlAnyToParsedConfigRecursive(any: tomlValue, backtrace + .key(key))
182+
switch jsonResultValue {
183+
case .success(let jsonValue): json[key] = jsonValue
184+
case .failure(let fail): return .failure(fail)
190185
}
191-
return .success(.array(json))
192-
193-
// Scalar
194-
case .string: return .success(.string(string.orDie()))
195-
case .int: return .success(.int(int.orDie()))
196-
case .bool: return .success(.bool(bool.orDie()))
197-
198-
// Unsupported
199-
case .double: return .failure(.semantic(backtrace, "TOML Double type is not supported"))
200-
case .date: return .failure(.semantic(backtrace, "TOML Date type is not supported"))
201-
case .time: return .failure(.semantic(backtrace, "TOML Time type is not supported"))
202-
case .dateTime: return .failure(.semantic(backtrace, "TOML DateTime type is not supported"))
203-
}
204-
}
205-
}
206-
207-
extension TOMLTable {
208-
func tomlTableToJsonRecursive(_ backtrace: ConfigBacktrace) -> ParsedConfig<Json.JsonDict> {
209-
var json = Json.JsonDict()
210-
for (key, tomlValue) in self {
211-
let jsonResultValue = tomlValue.toJsonRecursive(backtrace + .key(key))
212-
switch jsonResultValue {
213-
case .success(let jsonValue): json[key] = jsonValue
214-
case .failure(let fail): return .failure(fail)
215186
}
216-
}
217-
return .success(json)
187+
return .success(.dict(json))
188+
case let array as [Any]:
189+
var json = Json.JsonArray()
190+
for (index, tomlValue) in array.enumerated() {
191+
let jsonResultValue = tomlAnyToParsedConfigRecursive(any: tomlValue, backtrace + .index(index))
192+
switch jsonResultValue {
193+
case .success(let jsonValue): json.append(jsonValue)
194+
case .failure(let fail): return .failure(fail)
195+
}
196+
}
197+
return .success(.array(json))
198+
default:
199+
return Json.newScalarOrNil(any).map(Result.success)
200+
?? .failure(.semantic(backtrace, "Unsupported TOML type: \(type(of: any))"))
218201
}
219202
}
220203

@@ -226,14 +209,14 @@ extension TOMLTable {
226209
@MainActor private func _parseConfig(_ rawToml: String) -> (config: Config, errors: [ConfigParseError]) { // todo change return value to Result
227210
let rawTable: Json.JsonDict
228211
do {
229-
switch (try TOMLTable(string: rawToml)).tomlTableToJsonRecursive(.emptyRoot) {
230-
case .success(let _rawTable): rawTable = _rawTable
212+
let dict: [String: Any] = try .init(try TOMLTable(source: rawToml))
213+
switch tomlAnyToParsedConfigRecursive(any: dict, .emptyRoot) {
214+
case .success(.dict(let dict)): rawTable = dict
215+
case .success: return (defaultConfig, [.syntax("Config parsing error: the top level type must be a TOML Table")])
231216
case .failure(let fail): return (defaultConfig, [fail])
232217
}
233-
} catch let e as TOMLParseError {
234-
return (defaultConfig, [.syntax(e.debugDescription)])
235-
} catch let e {
236-
return (defaultConfig, [.syntax(e.localizedDescription)])
218+
} catch {
219+
return (defaultConfig, [.syntax(error.description)])
237220
}
238221

239222
var errors: [ConfigParseError] = []

Sources/AppBundle/model/Json.swift

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,22 +29,24 @@ enum Json: Encodable, Equatable {
2929
}
3030

3131
static func newOrDie(_ value: Any?) -> Json {
32-
if let value = value as? [String: Any?] {
33-
return .dict(value.mapValues(newOrDie))
34-
} else if let value = value as? [Any?] {
35-
return .array(value.map(newOrDie))
36-
} else if let value = value as? Int {
37-
return .int(value)
38-
} else if let value = value as? UInt32 {
39-
return .uint32(value)
40-
} else if let value = value as? Bool {
41-
return .bool(value)
42-
} else if let value = value as? String {
43-
return .string(value)
44-
} else if value == nil || value is NSNull {
45-
return .null
46-
} else {
47-
die("Can't parse \(String(describing: value)) (\(Swift.type(of: value))) to JSON")
32+
switch value {
33+
case let value as [String: Any?]: .dict(value.mapValues(newOrDie))
34+
case let value as [Any?]: .array(value.map(newOrDie))
35+
default:
36+
newScalarOrNil(value)
37+
?? dieT("Can't parse \(String(describing: value)) (\(Swift.type(of: value))) to JSON")
38+
}
39+
}
40+
41+
static func newScalarOrNil(_ value: Any?) -> Json? {
42+
switch value {
43+
case let value as Int: .int(value)
44+
case let value as Int64: Int(exactly: value).map(Json.int)
45+
case let value as UInt32: .uint32(value)
46+
case let value as Bool: .bool(value)
47+
case let value as String: .string(value)
48+
case nil, is NSNull: .null
49+
default: nil
4850
}
4951
}
5052

Sources/AppBundleTests/config/ConfigTest.swift

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,10 +184,29 @@ final class ConfigTest: XCTestCase {
184184
}
185185

186186
func testConfigParseError() {
187-
let (_, errors) = parseConfig("true")
188187
assertEquals(
189-
errors,
190-
["Error while parsing key-value pair: encountered end-of-file (at line 1, column 5)"],
188+
parseConfig("true").errors,
189+
["(Line 1) Syntax error: missing =."],
190+
)
191+
192+
assertEquals(
193+
parseConfig("\n1").errors,
194+
["(Line 2) Syntax error: missing =."],
195+
)
196+
197+
assertEquals(
198+
parseConfig("foo: 1").errors,
199+
["(Line 1) Syntax error: missing =."],
200+
)
201+
202+
assertEquals(
203+
parseConfig("foo = 1.0").errors,
204+
["foo: Unsupported TOML type: Double"],
205+
)
206+
207+
assertEquals(
208+
parseConfig("foo.bar = 1979-05-27").errors,
209+
["foo.bar: Unsupported TOML type: LocalDate"],
191210
)
192211
}
193212

@@ -331,6 +350,40 @@ final class ConfigTest: XCTestCase {
331350
])
332351
}
333352

353+
func testParseInlineTables() {
354+
let errors = parseConfig(
355+
"""
356+
on-window-detected = [
357+
{
358+
check-further-callbacks = true,
359+
run = ['layout floating', 'move-node-to-workspace W'],
360+
},
361+
{
362+
if.app-id = 'com.apple.systempreferences',
363+
run = [],
364+
}
365+
]
366+
""",
367+
).errors
368+
assertEquals(errors, [])
369+
}
370+
371+
func testTomlParser() {
372+
// https://github.com/nikitabobko/AeroSpace/issues/1064
373+
let errors = parseConfig(
374+
"""
375+
[[[on-window-detected]]
376+
if.app-id = 'com.apple.findmy'
377+
run = 'layout floating'
378+
379+
[on-window-detected]]
380+
if.app-id = 'com.openai.chat'
381+
run = 'layout floating'
382+
""",
383+
).errors
384+
assertEquals(errors, ["(Line 1) Syntax error: invalid or missing key."])
385+
}
386+
334387
func testParseOnWindowDetectedRegex() {
335388
let (config, errors) = parseConfig(
336389
"""

legal/README.md

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,10 @@ AeroSpace bundles the following dependencies and uses the following materials:
1111
[HotKey MIT license](./third-party-license/LICENSE-HotKey.txt).
1212
HotKey is used as a more convenient wrapper around macOS Carbon API to listen for global shortcuts.
1313

14-
**TOMLKIT**.
15-
[TOMLKIT GitHub link](https://github.com/LebJe/TOMLKit).
16-
[TOMLKIT MIT license](./third-party-license/LICENSE-TOMLKIT.txt).
17-
TOMLKIT is used as a more convenient Swift wrapper around tomlplusplus C++ API.
18-
19-
**tomlplusplus**.
20-
[tomlplusplus GitHub link](https://github.com/marzer/tomlplusplus).
21-
[tomlplusplus MIT license](./third-party-license/LICENSE-tomlplusplus.txt).
22-
tomlplusplus is used as TOML parser. tomlplusplus is used indirectly through TOMLKIT Swift API.
14+
**TOMLDecoder**.
15+
[TOMLDecoder GitHub link](https://github.com/LebJe/TOMLKit).
16+
[TOMLDecoder MIT license](./third-party-license/LICENSE-TOMLDecoder.txt).
17+
TOMLDecoder is used as TOML parsing library.
2318

2419
**ANTLR v4**.
2520
[ANTLR v4 GitHub link](https://github.com/antlr/antlr4).
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2019 TOMLDecoder contributors
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

legal/third-party-license/LICENSE-TOMLKIT.txt

Lines changed: 0 additions & 21 deletions
This file was deleted.

0 commit comments

Comments
 (0)