Skip to content

Commit bbb7b59

Browse files
committed
micro refact code
1 parent 0c21135 commit bbb7b59

File tree

1 file changed

+55
-37
lines changed

1 file changed

+55
-37
lines changed

docs/python/generators/examples_page.py

Lines changed: 55 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,64 +14,75 @@
1414
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
1515
import io
1616
import os
17+
import mkdocs_gen_files
1718
from pathlib import Path
19+
from typing import Any
1820

1921
from docs.python.generators import regexes, common
2022

2123

24+
def collect_srcs(top: str):
25+
for root, _, files in os.walk(top):
26+
for f in files:
27+
if f.endswith(('.h', 'cpp', 'CMakeLists.txt')):
28+
yield Path(root) / f
29+
30+
def get_id(title: str) -> str:
31+
assert title.startswith("# ")
32+
33+
title = title.lstrip("# ").rstrip("\n")
34+
35+
if "{" in title:
36+
id = title[title.find("{#")+2:title.find("}")]
37+
title = title[:title.find("{#")]
38+
39+
else:
40+
id = title.lower()
41+
for i in " _":
42+
id = id.replace(i, "-")
43+
44+
id = "".join(ch for ch in id if ch.isalnum() or ch == '-')
45+
id = id.strip('-')
46+
47+
return id
48+
49+
def descriptions(readlines: list[str]):
50+
description = ""
51+
for line in readlines:
52+
if m := regexes.AUI_EXAMPLE.match(line):
53+
category = m.group(1)
54+
for description_line in readlines:
55+
description_line = description_line.strip("\n")
56+
description += " " + description_line
57+
description = description.strip()
58+
59+
return category, description
60+
2261
def examine():
2362
EXAMPLES_DIR = Path.cwd() / "examples"
2463
EXAMPLES_DIR = EXAMPLES_DIR.as_posix()
2564

2665
examples_lists = {}
2766

28-
for root, dirs, files in os.walk(EXAMPLES_DIR):
67+
for root, _, files in os.walk(EXAMPLES_DIR):
2968
for file in files:
3069
if file != "README.md":
3170
continue
3271

3372
example_path = str(Path(root).relative_to(EXAMPLES_DIR))
34-
if "/" not in example_path and "\\" not in example_path:
73+
if os.sep not in example_path:
3574
continue
3675

3776
example_path = example_path.replace(os.sep, "_")
3877

39-
def collect_srcs(top):
40-
for root, dirs, files in os.walk(top):
41-
for f in files:
42-
if any(f.endswith(ext) for ext in ['.h', 'cpp', 'CMakeLists.txt']):
43-
yield Path(root) / f
44-
4578
srcs = list(collect_srcs(root))
4679

4780
input_file = Path(root) / file
4881
with open(input_file, 'r', encoding='utf-8') as fis:
4982
title = fis.readline()
50-
assert title.startswith("# ")
51-
title = title.lstrip("# ").rstrip("\n")
52-
if "{" in title:
53-
id = title[title.find("{#")+2:title.find("}")]
54-
title = title[:title.find("{#")]
55-
else:
56-
id = title.lower()
57-
for i in [" ", "_"]:
58-
id = id.replace(i, "-")
59-
id = "".join(ch for ch in id if ch.isalnum() or ch == '-')
60-
id = id.strip('-')
61-
62-
category = None
63-
description = ""
64-
it = iter(fis.readlines())
65-
for line in it:
66-
if m := regexes.AUI_EXAMPLE.match(line):
67-
category = m.group(1)
68-
for description_line in it:
69-
description_line = description_line.strip("\n")
70-
if not description_line:
71-
break
72-
description += " " + description_line
73-
74-
description = description.strip()
83+
id = get_id(title)
84+
category, description = descriptions(fis.readlines())
85+
7586
if not id:
7687
raise RuntimeError(f"no id provided in {input_file}")
7788
if not category:
@@ -87,12 +98,15 @@ def collect_srcs(top):
8798
'srcs': srcs,
8899
})
89100

101+
if not examples_lists:
102+
raise RuntimeError("no examples provided")
103+
90104
return examples_lists
91105

92106

107+
93108
examples_lists = examine()
94-
if not examples_lists:
95-
raise RuntimeError("no examples provided")
109+
96110

97111
def define_env(env):
98112
@env.macro
@@ -118,23 +132,27 @@ def example(category: str):
118132
"""
119133

120134
def gen_pages():
121-
import mkdocs_gen_files
122135
for category_name, category in examples_lists.items():
123136
for example in category:
124137
id = example['id']
125138
page_path = example['page_path']
139+
126140
mkdocs_gen_files.set_edit_path(f"{id}.md", '..' / page_path.relative_to(Path.cwd()))
141+
127142
with mkdocs_gen_files.open(f"{id}.md", "w") as fos:
128143
with io.open(page_path, 'r', encoding='utf-8') as fis:
129144
contents = fis.read()
145+
130146
print(contents, file=fos, end='')
131147

132148
if not example['srcs']:
133149
if "## Source Code" not in contents:
134150
raise RuntimeError(f'{page_path} contains neither "## Source Code" section nor source files.')
135151
continue
152+
136153
print('\n## Source Code\n\n', file=fos)
137154
print(f'[ <!-- aui:icon octicons-link-external-16 --> Repository ](https://github.com/aui-framework/aui/tree/master/{page_path.relative_to(Path.cwd())})\n', file=fos)
155+
138156
for f in example['srcs']:
139157
filename = f.relative_to(page_path.parent)
140158
print(f'\n### {filename}\n', file=fos)
@@ -152,5 +170,5 @@ def skip_license(iterator):
152170

153171
for line in skip_license(iter(f.read_text().splitlines())):
154172
print(f'{line}', file=fos)
155-
print(f'```', file=fos)
173+
print('```', file=fos)
156174

0 commit comments

Comments
 (0)