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

chore: Use ruff for linting and formatting #242

Merged
merged 5 commits into from
Apr 5, 2024
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
20 changes: 11 additions & 9 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
name: Semantic Tests
on:
push:
branches:
- '*'
- '!release-please*'
pull_request:
branches:
- '*'
- '!release-please*'
workflow_dispatch:

jobs:
Expand Down Expand Up @@ -97,7 +91,6 @@ jobs:
- run: tox -e no_erdantic

test-development-versions-deps:
environment: Tests
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
Expand All @@ -110,8 +103,7 @@ jobs:
continue-on-error: true
- run: echo "Done"

test-linter:
environment: Tests
linter:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
Expand All @@ -120,3 +112,13 @@ jobs:
python-version: '3.x'
- run: pip install tox
- run: tox -e linter

formatter:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.x'
- run: pip install tox
- run: tox -e formatter
41 changes: 18 additions & 23 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@

path = Path(__file__)
path_autodoc_pydantic = path.parents[2]
path_examples = path.parents[2].joinpath("tests",
"roots",
"test-base")
path_examples = path.parents[2].joinpath('tests', 'roots', 'test-base')

sys.path.insert(0, str(path.parent))
sys.path.insert(0, str(path_examples))
Expand All @@ -31,25 +29,25 @@
author = 'Franz Wöllert'

# The full version, including alpha/beta/rc tags
release = '2.1.0' # x-release-please-version
release = '2.1.0' # x-release-please-version

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx_rtd_theme",
"sphinx.ext.napoleon",
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.graphviz",
"sphinx_tabs.tabs",
"sphinx_copybutton",
"sphinxcontrib.autodoc_pydantic",
"sphinxcontrib.mermaid",
"sphinx.ext.viewcode",
"extensions"
'sphinx_rtd_theme',
'sphinx.ext.napoleon',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.graphviz',
'sphinx_tabs.tabs',
'sphinx_copybutton',
'sphinxcontrib.autodoc_pydantic',
'sphinxcontrib.mermaid',
'sphinx.ext.viewcode',
'extensions',
]

autosummary_generate = True
Expand All @@ -67,12 +65,9 @@
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"
html_logo = "material/logo_white.svg"
html_theme_options = {
'logo_only': True,
'display_version': True
}
html_theme = 'sphinx_rtd_theme'
html_logo = 'material/logo_white.svg'
html_theme_options = {'logo_only': True, 'display_version': True}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
Expand All @@ -81,8 +76,8 @@

add_module_names = False

mermaid_version = ""
html_static_path = ["_static"]
mermaid_version = ''
html_static_path = ['_static']
html_js_files = ['mermaid.min.js']
html_css_files = ['custom.css']

Expand Down
10 changes: 5 additions & 5 deletions docs/source/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
DocumenterConfigToc,
ConfigDescription,
AutoCodeBlock,
ShowVersions
ShowVersions,
)


def setup(app: Sphinx) -> None:
app.add_directive("autocodeblock", AutoCodeBlock)
app.add_directive("config_description", ConfigDescription)
app.add_directive("documenter_config_toc", DocumenterConfigToc)
app.add_directive("show_versions", ShowVersions)
app.add_directive('autocodeblock', AutoCodeBlock)
app.add_directive('config_description', ConfigDescription)
app.add_directive('documenter_config_toc', DocumenterConfigToc)
app.add_directive('show_versions', ShowVersions)
103 changes: 44 additions & 59 deletions docs/source/extensions/directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@
from sphinx.util.docutils import SphinxDirective

from docs.source.extensions.helper import generate_nodes, parse_options
from docs.source.extensions.templates import CONFIG_DESC_TAB_TPL, \
CONFIG_DESC_TPL, VERSION_TEMPLATE
from docs.source.extensions.templates import (
CONFIG_DESC_TAB_TPL,
CONFIG_DESC_TPL,
VERSION_TEMPLATE,
)


class DocumenterConfigToc(SphinxDirective):
Expand All @@ -37,38 +40,31 @@ class DocumenterConfigToc(SphinxDirective):
def run(self) -> List[Node]:
name = self.arguments[0]
startswith = f'autodoc_pydantic_{name}_'
configs = [x for x in self.env.config.values.keys()
if x.startswith(startswith)]
configs = [x for x in self.env.config.values.keys() if x.startswith(startswith)]

content = [":Options:"] + [self.create_link(x) for x in configs]
content = [':Options:'] + [self.create_link(x) for x in configs]
content = StringList(content)

return generate_nodes(self.state, content)

def sanitize(self, option: str) -> str:
"""Helper function to sanitize option name.

"""
"""Helper function to sanitize option name."""

name = self.arguments[0]
prefix = "autodoc_pydantic_"
special = {f"{name}-undoc-members",
f"{name}-members",
f"{name}-member-order"}
prefix = 'autodoc_pydantic_'
special = {f'{name}-undoc-members', f'{name}-members', f'{name}-member-order'}

replaced = option.replace(prefix, "").replace("_", "-")
replaced = option.replace(prefix, '').replace('_', '-')
if replaced in special:
replaced = replaced.replace(f"{name}-", "")
replaced = replaced.replace(f'{name}-', '')

return f":{replaced}:"
return f':{replaced}:'

def create_link(self, option: str) -> str:
"""Creates reST reference for given option to configuration section.

"""
"""Creates reST reference for given option to configuration section."""

label = self.sanitize(option)
return f" - :ref:`{label} <{option}>`"
return f' - :ref:`{label} <{option}>`'


class ConfigDescription(SphinxDirective):
Expand Down Expand Up @@ -145,31 +141,28 @@ def process_values(self) -> List[Tuple[str, str]]:

"""

values = self.options["values"].split(",")
values = self.options['values'].split(',')
stripped = [x.strip() for x in values]

if "*" not in self.options["values"]:
stripped[0] = stripped[0] + "*"
if '*' not in self.options['values']:
stripped[0] = stripped[0] + '*'

return [(x.replace("*", ""), x.replace("*", " (default)"))
for x in stripped]
return [(x.replace('*', ''), x.replace('*', ' (default)')) for x in stripped]

def process_enable(self) -> str:
"""Parse the list of additional options which need to be enabled to
properly render output.

"""

enable = self.options.get("enable", "")
enable = self.options.get('enable', '')
if enable:
enable = parse_options(enable)

return enable

def process_tabs(self):
"""Create the tab content.

"""
"""Create the tab content."""

enable = self.process_enable()

Expand All @@ -178,44 +171,40 @@ def process_tabs(self):
tab_rst = CONFIG_DESC_TAB_TPL.format(
value=value,
value_label=label,
path=self.options["path"],
directive_option=self.options["directive_option"],
path=self.options['path'],
directive_option=self.options['directive_option'],
enable=enable,
directive=self.arguments[0]
directive=self.arguments[0],
)
tabs.append(tab_rst)

return "\n".join(tabs)
return '\n'.join(tabs)

def process_title(self) -> str:
"""Generate title.

"""
"""Generate title."""

title = self.options["title"]
return title + "\n" + ("-" * len(title))
title = self.options['title']
return title + '\n' + ('-' * len(title))

def run(self) -> List[Node]:
"""Generate reST.

"""
"""Generate reST."""

tabs = self.process_tabs()
title = self.process_title()
version = self.options.get("version") or "0.1.0"
path = self.options.get("example_path") or self.options["path"]
version = self.options.get('version') or '0.1.0'
path = self.options.get('example_path') or self.options['path']

content = CONFIG_DESC_TPL.format(
title=title,
description="\n".join(self.content),
description='\n'.join(self.content),
tabs=tabs,
example_path=path,
confpy=self.options["confpy"],
directive_option=self.options["directive_option"],
version=version
confpy=self.options['confpy'],
directive_option=self.options['directive_option'],
version=version,
)

content = StringList(content.split("\n"))
content = StringList(content.split('\n'))
return generate_nodes(self.state, content)


Expand All @@ -229,7 +218,7 @@ class AutoCodeBlock(CodeBlock):
required_arguments = 1

option_spec = CodeBlock.option_spec.copy()
option_spec.update({"language": directives.unchanged})
option_spec.update({'language': directives.unchanged})

def run(self) -> List[Node]:
"""Modify content and argument to make it work with parent class without
Expand All @@ -238,7 +227,7 @@ def run(self) -> List[Node]:
"""

self.content = self.get_source_code(self.arguments[0])
self.arguments[0] = self.options.get("language") or "python"
self.arguments[0] = self.options.get('language') or 'python'

return super().run()

Expand All @@ -252,33 +241,29 @@ def get_source_code(self, objpath: str) -> List[str]:

obj = pydoc.locate(objpath)
lines = inspect.getsourcelines(obj)[0]
return [line.replace("\n", "") for line in lines]
return [line.replace('\n', '') for line in lines]


class ShowVersions(SphinxDirective):
"""Generates documentation section describing configuration parameters.

"""
"""Generates documentation section describing configuration parameters."""

has_content = False
required_arguments = 0
optional_arguments = 0

def run(self) -> List[Node]:
"""Generate reST.

"""
"""Generate reST."""

mermaid = self.env.app.extensions["sphinxcontrib.mermaid"].version
mermaid = self.env.app.extensions['sphinxcontrib.mermaid'].version

content = VERSION_TEMPLATE.format(
sphinx=sphinx.__version__,
pydantic=pydantic.version.VERSION,
sphinx_rtd_theme=sphinx_rtd_theme.__version__,
sphinx_tabs=sphinx_tabs.__version__,
sphinx_copybutton=sphinx_copybutton.__version__,
sphinxcontrib_mermaid=mermaid
sphinxcontrib_mermaid=mermaid,
)

content = StringList(content.split("\n"))
content = StringList(content.split('\n'))
return generate_nodes(self.state, content)
Loading
Loading