First time asking a question here, apologies if this isn't sufficiently clear :)
I have a list of Foo
s, where Foo
is some struct type imported upstream. Foo has some field Bar
that is a bit complicated to calculate. Historically creation of a Foo
has looked like this:
bar := someComplicatedAndBespokeBarCalculator(...)
myFoo := Foo{
...
Bar: bar
}
but we recently created a standardized method for calculating Bar
. The now-recommended design pattern is:
myFooInline := Foo{
...
Bar: standardizedBarCalculator(...)
}
I would like to set up a custom linter rule that parses all my Foo
s with the go/ast
library to assert that all Foo
s are created with the second, inline pattern such that we can ensure that no Foo
is created without using the standardizedBarCalculator
. Very possibly I'm doing something wrong, but trying to use ast.Inspect
and cast an ast.Node
into an ast.StructType
only seems to work when I'm defining a new struct, not when I'm instantiating an instance of an upstream-defined struct. So, I'm struggling to figure out how to do this. Any guidance would be appreciated!
The steps you're looking for should be approximately something like this:
*ast.CompositeLit
.Type
field references the target Foo
type (use go/types.Info
).Elts
field will contain a list of ast.KeyValueExpr
.Key
for *ast.Ident
with Name=="Bar"
.Value
for *ast.CallExpr
.Fun
field should be an *ast.Ident
with Name="standardizedBarCalculator"
.