@@ -4,12 +4,17 @@ import Prelude
44
55import Data.Maybe (Maybe (..))
66import Effect (Effect )
7- import Effect.Exception (throw )
7+ import Effect.Exception (catchException , throw )
88import Foreign.Object as Object
99import Node.Process as Process
1010
1111main :: Effect Unit
1212main = do
13+ testEnvMutation
14+ testLoadEnvFile
15+
16+ testEnvMutation :: Effect Unit
17+ testEnvMutation = do
1318 let key = " PURESCRIPT_NODE_PROCESS_TEST"
1419 original <- Process .lookupEnv key
1520 Process .setEnv key " first"
@@ -18,11 +23,48 @@ main = do
1823 current <- Process .lookupEnv key
1924 Process .unsetEnv key
2025 removed <- Process .lookupEnv key
21- case original of
22- Nothing -> Process .unsetEnv key
23- Just value -> Process .setEnv key value
26+ restoreEnv key original
2427 if
2528 Object .lookup key snapshot == Just " first"
2629 && current == Just " second"
2730 && removed == Nothing then pure unit
2831 else throw " Environment lookup, snapshot, or removal failed"
32+
33+ testLoadEnvFile :: Effect Unit
34+ testLoadEnvFile = do
35+ let loadedKey = " PURESCRIPT_NODE_PROCESS_ENV_FILE_LOADED"
36+ let existingKey = " PURESCRIPT_NODE_PROCESS_ENV_FILE_EXISTING"
37+ originalLoaded <- Process .lookupEnv loadedKey
38+ originalExisting <- Process .lookupEnv existingKey
39+ originalCwd <- Process .cwd
40+
41+ -- Explicit path: loads new variables, keeps existing ones.
42+ Process .unsetEnv loadedKey
43+ Process .setEnv existingKey " already-set"
44+ Process .loadEnvFile' " test/fixtures/.env"
45+ loadedByPath <- Process .lookupEnv loadedKey
46+ kept <- Process .lookupEnv existingKey
47+
48+ -- Default path: resolves `.env` against the current working directory.
49+ Process .unsetEnv loadedKey
50+ Process .chdir " test/fixtures"
51+ Process .loadEnvFile
52+ Process .chdir originalCwd
53+ loadedByDefault <- Process .lookupEnv loadedKey
54+
55+ -- Missing file throws.
56+ missingThrew <- Process .loadEnvFile' " test/fixtures/missing.env" $> false # catchException \_ -> pure true
57+
58+ restoreEnv loadedKey originalLoaded
59+ restoreEnv existingKey originalExisting
60+ if
61+ loadedByPath == Just " from-file"
62+ && kept == Just " already-set"
63+ && loadedByDefault == Just " from-file"
64+ && missingThrew then pure unit
65+ else throw " loadEnvFile did not load the file, overwrote an existing variable, or did not throw for a missing file"
66+
67+ restoreEnv :: String -> Maybe String -> Effect Unit
68+ restoreEnv key = case _ of
69+ Nothing -> Process .unsetEnv key
70+ Just value -> Process .setEnv key value
0 commit comments