Sourceror.Patch (Sourceror v0.11.0) View Source

Functions that generate patches for common operations.

Functions in this module assume that the AST was parsed using Sourceror functions and that it wasn't modified. If you changed the tree before calling Sourceror.Patch functions, then the patch ranges are not guaranteed to match 1:1 with the original source code.

Link to this section Summary

Functions

Renames a qualified or unqualified function call.

Renames an identifier(ie a variable name).

Generates patches that rename the keys of a keyword list.

Link to this section Functions

Link to this function

rename_call(arg, new_name)

View Source

Specs

rename_call(call :: Macro.t(), new_name :: atom() | String.t()) :: [
  Sourceror.patch()
]

Renames a qualified or unqualified function call.

iex> original = "String.to_atom(foo)"
iex> ast = Sourceror.parse_string!(original)
iex> patches = Sourceror.Patch.rename_call(ast, :to_existing_atom)
iex> Sourceror.patch_string(original, patches)
"String.to_existing_atom(foo)"

If the call is a sigil, you only need to provide the replacement letter:

iex> original = "~H(foo)"
iex> ast = Sourceror.parse_string!(original)
iex> patches = Sourceror.Patch.rename_call(ast, :F)
iex> Sourceror.patch_string(original, patches)
"~F(foo)"
Link to this function

rename_identifier(arg, new_name)

View Source

Specs

rename_identifier(identifier :: Macro.t(), new_name :: atom() | String.t()) :: [
  Sourceror.patch()
]

Renames an identifier(ie a variable name).

Examples

iex> original = "foo"
iex> ast = Sourceror.parse_string!(original)
iex> patches = Sourceror.Patch.rename_identifier(ast, :bar)
iex> Sourceror.patch_string(original, patches)
"bar"
Link to this function

rename_kw_keys(arg, replacements)

View Source

Specs

rename_kw_keys(keyword :: Macro.t(), replacements :: keyword()) :: [
  Sourceror.patch()
]

Generates patches that rename the keys of a keyword list.

The replacements is a keyword list, with the keys to replace as keys, and the replacement as the value.

Examples

iex> original = "[a: b, c: d, e: f]"
iex> ast = Sourceror.parse_string!(original)
iex> patches = Sourceror.Patch.rename_kw_keys(ast, a: :foo, e: :bar)
iex> Sourceror.patch_string(original, patches)
"[foo: b, c: d, bar: f]"