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.
25 // DefaultDir is default location of API files.
26 DefaultDir = "/usr/share/vpp/api"
29 // FindFiles finds API files located in dir or in a nested directory that is not nested deeper than deep.
30 func FindFiles(dir string, deep int) (files []string, err error) {
31 entries, err := ioutil.ReadDir(dir)
33 return nil, fmt.Errorf("reading directory %s failed: %v", dir, err)
35 for _, e := range entries {
36 if e.IsDir() && deep > 0 {
37 nestedDir := filepath.Join(dir, e.Name())
38 if nested, err := FindFiles(nestedDir, deep-1); err != nil {
41 files = append(files, nested...)
43 } else if !e.IsDir() && strings.HasSuffix(e.Name(), ".api.json") {
44 files = append(files, filepath.Join(dir, e.Name()))
50 // Parse parses API files in directory DefaultDir.
51 func Parse() ([]*File, error) {
52 return ParseDir(DefaultDir)
55 // ParseDir finds and parses API files in given directory and returns parsed files.
56 // Supports API files in JSON format (.api.json) only.
57 func ParseDir(apidir string) ([]*File, error) {
58 list, err := FindFiles(apidir, 1)
63 logf("found %d files in API dir %q", len(list), apidir)
66 for _, file := range list {
67 module, err := ParseFile(file)
71 files = append(files, module)
76 // ParseFile parses API file and returns File.
77 func ParseFile(apifile string) (*File, error) {
78 if !strings.HasSuffix(apifile, ".api.json") {
79 return nil, fmt.Errorf("unsupported file format: %q", apifile)
82 data, err := ioutil.ReadFile(apifile)
84 return nil, fmt.Errorf("reading file %s failed: %v", apifile, err)
87 base := filepath.Base(apifile)
88 name := base[:strings.Index(base, ".")]
90 logf("parsing file %q", base)
92 module, err := ParseRaw(data)
94 return nil, fmt.Errorf("parsing file %s failed: %v", base, err)
102 // ParseRaw parses raw API file data and returns File.
103 func ParseRaw(data []byte) (file *File, err error) {
105 if e := recover(); e != nil {
106 err = fmt.Errorf("panic occurred: %v", e)
110 file, err = parseJSON(data)