Skip to content

Instantly share code, notes, and snippets.

@charith-elastic
Last active January 27, 2021 11:31
Show Gist options
  • Save charith-elastic/16e99af837da8a33b25153f4528d84b8 to your computer and use it in GitHub Desktop.
Save charith-elastic/16e99af837da8a33b25153f4528d84b8 to your computer and use it in GitHub Desktop.
AST Refactoring

Refactoring with AST transforms

Problem

  • We want to change the k8s.Client interface to match the client.Client interface.
  • The two interfaces are identical except for the fact that client.Client methods all take a context.Context as the first parameter.
  • k8s.Client is used everywhere in the codebase and manually changing all occurrences would be very tedious and error-prone.
  • In most places, when we modify the method call we need to add an import for context as well.

Possible solutions

  • Search and replace script
    • Requires very complicated regex to be written
    • Lots of false positives because it's not aware of the context. (E.g. It will update all Get methods regardless of whether those methods actually belong to the k8s.Client interface.
  • Go's example-based refactoring tool eg
    • Unfortunately it doesn't work on my machine and always gets stuck. I suspect it is because it doesn't understand Go modules and tries to refactor ALL the Go code it finds in my machine.
  • Custom AST transform
    • What could go wrong?

Go AST Transform

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment