Skip to content

Commit

Permalink
fix: Correctly parse newline and multiline strings in dotenv files (#192
Browse files Browse the repository at this point in the history
)

* test: Add tests for correctly escaping new lines characters `\n`

* fix: Correctly parse newline and multiline strings in dotenv files

* test: Enhance test cases for more robust `\n`
  • Loading branch information
FranzGB authored Aug 19, 2024
1 parent 7e93cba commit 8add769
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
8 changes: 8 additions & 0 deletions spec/Configuration/Dotenv/TextSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ spec =
it "recognizes unicode characters" $
liftM (!! 1) (parseFile "spec/fixtures/.dotenv") `shouldReturn`
(T.pack "UNICODE_TEST", T.pack "Manabí")

it "handles newline characters correctly" $ do
liftM (!! 6) (parseFile "spec/fixtures/.dotenv") `shouldReturn`
(T.pack "NEWLINE_TEST", T.pack "Hello\nWorld\nThis is a test\n")

it "handles manual line breaks correctly" $ do
liftM (!! 7) (parseFile "spec/fixtures/.dotenv") `shouldReturn`
(T.pack "MULTILINE_TEST", T.pack "Roses are red\nViolets are blue\nCode is my art\nAnd bugs are my glue\n")
6 changes: 6 additions & 0 deletions spec/fixtures/.dotenv
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,9 @@ ENVIRONMENT="$HOME"
PREVIOUS="$DOTENV"
ME="$(whoami)"
BLANK=
NEWLINE_TEST="Hello\nWorld\nThis is a test\n"
MULTILINE_TEST="Roses are red
Violets are blue
Code is my art
And bugs are my glue
"
5 changes: 3 additions & 2 deletions src/Configuration/Dotenv/Parse.hs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import Text.Megaparsec (Parsec, anySingle,
between, eof, noneOf,
oneOf, sepEndBy, (<?>))
import Text.Megaparsec.Char (char, digitChar, eol,
letterChar, spaceChar)
letterChar, spaceChar, string)
import qualified Text.Megaparsec.Char.Lexer as L

type Parser = Parsec Void String
Expand Down Expand Up @@ -85,8 +85,9 @@ interpolatedValueCommandInterpolation = do
symbol = L.symbol sc

literalValueFragment :: String -> Parser VarFragment
literalValueFragment charsToEscape = VarLiteral <$> some (escapedChar <|> normalChar)
literalValueFragment charsToEscape = VarLiteral <$> some (newlineChar <|> escapedChar <|> normalChar)
where
newlineChar = string "\\n" >> return '\n'
escapedChar = (char '\\' *> anySingle) <?> "escaped character"
normalChar = noneOf charsToEscape <?> "unescaped character"

Expand Down

0 comments on commit 8add769

Please sign in to comment.