Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments via go generate

Tags:

go

generate

Here is how my project is structure

├── cmd
│   ├── orders
│   │   ├── main.go
└── scripts
    └── codegenerator.go

the codegenerator.go file is the file where i have put my code to generate the code. Here is the logic for codegenerator.go

  • rename main.go to old_main.go
  • read from old_main.go line by line and write to a new file called main.go
  • insert new lines/code blocks based on markers/placeholder in main.go
  • remove old_main.go file

The go:generate directive is in main.go like this

//go:generate go run ../../scripts/codegenerator.go

I ran go generate from command line and wanted to pass in 3 arguments so that they can be utilized in codegenerator.go. here is my command and the errors i got (i executed this command on path cmd/orders)

 $ go generate arg_one arg_two arg_three
can't load package: package arg_one: unknown import path "arg_one": cannot find module providing package arg_one
can't load package: package arg_two: unknown import path "arg_two": cannot find module providing package arg_two
can't load package: package arg_three: unknown import path "arg_three": cannot find module providing package arg_three

So the questions are

  1. Am i running go generate properly?
  2. How can i pass in arguments from go generate command line to the target script
like image 891
Em Ae Avatar asked Jan 19 '26 02:01

Em Ae


1 Answers

While I agree you may be better off using another solution, there isn't anything preventing usage of env vars (os specifics may vary)

➜  /tmp cat foo.go

package main

//go:generate python run.py $ARG

func main() {}
➜  /tmp cat run.py
import sys

print sys.argv[1]
➜  /tmp ARG=poop go generate foo.go
poop
like image 73
sberry Avatar answered Jan 20 '26 14:01

sberry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!