This repository has been archived by the owner on Oct 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathparse_docstring.py
77 lines (65 loc) · 3.15 KB
/
parse_docstring.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import ast
import json
import os
from docstring_parser import parse
# Get the current directory
current_directory = os.getcwd()
# Walk through all the folders and files in the current directory
for root, dirs, files in os.walk(current_directory):
# Iterate through the files
for file in files:
# Check if the file is a Python file and has the same name as the folder
if file.endswith(".py") and file[:-3] == os.path.basename(root):
# Construct the file path
file_path = os.path.join(root, file)
# Read the contents of the Python file
with open(file_path, "r") as f:
code = f.read()
# Parse the code
tree = ast.parse(code)
# Find functions in the code
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
function_name = node.name
if function_name != os.path.basename(root):
# don't parse for any function that has a different
# name than the node file name
continue
# Extract docstring if available
if (
node.body
and isinstance(node.body[0], ast.Expr)
and isinstance(node.body[0].value, ast.Str)
):
docstring = node.body[0].value.s
# Process the docstring using docstring_parser
parsed_docstring = parse(docstring)
if (
parsed_docstring.short_description
or parsed_docstring.long_description
):
# Build the JSON data
json_data = {
"description": parsed_docstring.long_description,
"parameters": [
{
"name": param.arg_name,
"type": param.type_name,
"description": param.description,
}
for param in parsed_docstring.params
],
"returns": [
{
"name": rtn.return_name,
"type": rtn.type_name,
"description": rtn.description,
}
for rtn in parsed_docstring.many_returns
],
}
# Write the data to a JSON file in the same directory
output_file_path = os.path.join(root, "docstring.json")
with open(output_file_path, "w") as output_file:
json.dump(json_data, output_file, indent=2)
# sys.exit(0)