Skip to content

Commit

Permalink
Add docs about @wants_filename
Browse files Browse the repository at this point in the history
  • Loading branch information
domdfcoding committed Jan 28, 2021
1 parent 789d1dd commit e000500
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
28 changes: 27 additions & 1 deletion doc-source/extending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Hooks may also accept positional and/or keyword arguments, either named or with
Some hooks may require access the the global configuration dict (the ``[config]`` table in ``formate.toml``).
Hooks can request this by using the :deco:`formate.config.wants_global_config`` decorator,
Hooks can request this by using the :deco:`formate.config.wants_global_config` decorator,
which provides the configuration as the ``formate_global_config`` keyword argument:

.. code-block:: python
Expand All @@ -70,3 +70,29 @@ which provides the configuration as the ``formate_global_config`` keyword argume
indent = formate_global_config.get("indent", "\t")
return re.sub("( |\t)", indent, source)
Similarly, some hooks may want to know which filename is being reformatted.
They can request this using the :deco:`formate.config.wants_filename` decorator,
which provides the configuration as the ``formate_filename`` keyword argument:

.. code-block:: python
def lint_stubs(source: str, formate_filename: PathLike) -> str:
"""
Lint Python stub files.
:param source: The source to check.
:param formate_filename: The name of the source file, to ensure this hook only runs on type stubs.
:return: The reformatted source.
"""
if os.path.splitext(formate_filename)[1] != ".pyi":
return source
...
return reformatted_source
.. versionadded:: 0.2.0
8 changes: 4 additions & 4 deletions formate/mini_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,22 @@ def check_ast(source: str) -> str:


@wants_filename
def squish_stubs(source: str, filename: PathLike) -> str:
def squish_stubs(source: str, formate_filename: PathLike) -> str:
"""
Squash type stubs by removing unnecessary blank lines.
.. versionadded:: 2.0.0
.. versionadded:: 0.2.0
:param source: The source to check.
:param filename: The name of the source file, to ensure this hook only runs on type stubs.
:param formate_filename: The name of the source file, to ensure this hook only runs on type stubs.
:return: The reformatted source.
"""

def_re = re.compile(r"^(?:# )?(\s*)def")
deco_re = re.compile(r"^(?:# )?(\s*)@")

filename = PathPlus(filename)
filename = PathPlus(formate_filename)

if filename.suffix != ".pyi":
return source
Expand Down

0 comments on commit e000500

Please sign in to comment.