Release 0.3.0
[govpp.git] / cmd / binapi-generator / generate.go
index fb6cee5..a8de5d5 100644 (file)
@@ -19,6 +19,7 @@ import (
        "fmt"
        "io"
        "os/exec"
+       "path"
        "path/filepath"
        "sort"
        "strings"
@@ -53,6 +54,8 @@ type context struct {
        inputFile  string // input file with VPP API in JSON
        outputFile string // output file with generated Go package
 
+       importPrefix string // defines import path prefix for importing types
+
        inputData []byte // contents of the input file
 
        includeAPIVersion  bool // include constant with API version string
@@ -99,13 +102,16 @@ func newContext(inputFile, outputDir string) (*context, error) {
 }
 
 func generatePackage(ctx *context, w io.Writer) error {
+       logf("----------------------------")
        logf("generating package %q", ctx.packageName)
+       logf("----------------------------")
 
        fmt.Fprintln(w, "// Code generated by GoVPP's binapi-generator. DO NOT EDIT.")
        fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
        fmt.Fprintln(w)
 
        generateHeader(ctx, w)
+       generateImports(ctx, w)
 
        // generate module desc
        fmt.Fprintln(w, "const (")
@@ -234,6 +240,9 @@ func generateHeader(ctx *context, w io.Writer) {
        fmt.Fprintf(w, "package %s\n", ctx.packageName)
        fmt.Fprintln(w)
 
+}
+
+func generateImports(ctx *context, w io.Writer) {
        fmt.Fprintln(w, "import (")
        fmt.Fprintf(w, "\tapi \"%s\"\n", govppApiImportPath)
        fmt.Fprintf(w, "\tbytes \"%s\"\n", "bytes")
@@ -244,15 +253,18 @@ func generateHeader(ctx *context, w io.Writer) {
        if len(ctx.packageData.Imports) > 0 {
                fmt.Fprintln(w)
                for _, imp := range getImports(ctx) {
-                       impPkg := getImportPkg(filepath.Dir(ctx.outputFile), imp)
-                       fmt.Fprintf(w, "\t%s \"%s\"\n", imp, strings.TrimSpace(impPkg))
+                       importPath := path.Join(ctx.importPrefix, imp)
+                       if importPath == "" {
+                               importPath = getImportPath(filepath.Dir(ctx.outputFile), imp)
+                       }
+                       fmt.Fprintf(w, "\t%s \"%s\"\n", imp, strings.TrimSpace(importPath))
                }
        }
        fmt.Fprintln(w, ")")
        fmt.Fprintln(w)
 }
 
-func getImportPkg(outputDir string, pkg string) string {
+func getImportPath(outputDir string, pkg string) string {
        absPath, _ := filepath.Abs(filepath.Join(outputDir, "..", pkg))
        cmd := exec.Command("go", "list", absPath)
        var errbuf, outbuf bytes.Buffer