Make the warnings for validating services more obvious
[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 JSON file.")
34         inputDir        = flag.String("input-dir", ".", "Input directory with JSON files.")
35         outputDir       = flag.String("output-dir", ".", "Output directory where package folders will be generated.")
36         includeAPIVer   = flag.Bool("include-apiver", false, "Whether to include VlAPIVersion in generated file.")
37         debug           = flag.Bool("debug", false, "Turn on debug mode.")
38         continueOnError = flag.Bool("continue-onerror", false, "Wheter to continue with next file on error.")
39 )
40
41 func init() {
42         flag.Parse()
43         if *debug {
44                 logrus.SetLevel(logrus.DebugLevel)
45         }
46 }
47
48 func logf(f string, v ...interface{}) {
49         if *debug {
50                 logrus.Debugf(f, v...)
51         }
52 }
53
54 var log = logrus.Logger{
55         Level:     logrus.InfoLevel,
56         Formatter: &logrus.TextFormatter{},
57         Out:       os.Stdout,
58 }
59
60 func main() {
61         if *inputFile == "" && *inputDir == "" {
62                 fmt.Fprintln(os.Stderr, "ERROR: input-file or input-dir must be specified")
63                 os.Exit(1)
64         }
65
66         if *inputFile != "" {
67                 // process one input file
68                 if err := generateFromFile(*inputFile, *outputDir); err != nil {
69                         fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", *inputFile, err)
70                         os.Exit(1)
71                 }
72         } else {
73                 // process all files in specified directory
74                 files, err := getInputFiles(*inputDir)
75                 if err != nil {
76                         fmt.Fprintf(os.Stderr, "ERROR: code generation failed: %v\n", err)
77                         os.Exit(1)
78                 }
79                 for _, file := range files {
80                         if err := generateFromFile(file, *outputDir); err != nil {
81                                 fmt.Fprintf(os.Stderr, "ERROR: code generation from %s failed: %v\n", file, err)
82                                 if *continueOnError {
83                                         continue
84                                 }
85                                 os.Exit(1)
86                         }
87                 }
88         }
89 }
90
91 // getInputFiles returns all input files located in specified directory
92 func getInputFiles(inputDir string) (res []string, err error) {
93         files, err := ioutil.ReadDir(inputDir)
94         if err != nil {
95                 return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
96         }
97         for _, f := range files {
98                 if strings.HasSuffix(f.Name(), inputFileExt) {
99                         res = append(res, filepath.Join(inputDir, f.Name()))
100                 }
101         }
102         return res, nil
103 }
104
105 // generateFromFile generates Go package from one input JSON file
106 func generateFromFile(inputFile, outputDir string) error {
107         logf("generating from file: %q", inputFile)
108         defer logf("--------------------------------------")
109
110         ctx, err := getContext(inputFile, outputDir)
111         if err != nil {
112                 return err
113         }
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 }