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

Add black formatter #17

Merged
merged 2 commits into from
Jul 22, 2020
Merged
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
12 changes: 12 additions & 0 deletions .github/workflows/workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ on:
tags:
- '*'
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Black
run: |
pip install black
black --check --diff .

test-extension:
runs-on: ubuntu-latest
strategy:
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# sphinxext-opengraph
![Build](https://github.com/wpilibsuite/sphinxext-opengraph/workflows/Test%20and%20Deploy/badge.svg)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

Sphinx extension to generate OpenGraph metadata (https://ogp.me/)

Expand Down
51 changes: 28 additions & 23 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
# This will fail if something happens or if not in a git repository.
# This is intentional.
try:
ret = subprocess.run("git describe --tags --abbrev=0", stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=True, shell=True)
ret = subprocess.run(
"git describe --tags --abbrev=0",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
shell=True,
)
version = ret.stdout.decode("utf-8").strip()
except:
version = "master"

with open("README.md", 'r', encoding="utf-8") as readme:
with open("README.md", "r", encoding="utf-8") as readme:
long_description = readme.read()

setuptools.setup(
Expand All @@ -22,26 +27,26 @@
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/wpilibsuite/sphinxext-opengraph",
install_requires=['sphinx>=2.0'],
packages=['sphinxext'],
install_requires=["sphinx>=2.0"],
packages=["sphinxext"],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Environment :: Web Environment',
'Framework :: Sphinx :: Extension',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python',
'Topic :: Documentation :: Sphinx',
'Topic :: Documentation',
'Topic :: Software Development :: Documentation',
'Topic :: Text Processing',
'Topic :: Utilities',
"Development Status :: 5 - Production/Stable",
"Environment :: Plugins",
"Environment :: Web Environment",
"Framework :: Sphinx :: Extension",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python",
"Topic :: Documentation :: Sphinx",
"Topic :: Documentation",
"Topic :: Software Development :: Documentation",
"Topic :: Text Processing",
"Topic :: Utilities",
],
python_requires='>=3.6'
python_requires=">=3.6",
)
37 changes: 26 additions & 11 deletions sphinxext/opengraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@

DEFAULT_DESCRIPTION_LENGTH = 200


class HTMLTextParser(HTMLParser):
"""
Parse HTML into text
"""

def __init__(self):
super().__init__()
# All text found
Expand All @@ -22,7 +24,7 @@ def __init__(self):

def handle_starttag(self, tag, attrs) -> None:
self.level += 1

def handle_endtag(self, tag) -> None:
self.level -= 1

Expand All @@ -31,16 +33,23 @@ def handle_data(self, data) -> None:
if self.level == 0:
self.text_outside_tags += data


class OGMetadataCreatorVisitor(nodes.NodeVisitor):
"""
Finds the title and creates a description from a doctree
"""

def __init__(self, desc_len: int, known_titles: Iterable[str] = None, document: nodes.document = None):
def __init__(
self,
desc_len: int,
known_titles: Iterable[str] = None,
document: nodes.document = None,
):

# Hack to prevent requirement for the doctree to be passed in.
# It's only used by doctree.walk(...) to print debug messages.
# It's only used by doctree.walk(...) to print debug messages.
if document == None:

class document_cls:
class reporter:
@staticmethod
Expand Down Expand Up @@ -137,7 +146,9 @@ def make_tag(property: str, content: str) -> str:
return f'<meta property="{property}" content="{content}" />\n '


def get_tags(context: Dict[str, Any], doctree: nodes.document, config: Dict[str, Any]) -> str:
def get_tags(
context: Dict[str, Any], doctree: nodes.document, config: Dict[str, Any]
) -> str:

# Set length of description
try:
Expand Down Expand Up @@ -165,8 +176,7 @@ def get_tags(context: Dict[str, Any], doctree: nodes.document, config: Dict[str,
# url tag
# Get the URL of the specific page
page_url = urljoin(
config["ogp_site_url"],
context["pagename"] + context["file_suffix"]
config["ogp_site_url"], context["pagename"] + context["file_suffix"]
)
tags += make_tag("og:url", page_url)

Expand Down Expand Up @@ -194,14 +204,20 @@ def get_tags(context: Dict[str, Any], doctree: nodes.document, config: Dict[str,
tags += make_tag("og:image:alt", htp.text)

# custom tags
tags += '\n'.join(config['ogp_custom_meta_tags'])
tags += "\n".join(config["ogp_custom_meta_tags"])

return tags


def html_page_context(app: Sphinx, pagename: str, templatename: str, context: Dict[str, Any], doctree: nodes.document) -> None:
def html_page_context(
app: Sphinx,
pagename: str,
templatename: str,
context: Dict[str, Any],
doctree: nodes.document,
) -> None:
if doctree:
context['metatags'] += get_tags(context, doctree, app.config)
context["metatags"] += get_tags(context, doctree, app.config)


def setup(app: Sphinx) -> Dict[str, Any]:
Expand All @@ -213,10 +229,9 @@ def setup(app: Sphinx) -> Dict[str, Any]:
app.add_config_value("ogp_site_name", None, "html")
app.add_config_value("ogp_custom_meta_tags", [], "html")

app.connect('html-page-context', html_page_context)
app.connect("html-page-context", html_page_context)

return {
"parallel_read_safe": True,
"parallel_write_safe": True,
}

8 changes: 4 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ def meta_tags(content):

@pytest.fixture()
def og_meta_tags(content):
return [tag for tag in _meta_tags(content) if tag.get("property", "").startswith("og:")]
return [
tag for tag in _meta_tags(content) if tag.get("property", "").startswith("og:")
]


def pytest_configure(config):
config.addinivalue_line(
"markers", "sphinx"
)
config.addinivalue_line("markers", "sphinx")
10 changes: 7 additions & 3 deletions tests/test_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ def test_simple(og_meta_tags):
assert len(og_meta_tags) > 0
assert get_tag_content(og_meta_tags, "type") == "website"
assert len(description) == 200
assert description == "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at lorem ornare, fringilla massa nec, venenatis mi. Donec erat sapien, tincidunt nec rhoncus nec, scelerisque id diam. Orci vari..."
assert (
description
== "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at lorem ornare, fringilla massa nec, venenatis mi. Donec erat sapien, tincidunt nec rhoncus nec, scelerisque id diam. Orci vari..."
)


@pytest.mark.sphinx("html", testroot="simple")
Expand Down Expand Up @@ -84,7 +87,9 @@ def test_list_punctuation(og_meta_tags):
@pytest.mark.sphinx("html", testroot="nested-lists")
def test_nested_list_punctuation(og_meta_tags):
description = get_tag_content(og_meta_tags, "description")
assert description == "Item 1, Item 2- Nested Item 1, Nested Item 2., Item 3, Item 4."
assert (
description == "Item 1, Item 2- Nested Item 1, Nested Item 2., Item 3, Item 4."
)


@pytest.mark.sphinx("html", testroot="skip-comments")
Expand All @@ -95,4 +100,3 @@ def test_skip_comments(og_meta_tags):
@pytest.mark.sphinx("html", testroot="custom-tags")
def test_custom_tags(og_meta_tags):
assert get_tag_content(og_meta_tags, "ignore_canonical") == "true"

TheTripleV marked this conversation as resolved.
Show resolved Hide resolved