Skip to content

Commit

Permalink
Add export for exporting to environment
Browse files Browse the repository at this point in the history
  • Loading branch information
juri committed May 18, 2024
1 parent 11a8c7f commit a72bf0e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Sources/DotEnvy/Load.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ extension DotEnvironment.Override {
}

extension DotEnvironment {
/// Export the `DotEnvironment` values into the process environment.
///
/// - Parameter overwrite: Indicates if the calculated value should overwrite any existing value
/// in the process environment.
public func export(overwrite: Bool = true) {
for value in self.merge() {
setenv(value.key, value.value, overwrite ? 1 : 0)
}
}

/// Load the contents of a dotenv file into a dictionary.
///
/// Defaults to loading `.env` from the current working directory. If the file does not exist, an
Expand Down
32 changes: 32 additions & 0 deletions Tests/DotEnvyTests/ExportTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
@testable import DotEnvy
import XCTest

final class ExportTests: XCTestCase {
func testOverwrite() throws {
setenv("KEY1", "ENVVALUE1", 1)
let dotenv = try DotEnvironment.make(
source: """
KEY1=DOTENVVALUE1
KEY2=DOTENVVALUE2
""",
overrides: .none
)
dotenv.export(overwrite: true)
XCTAssertEqual(ProcessInfo.processInfo.environment["KEY1"], "DOTENVVALUE1")
XCTAssertEqual(ProcessInfo.processInfo.environment["KEY2"], "DOTENVVALUE2")
}

func testNoOverwrite() throws {
setenv("KEY1", "ENVVALUE1", 1)
let dotenv = try DotEnvironment.make(
source: """
KEY1=DOTENVVALUE1
KEY2=DOTENVVALUE2
""",
overrides: .none
)
dotenv.export(overwrite: false)
XCTAssertEqual(ProcessInfo.processInfo.environment["KEY1"], "ENVVALUE1")
XCTAssertEqual(ProcessInfo.processInfo.environment["KEY2"], "DOTENVVALUE2")
}
}

0 comments on commit a72bf0e

Please sign in to comment.