Skip to content

Commit

Permalink
Better fix for package name issues
Browse files Browse the repository at this point in the history
Add ```get_top_level()``` function to retrieve the top level package name using either
* conf.py value of ```top_level```
* The grandparent directory of the docs source directory
* The ```html_context["github_repo"]``` value

If it can't find it after all that, then..... 🙂
  • Loading branch information
TDKorn committed Feb 25, 2023
1 parent 871c30c commit 048e5ec
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 22 deletions.
10 changes: 6 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -137,21 +137,23 @@ Add the extension to your ``conf.py``
...

Configuration Variables
=========================
Optional Configuration Variables
===================================

Add any of the following configuration variables to your ``conf.py``

``pkg_name``
``top_level``
^^^^^^^^^^^^^^^^^^^

.. code-block:: python
pkg_name: str
top_level: str
The name of the top-level package. For this repo, it would be ``sphinx_github_style``

...

``linkcode_blob``
^^^^^^^^^^^^^^^^^^^

Expand Down
9 changes: 5 additions & 4 deletions README_PyPi.rst
Original file line number Diff line number Diff line change
Expand Up @@ -127,21 +127,22 @@ Add the extension to your ``conf.py``
...

Configuration Variables
=========================
Optional Configuration Variables
===================================

Add any of the following configuration variables to your ``conf.py``

``pkg_name``
``top_level``
^^^^^^^^^^^^^^^^^^^

.. code-block:: python
pkg_name: str
top_level: str
The name of the top-level package. For this repo, it would be ``sphinx_github_style``

...

``linkcode_blob``
^^^^^^^^^^^^^^^^^^^
Expand Down
11 changes: 5 additions & 6 deletions docs/source/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -110,23 +110,22 @@ Add the extension to your ``conf.py``
"sphinx_github_style",
]
...

Configuration Variables
=========================
Optional Configuration Variables
===================================

Add any of the following configuration variables to your ``conf.py``

``pkg_name``
``top_level``
^^^^^^^^^^^^^^^^^^^

.. code-block:: python
pkg_name: str
top_level: str
The name of the top-level package. For this repo, it would be ``sphinx_github_style``

...

``linkcode_blob``
^^^^^^^^^^^^^^^^^^^
Expand Down
44 changes: 41 additions & 3 deletions sphinx_github_style/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
import sphinx
import inspect
import subprocess
import pkg_resources
from pathlib import Path
from sphinx.application import Sphinx
from sphinx.errors import ExtensionError
from typing import Dict, Any, Optional, Callable


__version__ = "1.0.1b0"
__version__ = "1.0.1b3"
__author__ = 'Adam Korn <hello@dailykitten.net>'


from .add_linkcode_class import add_linkcode_node_class
from .meth_lexer import TDKMethLexer
from .github_style import TDKStyle
Expand All @@ -21,7 +23,7 @@ def setup(app: Sphinx) -> Dict[str, Any]:
app.connect("builder-inited", add_static_path)

app.add_config_value('linkcode_blob', 'head', True)
app.add_config_value('pkg_name', None, '')
app.add_config_value('top_level', get_top_level(app), '')

app.setup_extension('sphinx_github_style.add_linkcode_class')
app.setup_extension('sphinx_github_style.github_style')
Expand Down Expand Up @@ -130,7 +132,7 @@ def get_linkcode_url(app: Sphinx) -> str:
"sphinx-github-style: config value ``linkcode_url`` is missing. "
"Creating link from ``html_context`` values..."
)
blob = context['github_version'] # Added by setup() above
blob = context['github_version'] # Added by setup() above
url = f"https://github.com/{context['github_user']}/{context['github_repo']}/{blob}/"

else:
Expand All @@ -146,6 +148,7 @@ def get_linkcode_resolve(linkcode_url: str) -> Callable:
Used by default if ``linkcode_resolve`` isn't defined in ``conf.py``
"""

def linkcode_resolve(domain, info):
"""Returns a link to the source code on GitHub, with appropriate lines highlighted
Expand Down Expand Up @@ -204,6 +207,41 @@ def linkcode_resolve(domain, info):
return linkcode_resolve


def get_top_level(app: Sphinx):
# Retrieve conf.py value
top_level = get_conf_val(app, "top_level")

if top_level is None:
# If not defined, try retrieving with pkg_resources
project_dir = Path(app.srcdir).parent.parent
project_name = os.path.basename(project_dir)
pkg = None

try:
pkg = pkg_resources.require(project_name)[0]

except pkg_resources.DistributionNotFound:
# Try `html_context` repo name in case project structure isn't repo/docs/source
project_name = get_conf_val(app, "html_context", {}).get("github_repo")

if project_name is not None:
try:
pkg = pkg_resources.require(project_name)[0]

except pkg_resources.DistributionNotFound:
pass

finally:
if pkg is None:
raise ExtensionError(
"sphinx_github_style: Unable to determine top-level package")

top_level = pkg.get_metadata('top_level.txt').strip()
app.config._raw_config['top_level'] = top_level

return top_level


def get_conf_val(app: Sphinx, attr: str, default: Any = None) -> Any:
"""Retrieve values from ``conf.py``
Expand Down
7 changes: 2 additions & 5 deletions sphinx_github_style/meth_lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from sphinx.application import Sphinx
from pygments.lexers.python import NumPyLexer
from inspect import getmembers, isfunction, ismethod, ismodule, isclass
from sphinx.errors import ExtensionError


def get_pkg_funcs(pkg: types.ModuleType):
Expand Down Expand Up @@ -44,7 +43,5 @@ def get_pkg_lexer(cls, pkg_name: str) -> Type["TDKMethLexer"]:


def setup(app: Sphinx):
pkg_name = app.config._raw_config.get("pkg_name", getattr(app.config, "pkg_name"))
if pkg_name is None:
raise ExtensionError("`pkg_name` is missing from conf.py")
app.add_lexer('python', TDKMethLexer.get_pkg_lexer(pkg_name))
top_level = app.config._raw_config['top_level'] # Set by __init__.setup()
app.add_lexer('python', TDKMethLexer.get_pkg_lexer(top_level))

0 comments on commit 048e5ec

Please sign in to comment.