Skip to content

Commit 590bc8e

Browse files
Merge pull request #158 from apple/validating-constructors
<rdar://70974921> swift-tsc's AbsolutePath and RelativePath Codable constructors should use validating overloads
2 parents 33ca7e4 + e7c1ae8 commit 590bc8e

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

Sources/TSCBasic/Path.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ extension AbsolutePath: Codable {
304304

305305
public init(from decoder: Decoder) throws {
306306
let container = try decoder.singleValueContainer()
307-
try self.init(container.decode(String.self))
307+
try self.init(validating: container.decode(String.self))
308308
}
309309
}
310310

@@ -316,7 +316,7 @@ extension RelativePath: Codable {
316316

317317
public init(from decoder: Decoder) throws {
318318
let container = try decoder.singleValueContainer()
319-
try self.init(container.decode(String.self))
319+
try self.init(validating: container.decode(String.self))
320320
}
321321
}
322322

Tests/TSCBasicTests/PathTests.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,10 @@ class PathTests: XCTestCase {
308308
var path: RelativePath
309309
}
310310

311+
struct Baz: Codable, Equatable {
312+
var path: String
313+
}
314+
311315
do {
312316
let foo = Foo(path: AbsolutePath("/path/to/foo"))
313317
let data = try JSONEncoder().encode(foo)
@@ -339,6 +343,22 @@ class PathTests: XCTestCase {
339343
XCTAssertEqual(bar.path.pathString, "path/to/bar")
340344
XCTAssertEqual(decodedBar.path.pathString, "path/to/bar")
341345
}
346+
347+
do {
348+
let data = try JSONEncoder().encode(Baz(path: ""))
349+
XCTAssertThrowsError(try JSONDecoder().decode(Foo.self, from: data))
350+
XCTAssertNoThrow(try JSONDecoder().decode(Bar.self, from: data)) // empty string is a valid relative path
351+
}
352+
353+
do {
354+
let data = try JSONEncoder().encode(Baz(path: "foo"))
355+
XCTAssertThrowsError(try JSONDecoder().decode(Foo.self, from: data))
356+
}
357+
358+
do {
359+
let data = try JSONEncoder().encode(Baz(path: "/foo"))
360+
XCTAssertThrowsError(try JSONDecoder().decode(Bar.self, from: data))
361+
}
342362
}
343363

344364
// FIXME: We also need tests for join() operations.

0 commit comments

Comments
 (0)