Sourceror.patch_string
You're seeing just the function
patch_string
, go back to Sourceror module for more information.
Specs
Applies one or more patches to the given string.
This functions limits itself to apply the patches in order, but it does not check for overlapping ranges, so make sure to pass non-overlapping patches.
A patch is a map containing at least the range that it should patch, and the change to be applied in the range, for example:
iex> original = ~S"""
...> if not allowed? do
...> raise "Not allowed!"
...> end
...> """
iex> patch = %{
...> change: "unless allowed? do\n raise \"Not allowed!\"\nend",
...> range: %{start: [line: 1, column: 1], end: [line: 3, column: 4]}
...> }
iex> Sourceror.patch_string(original, [patch])
~S"""
unless allowed? do
raise "Not allowed!"
end
"""
A range can also be a function, in which case the original text in the patch range will be given as an argument:
iex> original = ~S"""
...> hello :world
...> """
iex> patch = %{
...> change: &String.upcase/1,
...> range: %{start: [line: 1, column: 7], end: [line: 1, column: 13]}
...> }
iex> Sourceror.patch_string(original, [patch])
~S"""
hello :WORLD
"""
By default, the patch will be automatically indented to match the indentation of the range it wants to replace if the change is a text string:
iex> original = ~S"""
...> foo do bar do
...> :ok
...> end end
...> """
iex> patch = %{
...> change: "baz do\n :not_ok\nend",
...> range: %{start: [line: 1, column: 8], end: [line: 3, column: 6]}
...> }
iex> Sourceror.patch_string(original, [patch])
~S"""
foo do baz do
:not_ok
end end
"""
If you don't want this behavior, you can add :preserve_indentation: false
to
your patch:
iex> original = ~S"""
...> foo do bar do
...> :ok
...> end end
...> """
iex> patch = %{
...> change: "baz do\n :not_ok\nend",
...> range: %{start: [line: 1, column: 8], end: [line: 3, column: 6]},
...> preserve_indentation: false
...> }
iex> Sourceror.patch_string(original, [patch])
~S"""
foo do baz do
:not_ok
end end
"""