Skip to content

Commit ae1b5ee

Browse files
authored
Implement Codable for ProcessEnvironmentKey (#469)
The `Job` type in the `apple/swift-driver` repository conforms to `Codable` and also stores process environment in its properties. Lack of `Codable` conformance on `ProcessEnvironmentKey` prevents us from migrating `Job` to `ProcessEnvironmentBlock`.
1 parent 17087e4 commit ae1b5ee

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

Sources/TSCBasic/Process/ProcessEnv.swift

+14
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,20 @@ public struct ProcessEnvironmentKey {
1818
}
1919
}
2020

21+
extension ProcessEnvironmentKey: Encodable {
22+
public func encode(to encoder: any Encoder) throws {
23+
var container = encoder.singleValueContainer()
24+
try container.encode(self.value)
25+
}
26+
}
27+
28+
extension ProcessEnvironmentKey: Decodable {
29+
public init(from decoder: any Decoder) throws {
30+
let container = try decoder.singleValueContainer()
31+
self.value = try container.decode(String.self)
32+
}
33+
}
34+
2135
extension ProcessEnvironmentKey: Equatable {
2236
public static func == (_ lhs: Self, _ rhs: Self) -> Bool {
2337
#if os(Windows)

Tests/TSCBasicTests/ProcessEnvTests.swift

+11-1
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@
88
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
99
*/
1010

11+
import Foundation
1112
import XCTest
1213

1314
import TSCBasic
1415
import TSCTestSupport
1516

1617
class ProcessEnvTests: XCTestCase {
17-
1818
func testEnvVars() throws {
1919
let key = "SWIFTPM_TEST_FOO"
2020
XCTAssertEqual(ProcessEnv.vars[key], nil)
@@ -64,4 +64,14 @@ class ProcessEnvTests: XCTestCase {
6464
XCTAssertNotEqual(ProcessEnvironmentKey("Key"), "KEY")
6565
#endif
6666
}
67+
68+
func testEnvironmentKeysCodable() throws {
69+
let encoder = JSONEncoder()
70+
let json = try encoder.encode(ProcessEnvironmentKey("foo"))
71+
XCTAssertEqual(String(decoding: json, as: UTF8.self), #""foo""#)
72+
73+
let decoder = JSONDecoder()
74+
let result = try decoder.decode(ProcessEnvironmentKey.self, from: json)
75+
XCTAssertEqual(result, ProcessEnvironmentKey("foo"))
76+
}
6777
}

0 commit comments

Comments
 (0)