Skip to content

Commit

Permalink
fix: push from gh issue
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey committed Sep 6, 2024
1 parent 02ea9ed commit 0bade06
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 25 deletions.
3 changes: 1 addition & 2 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ runs:
- name: Commit and publish documentation changes to gh-pages branch
if: ${{ github.event_name }} != "pull_request"
run: |
# --skip-push assembles the build w/o pushing; for CI/CD.
sphinx-ape publish . ${{ github.repository }} --skip-push
sphinx-ape publish . --skip-push
git config --local user.email "[email protected]"
git config --local user.name "GitHub Action"
git add .
Expand Down
6 changes: 3 additions & 3 deletions sphinx_ape/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,19 +131,19 @@ def test(base_path):

@cli.command()
@click.argument("base_path", type=Path)
@click.argument("repository")
@click.option("--repo", "--repository", help="Specify the repository ID")
@click.option(
"--skip-push",
is_flag=True,
hidden=True,
)
def publish(base_path, repository, cicd, skip_push):
def publish(base_path, repository, skip_push):
"""
Publish docs
"""
builder = _create_builder(base_path=base_path)
try:
builder.publish(repository, cicd=cicd, push=not skip_push)
builder.publish(repository=repository, push=not skip_push)
except ApeDocsPublishError as err:
click.echo(f"ERROR: {err}", err=True)
sys.exit(1)
Expand Down
62 changes: 57 additions & 5 deletions sphinx_ape/_utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import ast
import os
import re
import shutil
import subprocess
from pathlib import Path
from typing import Optional, Union
from typing import Any, Optional, Union

import tomli

Expand Down Expand Up @@ -37,10 +37,62 @@ def sphinx_build(dst_path: Path, source_dir: Union[Path, str]) -> Path:
return path


def get_source_url(directory: Optional[Path] = None) -> str:
if env_var := os.getenv("GITHUB_REPO"):
return f"https://github.com/{env_var}"

return extract_source_url(directory=directory)


def extract_source_url(directory: Optional[Path] = None) -> str:
directory = directory or Path.cwd()
url = None
if (directory / "setup.py").is_file():
url = _extract_github_url_from_setup_py(directory / "setup.py")
if url is None:
raise ApeDocsBuildError("No package source URL found.")

return url


def _extract_github_url_from_setup_py(file_path: Path) -> Optional[str]:
# Check `project_urls`
project_urls: dict = _extract_key_from_setup_py("project_urls", file_path) or {} # type: ignore
if url := project_urls.get("Source"):
return url

# Try url
url = _extract_key_from_setup_py("url", file_path)
if url and url.startswith("https://github.com"):
return url

return None


def _extract_name_from_setup_py(file_path: Path) -> Optional[str]:
content = file_path.read_text()
if match := re.search(r"name\s*=\s*['\"](.+?)['\"]", content):
return match.group(1)
return _extract_key_from_setup_py("name", file_path)


def _extract_key_from_setup_py(key: str, file_path: Path) -> Optional[Any]:
if not (setup_content := file_path.read_text()):
return None
elif not (parsed_content := ast.parse(setup_content)):
return None

# Walk through the AST to find the setup() call and extract the desired information
for node in ast.walk(parsed_content):
if (
not isinstance(node, ast.Call)
or not hasattr(node.func, "id")
or node.func.id != "setup"
):
continue

for keyword in node.keywords:
if keyword.arg != key:
continue

return ast.literal_eval(keyword.value)

return None

Expand Down
18 changes: 10 additions & 8 deletions sphinx_ape/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import Optional, Union

from sphinx_ape._base import Documentation
from sphinx_ape._utils import git, replace_tree, sphinx_build
from sphinx_ape._utils import extract_source_url, git, replace_tree, sphinx_build
from sphinx_ape.exceptions import ApeDocsBuildError, ApeDocsPublishError

REDIRECT_HTML = """
Expand Down Expand Up @@ -97,29 +97,31 @@ def build(self):

self._setup_redirect()

def publish(self, repository: str, push: bool = True):
def publish(self, repository: Optional[str] = None, push: bool = True):
"""
Publish the documentation to GitHub pages.
Meant to be run in CI/CD on releases.
Args:
repository (str): The repository name.
repository (Optional[str]]): The repository name. Defaults to GitHub env-var
or extraction from setup file.
push (bool): Set to ``False`` to skip git add, commit, and push.
Raises:
:class:`~sphinx_ape.exceptions.ApeDocsPublishError`: When
publishing fails.
"""
try:
self._publish(repository)
self._publish(repository=repository, push=push)
except Exception as err:
raise ApeDocsPublishError(str(err)) from err

def _publish(self, repository: str, push: bool = True):
if not repository:
raise ApeDocsPublishError("Missing 'repository' argument.")
def _publish(self, repository: Optional[str] = None, push: bool = True):
if repository:
repo_url = f"https://github.com/{repository}"
else:
repo_url = extract_source_url()

repo_url = f"https://github.com/{repository}"
gh_pages_path = Path.cwd() / "gh-pages"
git(
"clone",
Expand Down
52 changes: 45 additions & 7 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
from sphinx_ape._utils import extract_package_name
from pathlib import Path

import pytest

def test_extract_package_name_setup_py(temp_path):
setup_py = temp_path / "setup.py"
name = "ape-myplugin"
content = f"""
from sphinx_ape._utils import extract_package_name, extract_source_url


@pytest.fixture(scope="session")
def create_setup_py():
def fn(
base_path: Path, name: str = "ape-myplugin", url: bool = False, source_url: bool = False
):
content = f"""
#!/usr/bin/env python
from setuptools import find_packages, setup
Expand All @@ -19,9 +25,41 @@ def test_extract_package_name_setup_py(temp_path):
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 3.12",
],
)
"""
setup_py.write_text(content)
if url:
content = f'{content}\n url="https://github.com/ApeWorX/{name}",'
if source_url:
content = (
f"{content} project_urls={{\n "
f'"Source": "https://github.com/ApeWorX/{name}",\n }},'
)

content = f"{content}\n)"
path = base_path / "setup.py"
path.write_text(content)
return path

return fn


def test_extract_package_name_setup_py(temp_path, create_setup_py):
name = "ape-myplugin"
create_setup_py(temp_path, name)
actual = extract_package_name(temp_path)
assert actual == name


def test_extract_source_url_from_setup_py_project_urls_source(temp_path, create_setup_py):
name = "ape-myplugin"
create_setup_py(temp_path, name, source_url=True)
actual = extract_source_url(temp_path)
expected = f"https://github.com/ApeWorX/{name}"
assert actual == expected


def test_extract_source_url_from_setup_py_url(temp_path, create_setup_py):
name = "ape-myplugin"
create_setup_py(temp_path, name, url=True)
actual = extract_source_url(temp_path)
expected = f"https://github.com/ApeWorX/{name}"
assert actual == expected

0 comments on commit 0bade06

Please sign in to comment.