Expose version info control flags
[govpp.git] / binapigen / run.go
1 //  Copyright (c) 2020 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 binapigen
16
17 import (
18         "fmt"
19         "io/ioutil"
20         "os"
21         "path"
22         "path/filepath"
23         "regexp"
24         "strings"
25
26         "github.com/sirupsen/logrus"
27
28         "git.fd.io/govpp.git/binapigen/vppapi"
29 )
30
31 type Options struct {
32         OutputDir        string // output directory for generated files
33         ImportPrefix     string // prefix for import paths
34         NoVersionInfo    bool   // disables generating version info
35         NoSourcePathInfo bool   // disables the 'source: /path' comment
36 }
37
38 func Run(apiDir string, filesToGenerate []string, opts Options, f func(*Generator) error) {
39         if err := run(apiDir, filesToGenerate, opts, f); err != nil {
40                 fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err)
41                 os.Exit(1)
42         }
43 }
44
45 func run(apiDir string, filesToGenerate []string, opts Options, fn func(*Generator) error) error {
46         apifiles, err := vppapi.ParseDir(apiDir)
47         if err != nil {
48                 return err
49         }
50
51         if opts.ImportPrefix == "" {
52                 opts.ImportPrefix, err = resolveImportPath(opts.OutputDir)
53                 if err != nil {
54                         return fmt.Errorf("cannot resolve import path for output dir %s: %w", opts.OutputDir, err)
55                 }
56                 logrus.Infof("resolved import path prefix: %s", opts.ImportPrefix)
57         }
58
59         gen, err := New(opts, apifiles, filesToGenerate)
60         if err != nil {
61                 return err
62         }
63
64         gen.vppVersion = vppapi.ResolveVPPVersion(apiDir)
65         if gen.vppVersion == "" {
66                 gen.vppVersion = "unknown"
67         }
68
69         if fn == nil {
70                 GenerateDefault(gen)
71         } else {
72                 if err := fn(gen); err != nil {
73                         return err
74                 }
75         }
76
77         if err = gen.Generate(); err != nil {
78                 return err
79         }
80
81         return nil
82 }
83
84 func GenerateDefault(gen *Generator) {
85         for _, file := range gen.Files {
86                 if !file.Generate {
87                         continue
88                 }
89                 GenerateAPI(gen, file)
90                 GenerateRPC(gen, file)
91         }
92 }
93
94 var Logger = logrus.New()
95
96 func init() {
97         if debug := os.Getenv("DEBUG_GOVPP"); strings.Contains(debug, "binapigen") {
98                 Logger.SetLevel(logrus.DebugLevel)
99                 logrus.SetLevel(logrus.DebugLevel)
100         }
101 }
102
103 func logf(f string, v ...interface{}) {
104         Logger.Debugf(f, v...)
105 }
106
107 // resolveImportPath tries to resolve import path for a directory.
108 func resolveImportPath(dir string) (string, error) {
109         absPath, err := filepath.Abs(dir)
110         if err != nil {
111                 return "", err
112         }
113         modRoot := findGoModuleRoot(absPath)
114         if modRoot == "" {
115                 return "", err
116         }
117         modPath, err := readModulePath(path.Join(modRoot, "go.mod"))
118         if err != nil {
119                 return "", err
120         }
121         relDir, err := filepath.Rel(modRoot, absPath)
122         if err != nil {
123                 return "", err
124         }
125         return filepath.Join(modPath, relDir), nil
126 }
127
128 // findGoModuleRoot looks for enclosing Go module.
129 func findGoModuleRoot(dir string) (root string) {
130         dir = filepath.Clean(dir)
131         for {
132                 if fi, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil && !fi.IsDir() {
133                         return dir
134                 }
135                 d := filepath.Dir(dir)
136                 if d == dir {
137                         break
138                 }
139                 dir = d
140         }
141         return ""
142 }
143
144 var modulePathRE = regexp.MustCompile(`module[ \t]+([^ \t\r\n]+)`)
145
146 // readModulePath reads module path from go.mod file.
147 func readModulePath(gomod string) (string, error) {
148         data, err := ioutil.ReadFile(gomod)
149         if err != nil {
150                 return "", err
151         }
152         m := modulePathRE.FindSubmatch(data)
153         if m == nil {
154                 return "", err
155         }
156         return string(m[1]), nil
157 }