Toolkit for shell script used in go:generate
.
go get -u github.com/utisam/gogtok/cmd/gogtok
gogtok new FILENAME
to generate a new script file- Add
//go:generate ./filename.sh
in your code. - Write script to render source
glue
: Generate glue codeimport [packages...]
: Generate import statementlist funcs/values/types [files...]
: Parse source files and show declarationslist fields [file] [name]
: Parse source files and show fieldsnew [name]
: Generate new script from boilerplatepackage name [dir]
: Show package name of the directorypackage path [dir]
: Show package path of the directory
goimports
cannot resolve package which has the same name with other packages.
For example, template
is matched with text/template
and html/template
,
then you must specify package.
render_import() {
gogtok import \
"text/template" \
"crypto/rand" \
"$(gogtok package path ..)/config"
}
gogtok import
generates a import block only if there are multiple packages.
gogtok package
rsespects GO111MODULE
and parse go.mod
in the parent directory.
render_convert() {
cat <<-EOS
func convert(a *OtherStruct) *SomeStruct {
return &SomeStruct{
EOS
gogtok list fields some.go SomeStruct | xargs gogtok glue a
cat <<-EOS
}
}
EOS
}
This function generates following code when SomeStruct
has 4 fields W
, X
, Y
, Z
:
func convert(a *OtherStruct) *SomeStruct {
return *SomeStruct{
W: a.W,
X: a.X,
Y: a.Y,
Z: a.Z,
}
}
gogtok glue
has options to customize glue code. See gogtok help glue
.
source <(go env)
gogtok list values \
--filter-decl-type Kind \
"${GOROOT}/src/reflect/type.go"
name
, type
, tags
and tag[key]
can be used to --columns
option.
gogtok list fields --print0 --columns 'name,type,tag[json]' file.go SomeStruct | \
while IFS= read -r -d '' name && read -r -d '' type && read -r -d '' tag_json
do
echo "name: $name, type: $type, tag[json]: $tag_json"
done
--print0
is usefull when you want to handle types and/or tags which contain space.
Like find -print0
, NULL chars are used to output.
xargs -0
can be used to pass the regular commands.