|
18 | 18 |
|
19 | 19 | import datetime
|
20 | 20 | import doctest
|
| 21 | +import importlib |
| 22 | +import inspect |
| 23 | +import os |
| 24 | +import re |
| 25 | +from pathlib import Path |
| 26 | + |
21 | 27 |
|
22 | 28 | project = "Qiskit"
|
23 | 29 | project_copyright = f"2017-{datetime.date.today().year}, Qiskit Development Team"
|
|
39 | 45 | "sphinx.ext.intersphinx",
|
40 | 46 | "sphinx.ext.doctest",
|
41 | 47 | # This is used by qiskit/documentation to generate links to github.com.
|
42 |
| - "sphinx.ext.viewcode", |
| 48 | + "sphinx.ext.linkcode", |
43 | 49 | "matplotlib.sphinxext.plot_directive",
|
44 | 50 | "reno.sphinxext",
|
45 | 51 | "sphinxcontrib.katex",
|
|
155 | 161 | # ----------------------------------------------------------------------------------
|
156 | 162 |
|
157 | 163 | plot_html_show_formats = False
|
| 164 | + |
| 165 | + |
| 166 | +# ---------------------------------------------------------------------------------- |
| 167 | +# Source code links |
| 168 | +# ---------------------------------------------------------------------------------- |
| 169 | + |
| 170 | +REPO_ROOT = Path(__file__).resolve().parents[1] |
| 171 | + |
| 172 | + |
| 173 | +def linkcode_resolve(domain, info): |
| 174 | + if domain != "py": |
| 175 | + return None |
| 176 | + |
| 177 | + module_name = info["module"] |
| 178 | + if "qiskit" not in module_name: |
| 179 | + return None |
| 180 | + |
| 181 | + try: |
| 182 | + module = importlib.import_module(module_name) |
| 183 | + except ModuleNotFoundError: |
| 184 | + return None |
| 185 | + |
| 186 | + obj = module |
| 187 | + for part in info["fullname"].split("."): |
| 188 | + try: |
| 189 | + obj = getattr(obj, part) |
| 190 | + except AttributeError: |
| 191 | + return None |
| 192 | + |
| 193 | + try: |
| 194 | + full_file_name = inspect.getsourcefile(obj) |
| 195 | + except TypeError: |
| 196 | + return None |
| 197 | + if full_file_name is None: |
| 198 | + return None |
| 199 | + try: |
| 200 | + relative_file_name = Path(full_file_name).resolve().relative_to(REPO_ROOT) |
| 201 | + file_name = re.sub(r"\.tox\/.+\/site-packages\/", "", str(relative_file_name)) |
| 202 | + except ValueError: |
| 203 | + return None |
| 204 | + |
| 205 | + try: |
| 206 | + source, lineno = inspect.getsourcelines(obj) |
| 207 | + except (OSError, TypeError): |
| 208 | + linespec = "" |
| 209 | + else: |
| 210 | + ending_lineno = lineno + len(source) - 1 |
| 211 | + linespec = f"#L{lineno}-L{ending_lineno}" |
| 212 | + |
| 213 | + github_branch = os.environ.get("QISKIT_DOCS_GITHUB_BRANCH_NAME", "main") |
| 214 | + return f"https://github.com/Qiskit/qiskit/tree/{github_branch}/{file_name}{linespec}" |
0 commit comments