gen icon indicating copy to clipboard operation
gen copied to clipboard

Get interface file fail when using ApplyInterface

Open sunyakun opened this issue 2 years ago • 0 comments

GORM Playground Link

make sure your GOROOT is not /usr/local/go before running the playground

https://github.com/go-gorm/playground/pull/642

Description

The gorm/gen use go/build:Default.Import to collect the interface file path when using ApplyInterface, and the Default.Import will running go list command which find the go executable by runtime.GOROOT(), but the runtime.GOROOT() return value will invalid in some scenarios such as my playground code. See more about the runtime.GOROOT() here.

Maybe golang.org/x/tools/go/packages is a better alternatives.

import (
        "golang.org/x/tools/go/packages"
        "fmt"
	"log"
	"reflect"
)

arg := reflect.TypeOf(query.CustomQuery{})
pkgs, err := packages.Load(nil, arg.PkgPath())
if err != nil {
        log.Printf("x/tools/go/packages: load fail: %s", err.Error())
} else {
        for _, pkg := range pkgs {
	        for _, file := range pkg.CompiledGoFiles {
		        fmt.Printf("%s\n", file)
	        }
        }
}

sunyakun avatar Aug 19 '23 13:08 sunyakun