Skip to content

Commit

Permalink
Update ruff and add cards
Browse files Browse the repository at this point in the history
  • Loading branch information
nabobalis committed Aug 5, 2024
1 parent 95bac35 commit 705ef9c
Show file tree
Hide file tree
Showing 8 changed files with 159 additions and 77 deletions.
13 changes: 4 additions & 9 deletions docs/test_package/animals.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class Animal:

says_str = "A {name} says {sound}"

def __init__(self, name, sound, num_legs=5):
def __init__(self, name, sound, num_legs=5) -> None:
"""
Parameters
----------
Expand All @@ -61,7 +61,7 @@ def __init__(self, name, sound, num_legs=5):
self.sound = sound
self.num_legs = num_legs

def says(self, sound=None):
def says(self, sound=None) -> None:
"""
Prints what the animals name is and what sound it makes.
Expand All @@ -87,11 +87,8 @@ def says(self, sound=None):
msg = "Silent Animals are not supported!"
raise NotImplementedError(msg)

out_sound = self.sound if sound is None else sound
print(self.says_str.format(name=self.name, sound=out_sound))


def function():
def function() -> None:
"""
Prints what the animals name is and what sound it makes.
Expand Down Expand Up @@ -132,10 +129,9 @@ def function():
----------
* `A URL. <www.sunpy.org>`__
"""
print("A SOUND")


def a_really_long_function_name_just_to_see_what_happens():
def a_really_long_function_name_just_to_see_what_happens() -> None:
"""
Prints what the animals name is and what sound it makes.
Expand Down Expand Up @@ -176,4 +172,3 @@ def a_really_long_function_name_just_to_see_what_happens():
----------
* `A URL. <www.sunpy.org>`__
"""
print("A SOUND")
8 changes: 4 additions & 4 deletions docs/test_package/timerange.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class TimeRange:
<BLANKLINE>
"""

def __init__(self, a, b=None, format=None): # NOQA: A002
def __init__(self, a, b=None, format=None) -> None: # NOQA: A002
# If a is a TimeRange object, copy attributes to new instance.
self._t1 = None
self._t2 = None
Expand Down Expand Up @@ -238,7 +238,7 @@ def __ne__(self, other):

return NotImplemented

def __repr__(self):
def __repr__(self) -> str:
"""
Returns a human-readable representation of `sunpy.time.TimeRange`.
"""
Expand Down Expand Up @@ -385,7 +385,7 @@ def previous(self):

return self

def extend(self, dt_start, dt_end):
def extend(self, dt_start, dt_end) -> None:
"""
Extend the time range forwards and backwards.
Expand All @@ -409,7 +409,7 @@ def get_dates(self):
]

@add_common_docstring(**_variables_for_parse_time_docstring())
def __contains__(self, time):
def __contains__(self, time) -> bool:
"""
Checks whether the given time lies within this range. Both limits are
inclusive (i.e., ``__contains__(t1)`` and ``__contains__(t2)`` always
Expand Down
4 changes: 2 additions & 2 deletions examples/example_template.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
=================
<Verbing> a thing
<Verbing> a thing.
=================
How to <verb> <active tense> <does something>.
Expand Down Expand Up @@ -63,7 +63,7 @@
# Comments in comment blocks remain nested in the text.


def dummy():
def dummy() -> None:
"""
Dummy function to make sure docstrings don't get rendered as text.
"""
Expand Down
4 changes: 2 additions & 2 deletions examples/section/example_template_subsection.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
============================
<Verbing> a thing subsection
<Verbing> a thing subsection.
============================
How to <verb> <active tense> <does something>.
Expand Down Expand Up @@ -65,7 +65,7 @@
# Comments in comment blocks remain nested in the text.


def dummy():
def dummy() -> None:
"""
Dummy function to make sure docstrings don't get rendered as text.
"""
Expand Down
7 changes: 2 additions & 5 deletions rebuild_all_rtd.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,9 @@
def get_active_versions(project):
r = requests.get(f"{BASE_URL}{project}/versions", headers=HEADERS, params={"active": True})
if not r.ok:
print(f"Failed to get versions for {project}: {r}")
return []
r = r.json()
if "results" not in r:
print(project)
print(r)
return []
results = r["results"]
return [res["slug"] for res in results]
Expand All @@ -35,12 +32,12 @@ def get_all_subprojects(base_project):
return [res["child"]["slug"] for res in results]


def rebuild_all_versions_for_project(project):
def rebuild_all_versions_for_project(project) -> None:
slugs = get_active_versions(project)
for slug in slugs:
r = requests.post(f"{BASE_URL}{project}/versions/{slug}/builds/", headers=HEADERS)
if r.status_code != 202:
print(f"{slug} failed to build with: {r}")
pass


if __name__ == "__main__":
Expand Down
98 changes: 44 additions & 54 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -1,74 +1,64 @@
# Allow unused variables when underscore-prefixed.
lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
target-version = "py39"
target-version = "py310"
line-length = 120
exclude=[
".git,",
extend-exclude=[
"__pycache__",
"build",
"tools/**",
]
lint.select = [
"A",
"ARG",
"ASYNC",
"B",
"BLE",
"C4",
"COM",
"DTZ",
"E",
"EM",
"ERA",
"EXE",
"F",
"FBT",
"FLY",
"G",
"I",
"ICN",
"INP",
"INT",
"ISC",
"LOG",
"NPY",
"PERF",
"PGH",
"PIE",
"PLE",
"PT",
"PTH",
"PYI",
"Q",
"RET",
"RSE",
"RUF",
"SIM",
"SLF",
"SLOT",
"T10",
"T20",
"TCH",
"TID",
"TRIO",
"TRY",
"UP",
"W",
"YTT",
"ALL",
]
lint.extend-ignore = [
"ANN001", # Missing type annotation for function argument
"ANN002", # Missing type annotation for variable
"ANN003", # Missing type annotation for keyword
"ANN201", # Missing return type annotation for public function
"ANN202", # Missing return type annotation for private function
"ANN204", # Missing return type annotation for special method
"ANN205", # Missing return type annotation for staticmethod
"ANN206", # Missing return type annotation for classmethod
"COM812", # May cause conflicts when used with the formatter
"E501", # Line too long
"ISC001", # May cause conflicts when used with the formatter
"T201", # Print statements
"D200", # One-line docstring should fit on one line
"D205", # 1 blank line required between summary line and description
"D400", # First line should end with a period
"D401", # First line should be in imperative mood
"D404", # First word of the docstring should not be "This"
"E501", # Line too long
"FIX002", # Line contains TODO, consider resolving the issue
"ISC001", # May cause conflicts when used with the formatter
"PLR2004", # Magic value used in comparison
"TD002", # Missing author in TODO
"TD003", # Missing issue link on the line following this TODO
]

[lint.per-file-ignores]
"examples/*.py" = [
"INP001", # Part of an implicit namespace package
"B018", # Not print but display
"D400", # First line should end with a period, question mark, or exclamation point
"ERA001", # Commented out code
"INP001", # Implicit namespace package
"T201", # Use print
]
"docs/conf.py" = [
"INP001", # Part of an implicit namespace package
"D100", # Missing docstring in public module
"INP001", # conf.py is part of an implicit namespace package
]
"setup.py" = [
"D100", # Missing docstring in public module
]
"test_*.py" = [
"D100", # Missing docstring in public module
"D103", # Missing docstring in public function
"N806", # in function should be lowercase
"S101", # Use of `assert` detected
]
"sunpy_soar/version.py" = [
"D100", # Missing docstring in public module
]
"sunpy_soar/conftest.py" = [
"D100", # Missing docstring in public module
]

[lint.pydocstyle]
Expand Down
7 changes: 6 additions & 1 deletion src/sunpy_sphinx_theme/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from pydata_sphinx_theme import utils
from sphinx.application import Sphinx

from .cards import Card, card, copy_asset_files, depart_card_node, visit_card_node

__all__ = ["get_html_theme_path", "ON_RTD", "PNG_ICON", "SVG_ICON"]


Expand Down Expand Up @@ -61,7 +63,7 @@ def default_navbar():
]


def update_config(app):
def update_config(app) -> None:
"""
Update config with new default values and handle deprecated keys.
"""
Expand Down Expand Up @@ -140,6 +142,9 @@ def setup(app: Sphinx):
app.add_html_theme("sunpy", theme_dir)
app.add_css_file("sunpy_style.css", priority=600)

app.add_directive("custom-card", Card)
app.add_node(card, html=(visit_card_node, depart_card_node))
app.connect("build-finished", copy_asset_files)
app.connect("builder-inited", update_config)
app.connect("html-page-context", update_html_context)

Expand Down
95 changes: 95 additions & 0 deletions src/sunpy_sphinx_theme/cards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""
This provides the card extension from the website into the theme.
"""

from pathlib import Path

from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx.util.fileutil import copy_asset

__all__ = ["Card", "visit_card_node", "depart_card_node", "copy_asset_files"]


class _card(nodes.General, nodes.Element):
pass


def visit_card_node(self, node) -> None:
title = node.get("title", "")
key = title or node["github"]
key = key.lower().replace(" ", "-")
title = f"<h4>{title}</h4>" if len(title) > 0 else ""
col_extra_class = "column-half" if title else ""
body = f"""<div class="column {col_extra_class}">
{title}
<div class="card">
<img class="dark-light" src="/_static/img/{node['img_name']}" alt="{node['name']}">
<p>{node['name']}</p>
<p><button type="button" class="btn btn-sunpy btn-sunpy1" data-bs-toggle="modal" data-bs-target="#{key}">More Info</button></p>
<div class="modal fade" id="{key}" tabindex=-1>
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title center">{node['name']}</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
"""
self.body.append(body)


def depart_card_node(self, node) -> None:
body = f"""
<p>Affiliation: <a href="{node['aff_link']}">{node['aff_name']}</a></p>
<p>GitHub: <a href="https://github.com/{node['github']}">{node['github']}</a></p>
<p>Start Date: {node['date']}</p>
</div>
</div>
</div>
</div>
</div></div>"""
self.body.append(body)


class Card(Directive):
has_content = True
required_arguments = 1
optional_arguments = 6
option_spec = { # NOQA: RUF012
"img_name": directives.unchanged,
"title": directives.unchanged,
"github": directives.unchanged,
"aff_name": directives.unchanged,
"aff_link": directives.unchanged,
"date": directives.unchanged,
"desc": directives.unchanged,
}

def run(self):
title = self.options.get("title") if "title" in self.options else ""
img_name = self.options.get("img_name") if "img_name" in self.options else "sunpy_icon.svg"
github = self.options.get("github") if "github" in self.options else ""
aff_name = self.options.get("aff_name") if "aff_name" in self.options else ""
aff_link = self.options.get("aff_link") if "aff_link" in self.options else ""
date = self.options.get("date") if "date" in self.options else ""
desc = self.options.get("desc") if "desc" in self.options else "N/A"
name = " ".join(self.arguments)
out = _card(
name=name,
img_name=img_name,
title=title,
github=github,
aff_name=aff_name,
aff_link=aff_link,
date=date,
desc=desc,
)
self.state.nested_parse(self.content, 0, out)
return [out]


def copy_asset_files(app, exc) -> None:
if exc is None: # Build succeeded
for path in (Path(__file__).parent / "static").glob("*"):
copy_asset(str(path), str(Path(app.outdir) / Path("_static")))

0 comments on commit 705ef9c

Please sign in to comment.