Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bumping module to the newest version #403

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 5 additions & 54 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,6 @@ jobs:
matrix:
os:
- "ubuntu-latest"
- "windows-latest"
- "macos-latest"
python-version:
- "3.x"
node-version:
Expand Down Expand Up @@ -142,8 +140,6 @@ jobs:
matrix:
os:
- "ubuntu-latest"
- "windows-latest"
- "macos-latest"
python-version:
- "3.9"
- "3.10"
Expand Down Expand Up @@ -218,63 +214,18 @@ jobs:
fail_ci_if_error: true # optional (default = false)
verbose: true # optional (default = false)

compare-wheels:
runs-on: ubuntu-latest
needs: [build]
steps:
- name: Download Linux package
uses: actions/download-artifact@v4
with:
name: python-packages-Linux
path: dist-Linux
- name: Download macOS package
uses: actions/download-artifact@v4
with:
name: python-packages-macOS
path: dist-macOS
- name: Download Windows package
uses: actions/download-artifact@v4
with:
name: python-packages-Windows
path: dist-Windows
- name: Unzip wheels
run: |
for os in Linux Windows macOS; do
unzip -d pkg-$os dist-$os/*.whl
done
- name: Compare macOS wheel to Linux wheel
run: diff -ur --color=always pkg-Linux pkg-macOS
- name: Compare Windows wheel to Linux wheel
run: diff -ur --color=always pkg-Windows pkg-Windows

python-publish-package:
# Only publish package on push to tag or default branch.
if: ${{ github.event_name == 'push' && github.repository == 'jbms/sphinx-immaterial' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') }}
if: ${{ github.event_name == 'push' && github.repository == 'antmicro/sphinx-immaterial' && (github.ref == 'refs/heads/main') }}
runs-on: ubuntu-latest
needs: [build, test]
steps:
- uses: actions/download-artifact@v4
with:
name: python-packages-Linux
path: dist
- name: Publish to PyPI (test server)
uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3
continue-on-error: true
- run: mv dist/*.whl dist/sphinx_immaterial-0.0.post1.tip-py3-none-any.whl
- uses: pyTooling/Actions/releaser@r0
with:
user: __token__
password: ${{ secrets.pypi_test_token }}
repository-url: https://test.pypi.org/legacy/
if: ${{ ! startsWith(github.ref, 'refs/tags/v') }}
- name: Publish to PyPI (main server)
uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3
with:
user: __token__
password: ${{ secrets.pypi_token }}
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
- uses: actions/checkout@v4
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
- name: Create a Github Release
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
env:
GH_TOKEN: ${{ github.token }}
run: gh release create ${{ github.ref_name }} --generate-notes
token: ${{ github.token }}
files: dist/*.whl
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,9 @@ tests/**/build/
tests/**/*.egg-info/
tests/**/*.so
tests/**/*.pyd

# fonts
sphinx_immaterial/resources/*.request
sphinx_immaterial/resources/*.response
sphinx_immaterial/resources/*.woff2
sphinx_immaterial/resources/*.ttf
26 changes: 0 additions & 26 deletions .readthedocs.yaml

This file was deleted.

1 change: 1 addition & 0 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ def check_lf(session: nox.Session):
def dist(session: nox.Session, cmd: str):
"""Create distributions."""
session.run("pip", "install", "wheel", "setuptools_scm", "setuptools>=42")
session.run("pip", "install", "-r", "requirements.txt")
github_output = os.environ.get("GITHUB_OUTPUT", None)
if cmd == "--version":
version = cast(str, session.run("python", "setup.py", "--version", silent=True))
Expand Down
13 changes: 13 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@
import setuptools.command.develop
import setuptools.command.install
import setuptools.command.sdist
from sphinx_immaterial.google_fonts import install_google_fonts

from importlib.resources import files
from sphinx_immaterial import resources

from sphinx_immaterial import DEFAULT_THEME_OPTIONS

with open("requirements.txt", encoding="utf-8") as reqs:
REQUIREMENTS = [reqs.readlines()]
Expand Down Expand Up @@ -153,6 +159,11 @@ def run(self):
target = {"min": "build", "dev": "build:dev"}

try:
install_google_fonts(
files(resources),
files(resources),
DEFAULT_THEME_OPTIONS["font"].values()
)
tgt = target[self.bundle_type]
node_modules_path = os.path.join(root_dir, "node_modules")
if self.skip_npm_reinstall and os.path.exists(node_modules_path):
Expand Down Expand Up @@ -195,6 +206,8 @@ def run(self):
"*.html",
"custom_admonitions.css",
"theme.conf",
"resources/*.response",
"resources/*/*.response",
],
"sphinx_immaterial.apidoc.cpp.cppreference_data": ["*.xml"],
},
Expand Down
2 changes: 2 additions & 0 deletions sphinx_immaterial/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"search": {},
},
"icon": {},
"pdf_url": "",
"repo_url": "",
"edit_uri": "",
"globaltoc_collapse": True,
Expand Down Expand Up @@ -245,6 +246,7 @@ def html_page_context(
"theme": theme_options,
"site_url": theme_options.get("site_url"),
"site_name": context["docstitle"],
"pdf_url": theme_options.get("pdf_url"),
"repo_url": theme_options.get("repo_url"),
"repo_name": theme_options.get("repo_name", None),
"extra": extra,
Expand Down
22 changes: 19 additions & 3 deletions sphinx_immaterial/external_resource_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
import os
import tempfile
from typing import Dict, Optional
from importlib.resources import files

import appdirs
import requests
import sphinx.application
import sphinx.config
import sphinx.util.logging

from sphinx_immaterial import resources

logger = sphinx.util.logging.getLogger(__name__)


Expand All @@ -22,19 +25,32 @@ def get_url(
req_json_encoded = json.dumps(req_json).encode("utf-8")
req_key = hashlib.sha256(req_json_encoded).hexdigest()

resp_path = os.path.join(cache_dir, f"{req_key}.response")
# First try the in-module resources
mod_res_path = files(resources) / f"{req_key}.response"
try:
with open(resp_path, "rb") as f:
with open(str(mod_res_path), "rb") as f:
return f.read()
except FileNotFoundError:
pass
print(f"Failed to load file from module: {mod_res_path}")

# Secondly, look at the cache
resp_path = os.path.join(cache_dir, f"{req_key}.response")
if cache_dir:
try:
with open(resp_path, "rb") as f:
return f.read()
except FileNotFoundError:
pass

logger.info("Fetching: %s with %r", url, headers)
r = requests.get(url, headers=headers, stream=True)
r.raise_for_status()

response_content = r.content

if not cache_dir:
return response_content

# Write request.
req_path = os.path.join(cache_dir, f"{req_key}.request")
os.makedirs(cache_dir, exist_ok=True)
Expand Down
40 changes: 30 additions & 10 deletions sphinx_immaterial/google_fonts.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,26 @@ def _adjust_css_urls(css_content: bytes, renamed_fonts: Dict[str, str]) -> str:
_TTF_FONT_PATHS_KEY = "sphinx_immaterial_ttf_font_paths"


def add_google_fonts(app: sphinx.application.Sphinx, fonts: List[str]):
cache_dir = os.path.join(get_cache_dir(app), "google_fonts")
static_dir = os.path.join(app.outdir, "_static")
max_workers: Optional[int] = cast(
int, app.config.config_values.get(_MAX_CONCURRENT_FETCHES_KEY, 128)
)
def install_google_fonts(cache_dir: str, font_dir: str, fonts: List[str]):
"""
Saves google fonts to given directory.

Firstly, it tries to load fonts from cache directory.
If it fails, it downloads fonts from remote locations.

The font files are saved to font_dir.

Parameters
----------
cache_dir : str
Directory with cached downloaded files.
If cache_dir is empty, skip checking cache
font_dir : str
Target directory where fonts are saved
fonts : List[str]
List of fonts to save
"""
max_workers = 128
if _MAX_CONCURRENT_FETCHES_ENV_KEY in os.environ:
try:
max_workers = int(os.environ[_MAX_CONCURRENT_FETCHES_ENV_KEY])
Expand All @@ -72,10 +86,7 @@ def add_google_fonts(app: sphinx.application.Sphinx, fonts: List[str]):
"Environment variable, %s, must be an integer value.",
_MAX_CONCURRENT_FETCHES_ENV_KEY,
)
if max_workers is not None and max_workers <= 0:
max_workers = None # use default from ThreadPoolExecutor
# _static path
font_dir = os.path.join(static_dir, "fonts")
os.makedirs(font_dir, exist_ok=True)

with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
Expand Down Expand Up @@ -183,7 +194,16 @@ async def do_fetch():
# issues if we're running in an environment with a loop already
# running (like within the Esbonio language server). Technically
# that'll block that loop, but it's better than causing a crash.
css_content = executor.submit(lambda: asyncio.run(do_fetch())).result()
return executor.submit(lambda: asyncio.run(do_fetch())).result()


def add_google_fonts(app: sphinx.application.Sphinx, fonts: List[str]):
cache_dir = os.path.join(get_cache_dir(app), "google_fonts")
static_dir = os.path.join(app.outdir, "_static")
# _static path
font_dir = os.path.join(static_dir, "fonts")

css_content = install_google_fonts(cache_dir, font_dir, fonts)

# Write fonts css file
ttf_font_paths = {}
Expand Down
3 changes: 3 additions & 0 deletions sphinx_immaterial/theme.conf
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ repo_name =
# source file. This is typically in the form of 'blob/<branch name>/<docs source folder>'.
edit_uri =

# Relative or absolute location of the PDF
pdf_url =

# Sitemap generation
# Specify a base_url used to generate sitemap.xml links. If not specified, then
# no sitemap will be built.
Expand Down
18 changes: 17 additions & 1 deletion src/partials/copyright.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,27 @@
<a href="{{ path }}">Copyright</a> {{ copyright }}.
{% endtrans %}
{%- else %}
{% trans copyright=copyright|e %}&#169; Copyright {{ copyright }}.
{% trans copyright=copyright|e %}Copyright &#169; {{ copyright }}.
{% endtrans %}
{%- endif %}
</div>
{% endif %}

{%- if commit %}
{%- if commit_url %}
<a href="{{ commit_url }}">{{ commit }}</a>
{%- else %}
<i>{{ commit }}</i>
{%- endif %}
{%- if build_id %}
{%- if build_url %}
@ <a href="{{ build_url }}">{{ build_id }}</a>
{%- else %}
@ <i>{{ build_id }}</i>
{%- endif %}
{%- endif %}
{%- endif %}

{%- if show_sphinx %}
{% trans sphinx_version=sphinx_version|e %}Created using
<a href="https://www.sphinx-doc.org/" target="_blank" rel="noopener">Sphinx</a>
Expand Down
15 changes: 15 additions & 0 deletions src/partials/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@
</div>
{% endif %}

<!-- Link to PDF -->
{% if config.pdf_url %}
<div class="md-header__button">
<a
href="{{ config.pdf_url }}"
title="PDF - {{ config.pdf_url }}"
>
<div class="md-icon">
{% set icon = config.theme.icon.pdf or "fontawesome/solid/file-pdf" %}
{% include ".icons/" ~ icon ~ ".svg" %}
</div>
</a>
</div>
{% endif %}

<!-- Button to open search modal -->
{% if "search" in config.plugins %}
<label class="md-header__button md-icon" for="__search">
Expand Down
Loading