traefik / yaegi

Yaegi is Another Elegant Go Interpreter
https://pkg.go.dev/github.com/traefik/yaegi
Apache License 2.0
6.94k stars 343 forks source link

`GOPATH` environment variable is ignored when using interpreter #1517

Open karelorigin opened 1 year ago

karelorigin commented 1 year ago

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.

mvertes commented 1 year ago

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}) 
karelorigin commented 1 year ago

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

mvertes commented 1 year ago

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