Skip to content

Commit

Permalink
Trimming trailing whitespace for values; remove escape double quotes
Browse files Browse the repository at this point in the history
  • Loading branch information
KeanuPang committed May 18, 2022
1 parent 9d897f3 commit 7f482b3
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
17 changes: 14 additions & 3 deletions Sources/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,14 @@ public struct Environment {
} else if let integerValue = Int(stringValue) {
self = .integer(integerValue)
} else {
self = .string(stringValue)
// replace escape double quotes
var value = stringValue
if value[value.startIndex] == "\"" && value[value.index(before: value.endIndex)] == "\"" {
value.remove(at: value.startIndex)
value.remove(at: value.index(before: value.endIndex))
value = value.replacingOccurrences(of: "\\\"", with: "\"")
}
self = .string(value)
}
}

Expand Down Expand Up @@ -177,12 +184,16 @@ public struct Environment {
// we loop over all the entries in the file which are already separated by a newline
var values: OrderedDictionary<String, Value> = .init()
for line in lines {
// ignore comments
if line.starts(with: "#") {
continue
}
// split by the delimeter
let substrings = line.split(separator: Self.delimeter)
// make sure we can grab two and only two string values
guard
let key = substrings.first,
let value = substrings.last,
let key = substrings.first?.trimmingCharacters(in: .whitespacesAndNewlines),
let value = substrings.last?.trimmingCharacters(in: .whitespacesAndNewlines),
substrings.count == 2,
!key.isEmpty,
!value.isEmpty else {
Expand Down
2 changes: 2 additions & 0 deletions Tests/DotenvTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ final class DotenvTests: XCTestCase {
let env = try Dotenv.load(path: path)
XCTAssertEqual(env.key1, .string("value1"))
XCTAssertEqual(env.key2, .string("value2"))
XCTAssertEqual(env.key3, .string("value3"))
XCTAssertEqual(env.key4, .string("quoted value"))
XCTAssertNil(env.nonExistentValue)
}

Expand Down
3 changes: 3 additions & 0 deletions Tests/Resources/fixture.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
key1=value1
key2=value2
# variable with trailing whitespace
key3=value3
key4="quoted value"

0 comments on commit 7f482b3

Please sign in to comment.