Skip to content
This repository has been archived by the owner on Jun 14, 2024. It is now read-only.

Commit

Permalink
feat: multiline values
Browse files Browse the repository at this point in the history
  • Loading branch information
Eggflaw committed May 31, 2024
1 parent c291813 commit 6bd5043
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 3 deletions.
47 changes: 44 additions & 3 deletions lib/init.luau
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,54 @@ function dotenv:parse(str: string): { [string?]: string? }
-- TODO: Parse dotenv and convert it into a table
local env: { [string?]: string? } = {}

local multiline = false
local multilineKey = ""
local multilineValue = ""
for line in str:gmatch("([^\n]+)\n") do
local key, value = line:match("(.+)=(.+)")

if key and value then
value = value:gsub('^"(.*)"$', "%1")
value = value:gsub("^'(.*)'$", "%1")
local firstChar = value:sub(1, 1)
local lastChar = value:sub(#value, #value)
if firstChar == '"' then
-- [[
-- #value == 1 is for keys that start with this
-- KEY="
-- FOO
-- BAR
-- "
-- otherwise it will return "\""
-- ]]
if lastChar ~= '"' or #value == 1 then
multiline = true
end
end

if not multiline then
value = value:gsub('^"(.*)"$', "%1")
value = value:gsub("^'(.*)'$", "%1")

env[key] = value
else
value = value:gsub('^"(.*)', "%1")
multilineKey = key
multilineValue = value
end
elseif multiline then
local lastChar = line:sub(#line, #line)
local escapeChar = line:sub(#line - 1, #line - 1)
if lastChar == '"' and escapeChar ~= "\\" then
line = line:gsub('(.*)"$', "%1")
multilineValue = multilineValue .. "\n" .. line

env[multilineKey] = multilineValue

env[key] = value
multiline = false
multilineKey = ""
multilineValue = ""
continue
end
multilineValue = multilineValue .. "\n" .. line
end
end

Expand Down
14 changes: 14 additions & 0 deletions tests/envs/multiline.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
NORMAL="BAR
FOO
BAZ
"
TEST_2="
BAR
FOO
BAZ
"

WITH_ESC="FOO
BAR\"
BAZ
"
24 changes: 24 additions & 0 deletions tests/parse.test.luau
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
-- stylua: ignore
local describe = require("@testing/describe")
local test = require("@testing/test")
local assertEq = require("@testing/assertEq")
local process = require("@lune/process")
local fs = require("@lune/fs")

local dotenv = require("../lib")

local function readEnv(path)
local content = fs.readFile(path)
local env = dotenv:parse(content)
return env
end

describe("Multiline", function()
test("Normal", function()
local env = readEnv("tests/envs/multiline.env")

assertEq(env.NORMAL, "BAR\nFOO\nBAZ\n")
assertEq(env.TEST_2, "\nBAR\nFOO\nBAZ\n")
assertEq(env.WITH_ESC, 'FOO\nBAR\\"\nBAZ\n')
end)
end)

0 comments on commit 6bd5043

Please sign in to comment.