-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathmain.py
More file actions
278 lines (247 loc) · 10.2 KB
/
main.py
File metadata and controls
278 lines (247 loc) · 10.2 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
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import os
import pprint
import re
import urllib.request
from mkdocs.structure.pages import Page
from mkdocs.utils import meta
from typing import List
CARDS_TEMPLATE = """
<div class="card-wrapper">
<div>
<a href="%s" class="card">
<div>
<p class="title">%s</p>
<p class="description">%s</p>
</div>
</a>
</div>
</div>
"""
def define_env(env):
"""
This is the hook for defining variables, macros and filters
- variables: the dictionary that contains the environment variables
- macro: a decorator function, to declare a macro.
"""
@env.macro
def include_file(filename, start_line=0, end_line=None, glue='', remove_indent=False):
"""
Include a file,
optionally indicating start_line and end_line (start counting from 0)
optionally set a glue string to lead every string except the first one (can be used for indent)
optionally remove common leading whitespace from all lines (remove_indent=True)
The path is relative to the top directory of the documentation
project.
"""
full_filename = os.path.join(env.project_dir, filename)
with open(full_filename, 'r') as f:
lines = f.readlines()
line_range = lines[start_line:end_line]
if remove_indent:
non_empty = [l for l in line_range if l.strip()]
if non_empty:
indent = min(len(l) - len(l.lstrip()) for l in non_empty)
line_range = [l[indent:] if l.strip() else l for l in line_range]
return glue.join(line_range)
@env.macro
def cards(pages, columns=1, style="cards", force_version=False):
current_page = env.variables.page
absolute_url = current_page.abs_url
canonical = current_page.canonical_url
url_parts = re.search("//([^/]+)/([^/]+)/([^/]+)/", canonical)
(site, language, version) = url_parts.groups()
version = force_version or version
version = os.getenv("READTHEDOCS_VERSION_NAME", version)
rtd_canonical = os.getenv("READTHEDOCS_CANONICAL_URL", "")
if rtd_canonical:
rtd_domain = re.search("//([^/]+)/", rtd_canonical)
if rtd_domain:
site = rtd_domain.group(1)
if isinstance(pages, str):
pages = [pages]
variables = env.conf.get('extra', {})
var_start = env.config['j2_variable_start_string']
var_end = env.config['j2_variable_end_string']
cards = []
for page_data in pages:
if isinstance(page_data, tuple):
page, custom_title, custom_description = page_data
else:
page = page_data
custom_title = None
custom_description = None
path, hash = page.split("#") if "#" in page else (page, "")
if hash:
hash = '#' + hash
if re.search("^https://[^@/]+.ibexa.co", path):
html = True
content = urllib.request.urlopen(path).read().decode('utf-8')
elif re.search(".html$", path):
html = True
content = open("docs/%s" % path, "r").read()
page = '/'.join((
'/',
site,
language,
version,
page
))
else:
html = False
path = path.rstrip('/')
content = open("docs/%s.md" % path, "r").read()
page = '/'.join((
'/',
site,
language,
version,
path,
hash
))
if html:
match = re.search("<meta property=\"og:title\" content=\"(.*)\"", content, re.MULTILINE)
if match:
title = match.groups()[0]
else:
match = re.search("<title>(.*)</title>", content, re.MULTILINE)
if match:
title = match.groups()[0]
else:
title = ""
match = re.search("<meta property=\"og:description\" content=\"(.*)\"", content, re.MULTILINE)
if match:
description = match.groups()[0]
else:
match = re.search("<meta name=\"description\" content=\"(.*)\"", content, re.MULTILINE)
if match:
description = match.groups()[0]
else:
description = ""
href = page
title = custom_title if custom_title else title
title = title.replace("(Ibexa Documentation)", "").strip()
description = custom_description if custom_description else description
else:
match = re.search("^# (.*)", content, re.MULTILINE)
if match:
header = match.groups()[0]
else:
header = ""
default_meta = {
"title": header,
"short": "",
"description": ""
}
current_meta = {
**default_meta,
**meta.get_data(content)[1]
}
href = page
title = custom_title if custom_title else current_meta['short'] or current_meta['title']
description = custom_description if custom_description else current_meta['description'] or " "
title = resolve_variables(title, var_start, var_end, variables)
description = resolve_variables(description, var_start, var_end, variables)
cards.append(
CARDS_TEMPLATE % (
href,
title,
description
)
)
return """<div class="%s col-%s">%s</div>""" % (style, columns, "\n".join(cards))
@env.macro
def version_to_anchor(version : str = '') -> str:
return version.replace('.', '')
@env.macro
def release_notes_filters(header : str, categories : List[str]) -> str:
validate_categories(categories)
filters = "".join(
["""
<div
class="release-notes-filters__visible-item release-notes-filters__visible-item--hidden"
data-filter="filter-{category_slug}"
>
{category}
<button type="button" class="release-notes-filters__visible-item-remove"></button>
</div>
""".format(category_slug=slugify(category), category=category) for category in categories])
categories_dropdown = "".join(
["""
<div class="release-notes-filters__item">
<input type="checkbox" id="filter-{category_slug}" />
<label for="filter-{category_slug}">{category}</label>
</div>
""".format(category_slug=slugify(category), category=category) for category in categories]
)
return """
<div class="release-notes-header">
<h1>{header}</h1>
<div class="release-notes-filters">
<div class="release-notes-filters__visible-items">
{visible_filters}
</div>
<div class="release-notes-filters__widget">
<button type="button" class="release-notes-filters__btn">
<span class="release-notes-filters__btn-icon">
<svg width="16" height="16"><use xlink:href="../../images/icons.svg#filters" /></svg>
</span>
Filters
</button>
<div class="release-notes-filters__items">
{categories_dropdown}
</div>
</div>
</div>
</div>
""".format(header=header, visible_filters=filters, categories_dropdown=categories_dropdown)
@env.macro
def release_note_entry_begin(header : str, date: str, categories : List[str]) -> str:
validate_categories(categories)
category_badges = "".join(
[
"""
<div class="pill pill--{category_slug}" data-filter="{category_slug}"></div>
""".format(category_slug=slugify(category), category=category)
for category in categories
]
)
return """
<div class="release-note" markdown="1">
## {header}
<div class="release-note__tags">
{category_badges}
</div>
<div class="release-note__date">{date}</div>
""".format(header=header, date=date, category_badges=category_badges)
@env.macro
def release_note_entry_end() -> str:
return "</div>"
def resolve_variables(text, var_start, var_end, variables):
"""Replace variable references (e.g. [[= var =]]) with variables."""
pattern = re.escape(var_start) + r'\s*([\w.]+)\s*' + re.escape(var_end)
def replacer(match):
key = match.group(1).strip()
if key not in variables:
raise KeyError("Undefined variable '%s' used in cards macro" % key)
return str(variables[key])
return re.sub(pattern, replacer, text)
def slugify(text: str) -> str:
return text.lower().replace(' ', '-')
def validate_categories(categories: List[str]) -> None:
available_categories = ['Headless', 'Experience', 'Commerce', 'LTS Update', 'New feature', 'First release']
for category in categories:
if category not in available_categories:
raise ValueError(
"Unknown category: {category}. Available categories are: {available_categories}".format(category=category, available_categories=" ".join(available_categories))
)
def on_pre_page_macros(env):
"""
Resolve variable references in the page's description front matter field
so that they are substituted before MkDocs renders the <meta> tag.
"""
page = env._page
if page.meta and 'description' in page.meta:
page.meta['description'] = env.render(
markdown=page.meta['description'],
force_rendering=True
)