Debian Codegraph @

ansible_collections/cisco/meraki/fmt.py

raw
1 import os
2 import re
3 import subprocess
4
5
6 def process_files(directory):
7 for root, _dirs, files in os.walk(directory):
8 for file in files:
9 if file.endswith(".py"):
10 process_file(os.path.join(root, file))
11
12
13 def process_file(filepath):
14 with open(filepath, 'r', encoding='utf-8') as file:
15 content = file.read()
16
17 sections = ['DOCUMENTATION', 'EXAMPLES', 'RETURN']
18 for section in sections:
19 content = process_section(content, section)
20
21 with open(filepath, 'w', encoding='utf-8') as file:
22 file.write(content)
23
24
25 def process_section(content, section):
26 pattern = rf'{section} = r""".*?"""'
27 match = re.search(pattern, content, re.DOTALL)
28 if match:
29 section_content = match.group(0)
30 yaml_content = section_content.split('r"""')[1].rsplit('"""', 1)[0].strip()
31
32 if section == 'DOCUMENTATION' or section == 'EXAMPLES':
33 with open('tmp.yaml', 'w', encoding='utf-8') as tmp_file:
34 tmp_file.write(yaml_content)
35
36 # subprocess.run(['yamlfmt', 'tmp.yaml'])
37 subprocess.run(['yamlfmt', 'tmp.yaml', '-conf', '.yamlfmt'], check=False)
38
39 with open('tmp.yaml', 'r', encoding='utf-8') as tmp_file:
40 formatted_content = tmp_file.read()
41
42 os.remove('tmp.yaml')
43 else:
44 formatted_content = yaml_content
45
46 if section == 'DOCUMENTATION':
47 formatted_content = update_notes_section(formatted_content)
48
49 formatted_content = re.sub(r'\n\s*\n', '\n', formatted_content).strip()
50 new_section_content = f'{section} = r"""\n{formatted_content}\n"""'
51 content = content.replace(section_content, new_section_content)
52
53 return content
54
55
56 def update_notes_section(content):
57 notes_pattern = re.compile(r'notes:\n( - .*\n)+', re.DOTALL)
58 match = notes_pattern.search(content)
59 if match:
60 notes_content = match.group(0)
61 # Ensure correct indentation and line breaks
62 updated_notes = re.sub(r',\s*', ',\n ', notes_content)
63 updated_notes = re.sub(r'(\n\s+)-\s+(SDK Method used are|Paths used are)', r'\n - \2\n ', updated_notes)
64 # Ensure the closing triple quotes are on a new line without spaces
65 updated_notes = re.sub(r'\n\s*"""', '\n"""', updated_notes)
66 content = content.replace(notes_content, updated_notes)
67 else:
68 print('No notes section found in DOCUMENTATION')
69 return content
70
71
72 if __name__ == "__main__":
73 directory = "/Users/franciscomunozmiranda/Desktop/Work/GitHub/dashboard-api-ansible/plugins/modules"
74 process_files(directory)