Skip to content

Commit

Permalink
fix: correctly handle escape sequences in strings
Browse files Browse the repository at this point in the history
Fixes #62
  • Loading branch information
zachallaun committed Jan 29, 2024
1 parent 10cca1d commit b2ce9cd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
17 changes: 13 additions & 4 deletions lib/mneme/assertion/pattern_builder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ defmodule Mneme.Assertion.PatternBuilder do
end

defp string_pattern(string, context) do
Pattern.new({:__block__, with_meta([delimiter: ~S(")], context), [escape(string)]})
Pattern.new({:__block__, with_meta([delimiter: ~S(")], context), [escape_string(string)]})
end

defp charlist_pattern(charlist, context) do
Expand All @@ -396,7 +396,7 @@ defmodule Mneme.Assertion.PatternBuilder do
defp heredoc_pattern(string, context) do
Pattern.new(
{:__block__, with_meta([delimiter: ~S(""")], context),
[string |> escape() |> format_for_heredoc()]}
[string |> escape_string() |> format_for_heredoc()]}
)
end

Expand All @@ -408,8 +408,17 @@ defmodule Mneme.Assertion.PatternBuilder do
end
end

defp escape(string) when is_binary(string) do
String.replace(string, "\\", "\\\\")
defp escape_string(string) when is_binary(string) do
# https://hexdocs.pm/elixir/String.html#module-escape-characters
string
|> String.replace("\\", "\\\\")
|> String.replace("\0", "\\0")
|> String.replace("\a", "\\a")
|> String.replace("\b", "\\b")
|> String.replace("\t", "\\t")
|> String.replace("\v", "\\v")
|> String.replace("\r", "\\r")
|> String.replace("\e", "\\e")
end

defp make_var(name, context) do
Expand Down
1 change: 1 addition & 0 deletions lib/mneme/patcher.ex
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ defmodule Mneme.Patcher do

{:error, errors, _project} ->
not_saved = Enum.map(errors, fn %Rewrite.SourceError{path: path} -> path end)

{:error, {:not_saved, not_saved}}
end
end
Expand Down
3 changes: 3 additions & 0 deletions test_integration/basic_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ defmodule Mneme.Integration.BasicTest do
\\
bar
"""

# y
auto_assert "foo\rbar" <- "foo\rbar"
end

test "tuples" do
Expand Down

0 comments on commit b2ce9cd

Please sign in to comment.