Fix union data size for types with enums
[govpp.git] / cmd / binapi-generator / main.go
1 // Copyright (c) 2018 Cisco and/or its affiliates.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package main
16
17 import (
18         "bufio"
19         "encoding/json"
20         "flag"
21         "fmt"
22         "io/ioutil"
23         "os"
24         "os/exec"
25         "path/filepath"
26         "strings"
27
28         "github.com/bennyscetbun/jsongo"
29         "github.com/sirupsen/logrus"
30 )
31
32 var (
33         inputFile          = flag.String("input-file", "", "Input file with VPP API in JSON format.")
34         inputDir           = flag.String("input-dir", ".", "Input directory with VPP API files in JSON format.")
35         outputDir          = flag.String("output-dir", ".", "Output directory where package folders will be generated.")
36         includeAPIVer      = flag.Bool("include-apiver", false, "Include APIVersion constant for each module.")
37         includeComments    = flag.Bool("include-comments", false, "Include JSON API source in comments for each object.")
38         includeBinapiNames = flag.Bool("include-binapi-names", false, "Include binary API names in struct tag.")
39         continueOnError    = flag.Bool("continue-onerror", false, "Continue with next file on error.")
40         debug              = flag.Bool("debug", debugMode, "Enable debug mode.")
41 )
42
43 var debugMode = os.Getenv("DEBUG_BINAPI_GENERATOR") != ""
44
45 var log = logrus.Logger{
46         Level:     logrus.InfoLevel,
47         Formatter: &logrus.TextFormatter{},
48         Out:       os.Stdout,
49 }
50
51 func main() {
52         flag.Parse()
53         if *debug {
54                 logrus.SetLevel(logrus.DebugLevel)
55         }
56
57         if *inputFile == "" && *inputDir == "" {
58                 fmt.Fprintln(os.Stderr, "ERROR: input-file or input-dir must be specified")
59                 os.Exit(1)
60         }
61
62         if *inputFile != "" {
63                 // process one input file
64                 if err := generateFromFile(*inputFile, *outputDir); err != nil {
65                         fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", *inputFile, err)
66                         os.Exit(1)
67                 }
68         } else {
69                 // process all files in specified directory
70                 files, err := getInputFiles(*inputDir)
71                 if err != nil {
72                         fmt.Fprintf(os.Stderr, "ERROR: code generation failed: %v\n", err)
73                         os.Exit(1)
74                 }
75                 for _, file := range files {
76                         if err := generateFromFile(file, *outputDir); err != nil {
77                                 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", file, err)
78                                 if *continueOnError {
79                                         continue
80                                 }
81                                 os.Exit(1)
82                         }
83                 }
84         }
85 }
86
87 // getInputFiles returns all input files located in specified directory
88 func getInputFiles(inputDir string) (res []string, err error) {
89         files, err := ioutil.ReadDir(inputDir)
90         if err != nil {
91                 return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
92         }
93         for _, f := range files {
94                 if strings.HasSuffix(f.Name(), inputFileExt) {
95                         res = append(res, filepath.Join(inputDir, f.Name()))
96                 }
97         }
98         return res, nil
99 }
100
101 // generateFromFile generates Go package from one input JSON file
102 func generateFromFile(inputFile, outputDir string) error {
103         logf("generating from file: %q", inputFile)
104         defer logf("--------------------------------------")
105
106         ctx, err := getContext(inputFile, outputDir)
107         if err != nil {
108                 return err
109         }
110
111         ctx.includeAPIVersionCrc = *includeAPIVer
112         ctx.includeComments = *includeComments
113         ctx.includeBinapiNames = *includeBinapiNames
114
115         // read input file contents
116         ctx.inputData, err = readFile(inputFile)
117         if err != nil {
118                 return err
119         }
120         // parse JSON data into objects
121         jsonRoot, err := parseJSON(ctx.inputData)
122         if err != nil {
123                 return err
124         }
125         ctx.packageData, err = parsePackage(ctx, jsonRoot)
126         if err != nil {
127                 return err
128         }
129
130         // create output directory
131         packageDir := filepath.Dir(ctx.outputFile)
132         if err := os.MkdirAll(packageDir, 0777); err != nil {
133                 return fmt.Errorf("creating output directory %q failed: %v", packageDir, err)
134         }
135         // open output file
136         f, err := os.Create(ctx.outputFile)
137         if err != nil {
138                 return fmt.Errorf("creating output file %q failed: %v", ctx.outputFile, err)
139         }
140         defer f.Close()
141
142         // generate Go package code
143         w := bufio.NewWriter(f)
144         if err := generatePackage(ctx, w); err != nil {
145                 return err
146         }
147
148         // go format the output file (fail probably means the output is not compilable)
149         cmd := exec.Command("gofmt", "-w", ctx.outputFile)
150         if output, err := cmd.CombinedOutput(); err != nil {
151                 return fmt.Errorf("gofmt failed: %v\n%s", err, string(output))
152         }
153
154         // count number of lines in generated output file
155         cmd = exec.Command("wc", "-l", ctx.outputFile)
156         if output, err := cmd.CombinedOutput(); err != nil {
157                 log.Warnf("wc command failed: %v\n%s", err, string(output))
158         } else {
159                 logf("generated lines: %s", output)
160         }
161
162         return nil
163 }
164
165 // readFile reads content of a file into memory
166 func readFile(inputFile string) ([]byte, error) {
167         inputData, err := ioutil.ReadFile(inputFile)
168         if err != nil {
169                 return nil, fmt.Errorf("reading data from file failed: %v", err)
170         }
171
172         return inputData, nil
173 }
174
175 // parseJSON parses a JSON data into an in-memory tree
176 func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
177         root := jsongo.JSONNode{}
178
179         if err := json.Unmarshal(inputData, &root); err != nil {
180                 return nil, fmt.Errorf("unmarshalling JSON failed: %v", err)
181         }
182
183         return &root, nil
184 }
185
186 func logf(f string, v ...interface{}) {
187         if *debug {
188                 logrus.Debugf(f, v...)
189         }
190 }