1 // Copyright (c) 2020 Cisco and/or its affiliates.
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:
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
23 "github.com/sirupsen/logrus"
27 DefaultAPIDir = "/usr/share/vpp/api"
30 const apifileSuffixJson = ".api.json"
32 // FindFiles returns all input files located in specified directory
33 func FindFiles(dir string, deep int) (paths []string, err error) {
34 entries, err := ioutil.ReadDir(dir)
36 return nil, fmt.Errorf("reading directory %s failed: %v", dir, err)
38 for _, e := range entries {
39 if e.IsDir() && deep > 0 {
40 nestedDir := filepath.Join(dir, e.Name())
41 if nested, err := FindFiles(nestedDir, deep-1); err != nil {
44 paths = append(paths, nested...)
46 } else if strings.HasSuffix(e.Name(), apifileSuffixJson) {
47 paths = append(paths, filepath.Join(dir, e.Name()))
53 func Parse() ([]*File, error) {
54 return ParseDir(DefaultAPIDir)
57 func ParseDir(apidir string) ([]*File, error) {
58 files, err := FindFiles(apidir, 1)
63 logrus.Infof("found %d files in API dir %q", len(files), apidir)
67 for _, file := range files {
68 module, err := ParseFile(file)
72 modules = append(modules, module)
78 // ParseFile parses API file contents and returns File.
79 func ParseFile(apifile string) (*File, error) {
80 if !strings.HasSuffix(apifile, apifileSuffixJson) {
81 return nil, fmt.Errorf("unsupported file format: %q", apifile)
84 data, err := ioutil.ReadFile(apifile)
86 return nil, fmt.Errorf("reading file %s failed: %v", apifile, err)
89 base := filepath.Base(apifile)
90 name := base[:strings.Index(base, ".")]
92 logf("parsing file %q", base)
94 module, err := ParseRaw(data)
96 return nil, fmt.Errorf("parsing file %s failed: %v", base, err)
104 func ParseRaw(data []byte) (file *File, err error) {
105 file, err = parseJSON(data)