-
Notifications
You must be signed in to change notification settings - Fork 4
/
readme_generator.py
176 lines (153 loc) · 7.08 KB
/
readme_generator.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import re
import logging
from collections import defaultdict
# Setup logging
logging.basicConfig(filename='readme_generation.log', filemode='w', level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s')
# Function to escape special characters for Markdown
def escape_markdown(text):
escape_chars = {
'*': '\\*',
'_': '\\_',
'[': '\\[',
']': '\\]',
'(': '\\(',
')': '\\)',
'#': '\\#',
'+': '\\+',
'-': '\\-',
'!': '\\!',
'~': '\\~',
'|': '\\|',
'<': '\\<',
'>': '\\>',
'`': '\\`',
}
for char, escaped in escape_chars.items():
text = text.replace(char, escaped)
return text
# Function to parse a single SQLX file and extract relevant details
def parse_sqlx(file_content: str, filename: str) -> dict:
logging.info(f"Parsing file: {filename}")
function_pattern = re.compile(
r"CREATE OR REPLACE (?:AGGREGATE )?FUNCTION\s+\$\{self\(\)\}\((.*?)\)\s+RETURNS\s+([^;]+?)(?=\s+(?:LANGUAGE|OPTIONS|$))",
re.DOTALL
)
description_pattern = re.compile(r"description\s*=\s*['\"]{3}(.*?)['\"]{3}", re.DOTALL)
# Extract function signature and return type
function_match = function_pattern.search(file_content)
if function_match:
function_signature = function_match.group(1).strip()
return_type = function_match.group(2).strip()
logging.debug(f"Function signature: {function_signature}")
logging.debug(f"Return type: {return_type}")
else:
function_signature = ""
return_type = "UNKNOWN"
logging.warning(f"No function signature or return type found in {filename}")
# Extract description
description_match = description_pattern.search(file_content)
description = description_match.group(1).strip() if description_match else "No description available"
description = re.compile(r'\n*For more info.*', re.M | re.S).sub('', description) # remove repetitive links
description = description.replace('\n', '<br>')
description = escape_markdown(description)
# Extract function arguments and their types
arg_list = []
for arg in re.split(r",\s*(?![^<>]*>)", function_signature): # Split by comma only if not within "<>"
arg_parts = arg.strip().split()
if len(arg_parts) >= 2: # Allow more than two parts for complex arguments
arg_list.append((arg_parts[0], " ".join(arg_parts[1:]))) # (arg_name, arg_type)
elif arg.strip(): # Ignore empty arguments
logging.warning(f"Unexpected argument format in {filename}: {arg}")
# Determine function type
function_type = "AGGREGATE" if "AGGREGATE FUNCTION" in file_content else "SCALAR"
return {
"function_name": filename[:-5], # Remove file extension .sqlx
"signature": f"({', '.join([f'{arg[0]} {arg[1]}' for arg in arg_list])}) -> {return_type}",
"description": description,
"function_type": function_type,
}
# Function to walk through directories, parse SQLX files, and collect data for README
def process_folder(input_folder: str, sketch_type: str) -> dict:
function_index = defaultdict(list)
for root, dirs, files in os.walk(input_folder):
for file in files:
if file.endswith(".sqlx"):
sqlx_path = os.path.join(root, file)
logging.info(f"Processing file: {sqlx_path}")
with open(sqlx_path, 'r') as f:
content = f.read()
# Parse the SQLX content
parsed_data = parse_sqlx(content, file)
logging.info(f"Parsed data for {file}: {parsed_data}")
function_index[sketch_type].append({
'function_name': parsed_data['function_name'],
'signature': parsed_data['signature'],
'function_type':parsed_data['function_type'],
'description': parsed_data['description'],
'path': sqlx_path
})
return function_index
# Function to generate README content based on the template
def generate_readme(template_path: str, function_index: dict, examples_path: str) -> str:
# Read the template file
with open(template_path, 'r') as template_file:
output_lines = template_file.readlines()
# Generate the table content
output_lines += "\n"
output_lines += "| Function Name | Function Type | Signature | Description |\n"
output_lines += "|---|---|---|---|\n" # table header
# Sort functions by function type (AGGREGATE first, then SCALAR) and then by number of arguments
sorted_functions = sorted(function_index, key=lambda x: (x['function_type'], len(x['signature'].split(','))), reverse=False)
for function in sorted_functions:
function_link = f"[{function['function_name']}](../{function['path']})"
output_lines += f"| {function_link} | {function['function_type']} | {function['signature']} | {function['description']} |\n"
# Add examples section
example_files = [f for f in os.listdir(examples_path) if f.endswith("_test.sql")]
if example_files:
output_lines.append("\n**Examples:**\n\n")
for example_file in example_files:
# Read the example SQL file
with open(os.path.join(examples_path, example_file), 'r') as f:
sql_code = f.read()
# Remove license header from examples
sql_code_lines = sql_code.splitlines()
start_index = 0
for i, line in enumerate(sql_code_lines):
if not line.startswith("/*") and not line.startswith(" *") and not line.startswith(" */"):
start_index = i
break
sql_code_without_license = "\n".join(sql_code_lines[start_index:])
# Add the SQL code in a code block
output_lines.append(f"```sql\n{sql_code_without_license}\n```\n")
output_content = "".join(output_lines)
return output_content
if __name__ == "__main__":
sketch_types = ["cpc", "fi", "hll", "kll", "tdigest", "theta", "tuple"]
template_name = "README_template.md"
readme_name = "README.md"
for sketch_type in sketch_types:
logging.info("processing sketch type " + sketch_type)
function_index = process_folder(os.path.join("definitions", sketch_type), sketch_type)
sketch_type_readme_name = os.path.join(sketch_type, readme_name)
logging.info("generating " + sketch_type_readme_name)
readme_content = generate_readme(os.path.join(sketch_type, template_name), function_index[sketch_type], os.path.join(sketch_type, "test"))
with open(sketch_type_readme_name, "w") as readme_file:
readme_file.write(readme_content)
logging.info(sketch_type_readme_name + " generated successfully")