1#!/usr/bin/env python3
2
3# Copyright 2016 gRPC authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import collections
18import fnmatch
19import os
20import re
21import sys
22
23import yaml
24
25_RE_API = r'(?:GPRAPI|GRPCAPI|CENSUSAPI)([^#;]*);'
26
27
28def list_c_apis(filenames):
29    for filename in filenames:
30        with open(filename, 'r') as f:
31            text = f.read()
32        for m in re.finditer(_RE_API, text):
33            api_declaration = re.sub('[ \r\n\t]+', ' ', m.group(1))
34            type_and_name, args_and_close = api_declaration.split('(', 1)
35            args = args_and_close[:args_and_close.rfind(')')].strip()
36            last_space = type_and_name.rfind(' ')
37            last_star = type_and_name.rfind('*')
38            type_end = max(last_space, last_star)
39            return_type = type_and_name[0:type_end + 1].strip()
40            name = type_and_name[type_end + 1:].strip()
41            yield {
42                'return_type': return_type,
43                'name': name,
44                'arguments': args,
45                'header': filename
46            }
47
48
49def headers_under(directory):
50    for root, dirnames, filenames in os.walk(directory):
51        for filename in fnmatch.filter(filenames, '*.h'):
52            yield os.path.join(root, filename)
53
54
55def mako_plugin(dictionary):
56    apis = []
57    headers = []
58
59    for lib in dictionary['libs']:
60        if lib['name'] in ['grpc', 'gpr']:
61            headers.extend(lib['public_headers'])
62
63    apis.extend(list_c_apis(sorted(set(headers))))
64    dictionary['c_apis'] = apis
65
66
67if __name__ == '__main__':
68    print(
69        (yaml.dump([api for api in list_c_apis(headers_under('include/grpc'))
70                   ])))
71