yaegi icon indicating copy to clipboard operation
yaegi copied to clipboard

`GOPATH` environment variable is ignored when using interpreter

Open karelorigin opened this issue 1 year ago • 3 comments

The following program sample.go triggers an unexpected result

package main

import (
	"fmt"

	"github.com/traefik/yaegi/interp"
)

var script = `package main

import (
	"fmt"
)

func main() {
	fmt.Println("hello there")
}
`

func main() {
	i := interp.New(interp.Options{})

	_, err := i.Eval(script)
	if err != nil {
		fmt.Println("Error:", err)
	}
}

Expected result

$ env GOPATH=~/go/ go run main.go
// hello there

Got

$ env GOPATH=~/go/ go run main.go
// Error: 4:2: import "fmt" error: unable to find source related to: "fmt". Either the GOPATH environment variable, or the Interpreter.Options.GoPath needs to be set

Yaegi Version

v0.15.0

Additional Notes

Yaegi states that the GOPATH environment variable is used for finding packages, except it never is. This only seems to work for the Yaegi binary, which explicitly passes it to the interpreter options.

karelorigin avatar Feb 24 '23 18:02 karelorigin

Yes, the GOPATH environment variable is used by default for the command line executable (github.com/traefik/yaegi/cmd/yaegi), but not by the library package (github.com/traefik/yaegi/interp) that you use in your example. This is on purpose, for security reason when the interpreter is embedded in another host process and that we require the full control of the GOPATH, possibly fully separated from the default. We decided to make the management of GOPATH explicit, with an empty default.

You can still pass the GOPATH when creating the interpreter as in the following:

I := interp.New(interp.Options{GoPath: build.Default.GOPATH}) 

mvertes avatar Mar 23 '23 11:03 mvertes

Could it be a good idea to change the error message as it's (almost) never applicable and thus not accurate?

karelorigin avatar Mar 23 '23 11:03 karelorigin

@karelorigin yes you're right. I haven't noticed that the error message is inaccurate and needs to be changed. Thanks.

mvertes avatar Mar 23 '23 11:03 mvertes