-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_swagger_annotations.py
More file actions
55 lines (43 loc) · 2.27 KB
/
check_swagger_annotations.py
File metadata and controls
55 lines (43 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from parser.init_parser import init_parser
def init_java_parser():
return init_parser('java')
def check_method_annotations(code):
parser = init_java_parser()
tree = parser.parse(bytes(code, 'utf8'))
root_node = tree.root_node
annotation_nodes = find_nodes_by_types(root_node, ['annotation', 'marker_annotation'])
api_ignore = any('@ApiIgnore' in node.text.decode('utf8') for node in annotation_nodes)
if api_ignore:
return True, "Method is ignored by @ApiIgnore."
api_operation = next((node for node in annotation_nodes if '@ApiOperation' in node.text.decode('utf8')), None)
if not api_operation:
return False, "Missing @ApiOperation annotation."
api_operation_content = api_operation.text.decode('utf8')
if 'httpMethod' not in api_operation_content:
return False, "Missing httpMethod in @ApiOperation annotation."
if 'value' not in api_operation_content:
return False, "Missing value in @ApiOperation annotation."
param_nodes = find_nodes_by_types(root_node, 'formal_parameter')
for param_node in param_nodes:
param_annotations = find_nodes_by_types(param_node, ['annotation', 'marker_annotation'])
has_request_body = any('@RequestBody' in node.text.decode('utf8') for node in param_annotations)
if not has_request_body:
api_param = next((node for node in param_annotations if '@ApiParam' in node.text.decode('utf8')), None)
if not api_param:
return False, "Missing @ApiParam annotation for parameter."
api_param_content = api_param.text.decode('utf8')
missing_fields = [field for field in ["value", "required", "example"] if field not in api_param_content]
if missing_fields:
return False, f"Missing fields in @ApiParam annotation for parameter: {', '.join(missing_fields)}"
return True, "Swagger annotations are compliant."
def find_nodes_by_types(root_node, node_types):
if not isinstance(node_types, list):
node_types = [node_types]
nodes = []
def collect_nodes(node):
if node.type in node_types:
nodes.append(node)
for child in node.children:
collect_nodes(child)
collect_nodes(root_node)
return nodes