Skip to content

Commit

Permalink
Merge pull request #757 from fractal-analytics-platform/751-update-pr…
Browse files Browse the repository at this point in the history
…e-commit-hooks-versions

751 update pre commit hooks versions
  • Loading branch information
tcompa authored Dec 3, 2024
2 parents 363c6d6 + d63142b commit 560125e
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 70 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/precommit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: precommit

on:
push:
branches: ["main"]
pull_request:
branches: ["main"]

jobs:
precommit:
runs-on: ubuntu-22.04
timeout-minutes: 3
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.10"
cache: "pip"
- uses: pre-commit/[email protected]
28 changes: 18 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
rev: v5.0.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/asottile/reorder_python_imports
rev: v3.1.0
hooks:
- id: reorder-python-imports
- id: reorder-python-imports
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
args: [--line-length=79]
- id: black
args: [--line-length=79]
- repo: https://github.com/PyCQA/flake8
rev: 3.9.2
rev: 7.1.1
hooks:
- id: flake8
- id: flake8
args: ["--exclude", "examples/*"]
- repo: https://github.com/PyCQA/bandit
rev: '1.7.4'
hooks:
- id: bandit
args: ["-x", "tests/*"]
args: ["--exclude", "tests/*"]
- repo: local
hooks:
- id: grep-for-devtools
name: Check for devtools in fractal_client files
entry: bash -c 'for file in "$@"; do if grep -n "devtools" "$file"; then echo "$file" && exit 1; fi; done' --
language: system
files: fractal_client/
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
**Note**: Numbers like (\#123) point to closed Pull Requests on the fractal repository.

# Unreleased

* Update versions of pre-commit hooks and add precommit GitHub Action (\#757).


# 2.5.0

* Update task-collection commands, to align with [fractal-server 2.9.0](https://github.com/fractal-analytics-platform/fractal-server/blob/main/CHANGELOG.md#290) (\#738).
Expand Down
2 changes: 1 addition & 1 deletion docs/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
build
api_files
api_files
121 changes: 74 additions & 47 deletions docs/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
Original Copyright 2013 Aleksandr Rudakov
License: MIT
"""

import re
from argparse import _HelpAction, _StoreConstAction, _SubParsersAction
from argparse import _HelpAction
from argparse import _StoreConstAction
from argparse import _SubParsersAction


class NavigationException(Exception): # noqa: N818
Expand All @@ -20,22 +21,30 @@ class NavigationException(Exception): # noqa: N818

def parser_navigate(parser_result, path, current_path=None):
if isinstance(path, str):
if path == '':
if path == "":
return parser_result
path = re.split(r'\s+', path)
path = re.split(r"\s+", path)
current_path = current_path or []
if len(path) == 0:
return parser_result
if 'children' not in parser_result:
raise NavigationException(f"Current parser has no child elements. (path: {' '.join(current_path)})")
if "children" not in parser_result:
raise NavigationException(
"Current parser has no child elements. "
f"(path: {' '.join(current_path)})"
)
next_hop = path.pop(0)
for child in parser_result['children']:
for child in parser_result["children"]:
# identifer is only used for aliased subcommands
identifier = child['identifier'] if 'identifier' in child else child['name']
identifier = (
child["identifier"] if "identifier" in child else child["name"]
)
if identifier == next_hop:
current_path.append(next_hop)
return parser_navigate(child, path, current_path)
raise NavigationException(f"Current parser has no child element with name: {next_hop} (path: {' '.join(current_path)})")
raise NavigationException(
f"Current parser has no child element with name: {next_hop} "
f"(path: {' '.join(current_path)})"
)


def _try_add_parser_attribute(data, parser, attribname):
Expand All @@ -54,20 +63,25 @@ def _format_usage_without_prefix(parser):
the 'usage: ' prefix.
"""
fmt = parser._get_formatter()
fmt.add_usage(parser.usage, parser._actions, parser._mutually_exclusive_groups, prefix='')
fmt.add_usage(
parser.usage,
parser._actions,
parser._mutually_exclusive_groups,
prefix="",
)
return fmt.format_help().strip()


def parse_parser(parser, data=None, **kwargs):
if data is None:
data = {
'name': '',
'usage': parser.format_usage().strip(),
'bare_usage': _format_usage_without_prefix(parser),
'prog': parser.prog,
"name": "",
"usage": parser.format_usage().strip(),
"bare_usage": _format_usage_without_prefix(parser),
"prog": parser.prog,
}
_try_add_parser_attribute(data, parser, 'description')
_try_add_parser_attribute(data, parser, 'epilog')
_try_add_parser_attribute(data, parser, "description")
_try_add_parser_attribute(data, parser, "epilog")
for action in parser._get_positional_actions():
if not isinstance(action, _SubParsersAction):
continue
Expand All @@ -90,23 +104,25 @@ def parse_parser(parser, data=None, **kwargs):
if name in subsection_alias_names:
continue
subalias = subsection_alias[subaction]
subaction.prog = f'{parser.prog} {name}'
subaction.prog = f"{parser.prog} {name}"
subdata = {
'name': name if not subalias else f"{name} ({', '.join(subalias)})",
'help': helps.get(name, ''),
'usage': subaction.format_usage().strip(),
'bare_usage': _format_usage_without_prefix(subaction),
"name": name
if not subalias
else f"{name} ({', '.join(subalias)})",
"help": helps.get(name, ""),
"usage": subaction.format_usage().strip(),
"bare_usage": _format_usage_without_prefix(subaction),
}
if subalias:
subdata['identifier'] = name
subdata["identifier"] = name
parse_parser(subaction, subdata, **kwargs)
data.setdefault('children', []).append(subdata)
data.setdefault("children", []).append(subdata)

show_defaults = True
if kwargs.get('skip_default_values', False) is True:
if kwargs.get("skip_default_values", False) is True:
show_defaults = False
show_defaults_const = show_defaults
if kwargs.get('skip_default_const_values', False) is True:
if kwargs.get("skip_default_const_values", False) is True:
show_defaults_const = False

# argparse stores the different groups as a list in parser._action_groups
Expand All @@ -122,16 +138,22 @@ def parse_parser(parser, data=None, **kwargs):

# Quote default values for string/None types
default = action.default
if action.default not in ['', None, True, False] and action.type in [None, str] and isinstance(action.default, str):
if (
action.default not in ["", None, True, False]
and action.type in [None, str]
and isinstance(action.default, str)
):
default = f'"{default}"'

# fill in any formatters, like %(default)s
format_dict = dict(vars(action), prog=data.get('prog', ''), default=default)
format_dict['default'] = default
help_str = action.help or '' # Ensure we don't print None
format_dict = dict(
vars(action), prog=data.get("prog", ""), default=default
)
format_dict["default"] = default
help_str = action.help or "" # Ensure we don't print None
try:
help_str = help_str % format_dict
except Exception:
except Exception: # nosec
pass

# Options have the option_strings set, positional arguments don't
Expand All @@ -142,24 +164,26 @@ def parse_parser(parser, data=None, **kwargs):
else:
name = [action.metavar]
# Skip lines for subcommands
if name == ['==SUPPRESS==']:
if name == ["==SUPPRESS=="]:
continue

if isinstance(action, _StoreConstAction):
option = {
'name': name,
'default': default if show_defaults_const else '==SUPPRESS==',
'help': help_str,
"name": name,
"default": default
if show_defaults_const
else "==SUPPRESS==",
"help": help_str,
}
else:
option = {
'name': name,
'default': default if show_defaults else '==SUPPRESS==',
'help': help_str,
"name": name,
"default": default if show_defaults else "==SUPPRESS==",
"help": help_str,
}
if action.choices:
option['choices'] = action.choices
if "==SUPPRESS==" not in option['help']:
option["choices"] = action.choices
if "==SUPPRESS==" not in option["help"]:
options_list.append(option)

if len(options_list) == 0:
Expand All @@ -168,20 +192,23 @@ def parse_parser(parser, data=None, **kwargs):
# Upper case "Positional Arguments" and "Optional Arguments" titles
# Since python-3.10 'optional arguments' changed to 'options'
# more info: https://github.com/python/cpython/pull/23858
if action_group.title == 'optional arguments' or action_group.title == 'options':
action_group.title = 'Named Arguments'
if action_group.title == 'positional arguments':
action_group.title = 'Positional Arguments'
if (
action_group.title == "optional arguments"
or action_group.title == "options"
):
action_group.title = "Named Arguments"
if action_group.title == "positional arguments":
action_group.title = "Positional Arguments"

group = {
'title': action_group.title,
'description': action_group.description,
'options': options_list,
"title": action_group.title,
"description": action_group.description,
"options": options_list,
}

action_groups.append(group)

if len(action_groups) > 0:
data['action_groups'] = action_groups
data["action_groups"] = action_groups

return data
4 changes: 1 addition & 3 deletions fractal_client/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,9 +915,7 @@
# user set-groups
user_set_groups_parser = user_subparsers.add_parser(
"set-groups",
description=(
"Reset user-group membership for an existing user."
),
description=("Reset user-group membership for an existing user."),
allow_abbrev=False,
)
user_set_groups_parser.add_argument(
Expand Down
14 changes: 7 additions & 7 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,12 @@ pytest-randomly = "^3.15.0"

[tool.poetry.group.dev.dependencies]
devtools = "^0.12.0"
pre-commit = "^2.19.0"
pre-commit = ">=3.0.0,<4.0.0"
pytest = "^7.1.2"
bumpver = "^2022.1118"
coverage = {extras = ["toml"], version = "^6.5.0"}
fractal-server = { git = "https://github.com/fractal-analytics-platform/fractal-server.git", branch = "main" }


[tool.poetry.group.docs]
optional = true

Expand Down

0 comments on commit 560125e

Please sign in to comment.