commit a9d6755b37ba094e052a3ecf6856ee22034dae4d
parent a76f8784f2764d17cfd8f6ea31361f4465a39a7f
Author: FIGBERT <figbert@figbert.com>
Date: Sun, 4 Sep 2022 10:27:57 -0700
Add support for relative links
Diffstat:
2 files changed, 31 insertions(+), 3 deletions(-)
diff --git a/Sources/SwiftGemtext/SwiftGemtext.swift b/Sources/SwiftGemtext/SwiftGemtext.swift
@@ -4,6 +4,10 @@ public struct Gemtext {
public init() {}
public func parse(_ source: String) -> [LineType] {
+ return parse(source, url: nil)
+ }
+
+ public func parse(_ source: String, url: URL?) -> [LineType] {
var lines = [LineType]()
var pre = PreformattedState()
@@ -24,13 +28,13 @@ public struct Gemtext {
continue
}
- lines.append(parsePlainLine(line))
+ lines.append(parsePlainLine(line, relativeTo: url))
}
}
return lines
}
- func parsePlainLine(_ line: String) -> LineType {
+ func parsePlainLine(_ line: String, relativeTo rel: URL?) -> LineType {
if line.starts(with: "#") { // Heading Line
var level: Int = 1
if line.starts(with: "###") {
@@ -44,7 +48,7 @@ public struct Gemtext {
let url = base.components(separatedBy: .whitespaces).first!
let caption = base.dropFirst(url.count).trimmingCharacters(in: .whitespaces)
- return LineType.Link(URL(string: url)!, caption.isEmpty ? nil : caption)
+ return LineType.Link(URL(string: url, relativeTo: rel)!, caption.isEmpty ? nil : caption)
} else if line.starts(with: "* ") { // Unordered List Line
return LineType.UnorderedList(line.dropFirst(2).trimmingCharacters(in: .whitespacesAndNewlines))
} else if line.starts(with: ">") { // Quote Line
diff --git a/Tests/SwiftGemtextTests/SwiftGemtextTests.swift b/Tests/SwiftGemtextTests/SwiftGemtextTests.swift
@@ -31,6 +31,29 @@ final class SwiftGemtextTests: XCTestCase {
XCTAssertEqual(manual, run)
}
+ func testRelativeURLs() {
+ let source = """
+ Zounds!
+
+ => gemini://figbert.com/ wow its a capsule
+ => / same
+ => /a-page i have a few of these
+ => https://news.ycombinator.com/ Hacker News
+ """
+ let base = URL(string: "gemini://figbert.com")
+
+ let manual = [
+ LineType.Text("Zounds!"),
+ LineType.EmptyLine,
+ LineType.Link(URL(string: "gemini://figbert.com/")!, "wow its a capsule"),
+ LineType.Link(URL(string: "/", relativeTo: base)!, "same"),
+ LineType.Link(URL(string: "/a-page", relativeTo: base)!, "i have a few of these"),
+ LineType.Link(URL(string: "https://news.ycombinator.com/")!, "Hacker News"),
+ ]
+ let run = Gemtext().parse(source, url: base)
+ XCTAssertEqual(manual, run)
+ }
+
func testComplexGemini() {
let source = """
# One
@@ -81,6 +104,7 @@ final class SwiftGemtextTests: XCTestCase {
static var allTests = [
("testSingleLine", testSingleLine),
("testPlainGemini", testPlainGemini),
+ ("testRelativeURLs", testRelativeURLs),
("testComplexGemini", testComplexGemini)
]
}