Skip to content

Commit 8671d5a

Browse files
committed
Escape ${ in strings when printing Nix expressions
1 parent 64ba3c7 commit 8671d5a

File tree

4 files changed

+14
-3
lines changed

4 files changed

+14
-3
lines changed

src/Nix/Pretty.hs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,11 @@ prettyString (DoubleQuoted parts) = "\"" <> foldMap prettyPart parts <> "\""
104104
where
105105
-- It serializes Text -> String, because the helper code is done for String,
106106
-- please, can someone break that code.
107-
prettyPart (Plain t) = pretty . foldMap escape . toString $ t
107+
prettyPart (Plain t) = pretty . dollarEscape . toText . foldMap escape . toString $ t
108108
prettyPart EscapedNewline = "''\\n"
109109
prettyPart (Antiquoted r) = "${" <> withoutParens r <> "}"
110110
escape '"' = "\\\""
111+
escape '$' = "$" -- do not print $ as \$ if no { is following
111112
escape x =
112113
maybe
113114
(one x)
@@ -382,6 +383,10 @@ prettyNThunk t =
382383
"(" <> fold (one "thunk from: " <> (prettyOriginExpr . _originExpr <$> ps)) <> ")"
383384
]
384385

386+
-- | dollarEscape for double quoted string
387+
dollarEscape :: Text -> Text
388+
dollarEscape = replace "${" "\\${"
389+
385390
-- | This function is used only by the testing code.
386391
printNix :: forall t f m . MonadDataContext f m => NValue t f m -> Text
387392
printNix = iterNValueByDiscardWith thk phi
@@ -390,7 +395,7 @@ printNix = iterNValueByDiscardWith thk phi
390395

391396
phi :: NValue' t f m Text -> Text
392397
phi (NVConstant' a ) = atomText a
393-
phi (NVStr' ns) = show $ ignoreContext ns
398+
phi (NVStr' ns) = dollarEscape $ show $ ignoreContext ns
394399
phi (NVList' l ) = "[ " <> unwords l <> " ]"
395400
phi (NVSet' _ s) =
396401
"{ " <>

tests/PrettyTests.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ case_string_antiquotation =
2323
do
2424
assertPretty
2525
(mkStr "echo $foo")
26-
"\"echo \\$foo\""
26+
"\"echo $foo\""
2727
assertPretty
2828
(mkStr "echo ${foo}")
2929
"\"echo \\${foo}\""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# to observe the upstream nix behavior for dollar sign excape in doublequote string
2+
"\${foo $foo"
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# to observe the upstream nix behavior for dollar excape in Indented string
2+
''
3+
''$ ''${
4+
''

0 commit comments

Comments
 (0)