Debian Codegraph @

docs/macros.py

raw symbols SCIP
1 """Macro definitions for documentation."""
2
3 # Use built-in 'list' type when upgrading to Python 3.9.
4
5 import glob
6 import os
7 import re
8 import textwrap
9 from io import TextIOWrapper
10 from typing import List
11 from urllib.parse import ParseResult, urlparse
12
13 from mkdocs_macros.plugin import MacrosPlugin
14
15
16 def define_env(env: MacrosPlugin):
17 """
18 Define the mkdocs-macros-plugin environment.
19
20 This function is called on setup. 'env' can be interacted with
21 for defining variables, macros and filters.
22
23 - variables: the dictionary that contains the environment variables
24 - macro: a decorator function, to declare a macro.
25 - filter: a function with one or more arguments, used to perform a
26 transformation
27 """
28 # Values can be overridden in mkdocs.yml:extras.
29 go_examples_path: str = env.variables.get(
30 "go_examples_path", "examples/**/*.go"
31 )
32 godoc_url: ParseResult = urlparse(
33 env.variables.get(
34 "godoc_url", "https://pkg.go.dev/github.com/cilium/ebpf"
35 )
36 )
37
38 c_examples_path: str = env.variables.get("c_examples_path", "examples/**/*.c")
39
40 @env.macro
41 def godoc(sym: str, short: bool = False):
42 """
43 Generate a godoc link based on the configured godoc_url.
44
45 `sym` is the symbol to link to. A dot '.' separator means it's a method
46 on another type. Forward slashes '/' can be used to navigate to symbols
47 in subpackages.
48
49 For example:
50 - CollectionSpec.LoadAndAssign
51 - link/Link
52 - btf/Spec.TypeByID
53
54 `short` renders only the symbol name.
55 """
56 if len(godoc_url) == 0:
57 raise ValueError("Empty godoc url")
58
59 # Support referring to symbols in subpackages.
60 subpkg = os.path.dirname(sym)
61 # Symbol name including dots for struct methods. (e.g. Map.Get)
62 name = os.path.basename(sym)
63
64 # Python's urljoin() expects the base path to have a trailing slash for
65 # it to correctly append subdirs. Use urlparse instead, and interact
66 # with the URL's components individually.
67 url = godoc_url._replace(
68 path=os.path.join(godoc_url.path, subpkg),
69 # Anchor token appearing after the # in the URL.
70 fragment=name,
71 ).geturl()
72
73 text = name
74 if short:
75 text = text.split(".")[-1]
76
77 return f"[:fontawesome-brands-golang: `{text}`]({url})"
78
79 @env.macro
80 def go_example(*args, **kwargs):
81 """
82 Include the body of a Go code example.
83
84 See docstring of code_example() for details.
85 """
86 return code_example(
87 *args, **kwargs, language="go", path=go_examples_path
88 )
89
90 @env.macro
91 def c_example(*args, **kwargs):
92 """
93 Include the body of a C code example.
94
95 See docstring of `code_example` for details.
96 """
97 return code_example(
98 *args, **kwargs, language="c", path=c_examples_path
99 )
100
101 @env.macro
102 def linux_version(version: str, why: str = ''):
103 """
104 Render a badge with the Linux logo and a version number denoting the
105 minimum kernel version needed to use a feature. Optional string to
106 explain why the feature won't work on older versions.
107 """
108 return ('<span class="md-badge md-badge--right">'
109 # TODO: Make the icon link to some docs about handling kernel
110 # versions, once those are written.
111 '<span class="md-badge__icon">:simple-linux:</span>'
112 f'<span class="md-badge__text">[{version}](# "{why}")</span>'
113 '</span>')
114
115 def code_example(
116 symbol: str,
117 title: str = None,
118 language: str = "",
119 lines: bool = True,
120 signature: bool = False,
121 path: str = "",
122 ) -> str:
123 """
124 Include the body of a code example.
125
126 `symbol` takes the name of the function or snippet to include.
127 `title` is rendered as a title at the top of the snippet.
128 `language` is the name of the programming language passed to pygments.
129 `lines` controls rendering line numbers.
130 `signature` controls whether or not the function signature and brackets are
131 included.
132 `path` specifies the include path that may contain globs.
133 """
134 opts: List[str] = []
135 if lines:
136 opts.append("linenums='1'")
137 if title:
138 opts.append(f"title='{title}'")
139
140 if signature:
141 body = full_body(path, symbol)
142 else:
143 body = inner_body(path, symbol)
144
145 out = f"``` {language} {' '. join(opts)}\n{body}```"
146
147 return out
148
149
150 def inner_body(path: str, sym: str) -> str:
151 """
152 Get the inner body of sym, using default delimiters.
153
154 First and last lines (so, function signature and closing bracket) are
155 stripped, the remaining body dedented.
156 """
157 out = _search_body(path, sym)
158 if len(out) < 2:
159 raise ValueError(
160 f"Need at least two lines to get inner body for symbol {sym}"
161 )
162
163 return textwrap.dedent("".join(out[1:-1]))
164
165
166 def full_body(path: str, sym: str) -> str:
167 """Get the full body of sym, using default delimiters, dedented."""
168 out = _search_body(path, sym)
169
170 return textwrap.dedent("".join(out))
171
172
173 def _get_body(
174 f: TextIOWrapper, sym: str, start: str = "{", end: str = "}"
175 ) -> List[str]:
176 """
177 Extract a body of text between sym and start/end delimiters.
178
179 Tailored to finding function bodies of C-family programming languages with
180 curly braces.
181
182 The starting line of the body must contain sym prefixed by a space, with
183 'start' appearing on the same line, for example " Foo() {". Further
184 occurrences of "{" and its closing counterpart "}" are tracked, and the
185 lines between and including the final "}" are returned.
186 """
187 found = False
188 stack = 0
189 lines = []
190
191 for line in f.readlines():
192 if not found:
193 # Skip current line if we're not in a body and the current line
194 # doesn't contain the given symbol.
195 #
196 # The symbol must be surrounded by non-word characters like spaces
197 # or parentheses. For example, a line "// DocObjs {" or "func
198 # DocLoader() {" should match.
199 if re.search(rf"\W{sym}\W", line) is None:
200 continue
201
202 found = True
203
204 # Count the amount of start delimiters.
205 stack += line.count(start)
206
207 if stack == 0:
208 # No opening delimiter found, ignore the line.
209 found = False
210 continue
211
212 lines.append(line)
213
214 # Count the amount of end delimiters and stop if we've escaped the
215 # current scope.
216 stack -= line.count(end)
217 if stack <= 0:
218 break
219
220 # Rewind the file for reuse.
221 f.seek(0)
222
223 if stack > 0:
224 raise LookupError(f"No end delimiter for {sym}")
225
226 if len(lines) == 0:
227 raise LookupError(f"Symbol {sym} not found")
228
229 return lines
230
231
232 def _search_body(path: str, sym: str) -> List[str]:
233 """Find the body of the given symbol in a path glob."""
234 files = glob.glob(path, recursive=True)
235 if len(files) == 0:
236 raise LookupError(f"Path {path} did not match any files")
237
238 for file in files:
239 with open(file, mode="r") as f:
240 try:
241 return _get_body(f, sym)
242 except LookupError:
243 continue
244
245 raise LookupError(f"Symbol {sym} not found in any of {files}")