genbindings: support custom import headers in emitgo

This commit is contained in:
mappu 2024-08-10 10:28:02 +12:00
parent 9264bc6cc6
commit 8c572259c4

View File

@ -3,6 +3,7 @@ package main
import ( import (
"go/format" "go/format"
"log" "log"
"sort"
"strings" "strings"
) )
@ -82,8 +83,11 @@ func emitGo(src *CppParsedHeader, headerName string) (string, error) {
*/ */
import "C" import "C"
%%_IMPORTLIBS_%%
`) `)
imports := map[string]struct{}{}
for _, c := range src.Classes { for _, c := range src.Classes {
ret.WriteString(` ret.WriteString(`
@ -145,8 +149,24 @@ import "C"
} }
goSrc := ret.String()
// Fixup imports
if len(imports) > 0 {
allImports := make([]string, 0, len(imports))
for k, _ := range imports {
allImports = append(allImports, `"`+k+`"`)
}
sort.Strings(allImports)
goSrc = strings.Replace(goSrc, `%%_IMPORTLIBS_%%`, "import (\n\t"+strings.Join(allImports, "\n\t")+"\n)", 1)
} else {
goSrc = strings.Replace(goSrc, `%%_IMPORTLIBS_%%`, "", 1)
}
// Run gofmt over the result // Run gofmt over the result
formattedSrc, err := format.Source([]byte(ret.String())) formattedSrc, err := format.Source([]byte(goSrc))
if err != nil { if err != nil {
log.Printf("gofmt failure: %v", err) log.Printf("gofmt failure: %v", err)
formattedSrc = []byte(ret.String()) formattedSrc = []byte(ret.String())