Debian Codegraph @

src/pydata_sphinx_theme/edit_this_page.py

raw
1 """Create an "edit this page" url compatible with bitbucket, gitlab and github."""
2
3 import jinja2
4
5 from sphinx.application import Sphinx
6 from sphinx.errors import ExtensionError
7
8
9 def setup_edit_url(
10 app: Sphinx, pagename: str, templatename: str, context, doctree
11 ) -> None:
12 """Add a function that jinja can access for returning the edit URL of a page."""
13
14 def get_edit_provider_and_url() -> None:
15 """Return a provider name and a URL for an "edit this page" link."""
16 file_name = f"{pagename}{context['page_source_suffix']}"
17
18 # Make sure that doc_path has a path separator only if it exists (to avoid //)
19 doc_path = context.get("doc_path", "")
20 if doc_path and not doc_path.endswith("/"):
21 doc_path = f"{doc_path}/"
22
23 default_provider_urls = {
24 "bitbucket_url": "https://bitbucket.org",
25 "github_url": "https://github.com",
26 "gitlab_url": "https://gitlab.com",
27 }
28
29 edit_attrs = {}
30
31 # ensure custom URL is checked first, if given
32 url_template = context.get("edit_page_url_template")
33
34 if url_template is not None:
35 if "file_name" not in url_template:
36 raise ExtensionError(
37 "Missing required value for `use_edit_page_button`. "
38 "Ensure `file_name` appears in `edit_page_url_template`: "
39 f"{url_template}"
40 )
41 provider_name = context.get("edit_page_provider_name")
42 edit_attrs[("edit_page_url_template",)] = (provider_name, url_template)
43
44 edit_attrs.update(
45 {
46 ("bitbucket_user", "bitbucket_repo", "bitbucket_version"): (
47 "Bitbucket",
48 "{{ bitbucket_url }}/{{ bitbucket_user }}/{{ bitbucket_repo }}"
49 "/src/{{ bitbucket_version }}"
50 "/{{ doc_path }}{{ file_name }}?mode=edit",
51 ),
52 ("github_user", "github_repo", "github_version"): (
53 "GitHub",
54 "{{ github_url }}/{{ github_user }}/{{ github_repo }}"
55 "/edit/{{ github_version }}/{{ doc_path }}{{ file_name }}",
56 ),
57 ("gitlab_user", "gitlab_repo", "gitlab_version"): (
58 "GitLab",
59 "{{ gitlab_url }}/{{ gitlab_user }}/{{ gitlab_repo }}"
60 "/-/edit/{{ gitlab_version }}/{{ doc_path }}{{ file_name }}",
61 ),
62 }
63 )
64
65 doc_context = dict(default_provider_urls)
66 doc_context.update(context)
67 doc_context.update(doc_path=doc_path, file_name=file_name)
68
69 for attrs, (provider, url_template) in edit_attrs.items():
70 if all(doc_context.get(attr) not in [None, "None"] for attr in attrs):
71 return provider, jinja2.Template(url_template).render(**doc_context)
72
73 raise ExtensionError(
74 "Missing required value for `use_edit_page_button`. "
75 "Ensure one set of the following in your `html_context` "
76 f"configuration: {sorted(edit_attrs.keys())}"
77 )
78
79 context["get_edit_provider_and_url"] = get_edit_provider_and_url
80
81 # Ensure that the max TOC level is an integer
82 context["theme_show_toc_level"] = int(context.get("theme_show_toc_level", 1))