Skip to content

Commit

Permalink
style!: switch to black's default 88 char limit
Browse files Browse the repository at this point in the history
* ci: autoupdate pre-commit config
* feat: assert 85 char limit in nbqa-black
  • Loading branch information
redeboer committed Jun 16, 2022
1 parent 001da43 commit 27dba75
Show file tree
Hide file tree
Showing 24 changed files with 119 additions and 177 deletions.
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
- id: check-useless-excludes

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.2.0
rev: v4.3.0
hooks:
- id: check-ast
- id: check-case-conflict
Expand Down Expand Up @@ -46,7 +46,7 @@ repos:
- id: blacken-docs

- repo: https://github.com/ComPWA/repo-maintenance
rev: 0.0.128
rev: 0.0.130
hooks:
- id: check-dev-files
- id: format-setup-cfg
Expand Down Expand Up @@ -76,7 +76,7 @@ repos:
- id: markdownlint

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.6.2
rev: v2.7.1
hooks:
- id: prettier

Expand All @@ -86,12 +86,12 @@ repos:
- id: pydocstyle

- repo: https://github.com/ComPWA/mirrors-pyright
rev: v1.1.252
rev: v1.1.254
hooks:
- id: pyright

- repo: https://github.com/asottile/pyupgrade
rev: v2.33.0
rev: v2.34.0
hooks:
- id: pyupgrade
args:
Expand Down
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"coverage-gutters.showGutterCoverage": false,
"coverage-gutters.showLineCoverage": true,
"editor.formatOnSave": true,
"editor.rulers": [80],
"editor.rulers": [88],
"files.watcherExclude": {
"**/*_cache/**": true,
"**/.eggs/**": true,
Expand All @@ -52,7 +52,7 @@
"python.testing.pytestArgs": ["--color=no", "--no-cov", "-vv"],
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"rewrap.wrappingColumn": 79,
"rewrap.wrappingColumn": 88,
"search.exclude": {
"**/tests/**/__init__.py": true,
"*/.pydocstyle": true,
Expand Down
7 changes: 4 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ exclude = '''
)/
'''
include = '\.pyi?$'
line-length = 79
preview = true
target-version = [
'py36',
Expand All @@ -35,5 +34,7 @@ target-version = [

[tool.isort]
profile = "black"
src_paths = ["src", "tests"]
line_length = 79
src_paths = [
"src",
"tests",
]
5 changes: 1 addition & 4 deletions src/repoma/check_dev_files/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
"--no-prettierrc",
default=False,
action="store_true",
help=(
"Remove the prettierrc, so that Prettier's default values are"
" used."
),
help="Remove the prettierrc, so that Prettier's default values are used.",
)
parser.add_argument(
"--allow-labels",
Expand Down
58 changes: 36 additions & 22 deletions src/repoma/check_dev_files/black.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Check :file:`pyproject.toml` black config."""
from __future__ import annotations

from collections import OrderedDict
from textwrap import dedent
Expand All @@ -9,17 +10,14 @@
from repoma.errors import PrecommitError
from repoma.utilities import CONFIG_PATH, natural_sorting
from repoma.utilities.executor import Executor
from repoma.utilities.precommit import (
PrecommitConfig,
load_round_trip_precommit_config,
)
from repoma.utilities.precommit import PrecommitConfig, load_round_trip_precommit_config
from repoma.utilities.setup_cfg import get_supported_python_versions


def main() -> None:
if not CONFIG_PATH.pyproject.exists():
return
config = _load_config()
config = _load_black_config()
executor = Executor()
executor(_check_line_length, config)
executor(_check_activate_preview, config)
Expand All @@ -30,13 +28,9 @@ def main() -> None:
raise PrecommitError(executor.merge_messages())


def _load_config(content: Optional[str] = None) -> dict:
if content is None:
with open(CONFIG_PATH.pyproject) as stream:
config = toml.load(stream, _dict=OrderedDict)
else:
config = toml.loads(content, _dict=OrderedDict)
return config.get("tool", {}).get("black")
def _load_black_config(content: Optional[str] = None) -> dict:
config = _load_pyproject_toml(content)
return config.get("tool", {}).get("black", {})


def _check_activate_preview(config: dict) -> None:
Expand All @@ -55,17 +49,9 @@ def _check_activate_preview(config: dict) -> None:


def _check_line_length(config: dict) -> None:
expected_line_length = 79
if config.get("line-length") != expected_line_length:
if config.get("line-length") is not None:
raise PrecommitError(
dedent(
f"""
Black line-length in pyproject.toml in pyproject.toml should be:
[tool.black]
line-length = {expected_line_length}
"""
).strip()
"pyproject.toml should not specify a line-length (default to 88)."
)


Expand Down Expand Up @@ -134,3 +120,31 @@ def _update_nbqa_hook() -> None:
config["repos"][repo_index]["hooks"][hook_index] = expected_config
yaml.dump(config, CONFIG_PATH.precommit)
raise PrecommitError(f"Updated args of {hook_id} pre-commit hook")
nbqa_config = _load_nbqa_black_config()
if nbqa_config != ["--line-length=85"]:
error_message = dedent(
"""
Configuration of nbqa-black in pyproject.toml should be as follows:
[tool.nbqa.addopts]
black = [
"--line-length=85",
]
This is to ensure that code blocks render nicely in the sphinx-book-theme.
"""
).strip()
raise PrecommitError(error_message)


def _load_nbqa_black_config(content: Optional[str] = None) -> list[str]:
# cspell:ignore addopts
config = _load_pyproject_toml(content)
return config.get("tool", {}).get("nbqa", {}).get("addopts", {}).get("black", {})


def _load_pyproject_toml(content: Optional[str] = None) -> dict:
if content is None:
with open(CONFIG_PATH.pyproject) as stream:
return toml.load(stream, _dict=OrderedDict)
return toml.loads(content, _dict=OrderedDict)
36 changes: 10 additions & 26 deletions src/repoma/check_dev_files/cspell.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
from repoma.errors import PrecommitError
from repoma.utilities import CONFIG_PATH, REPOMA_DIR, rename_file
from repoma.utilities.executor import Executor
from repoma.utilities.precommit import (
PrecommitConfig,
load_round_trip_precommit_config,
)
from repoma.utilities.precommit import PrecommitConfig, load_round_trip_precommit_config
from repoma.utilities.readme import add_badge, remove_badge
from repoma.utilities.vscode import (
add_vscode_extension_recommendation,
Expand Down Expand Up @@ -86,8 +83,7 @@ def _remove_configuration() -> None:
if CONFIG_PATH.cspell.exists():
os.remove(CONFIG_PATH.cspell)
raise PrecommitError(
f'"{CONFIG_PATH.cspell}" is no longer required'
" and has been removed"
f'"{CONFIG_PATH.cspell}" is no longer required and has been removed'
)
if CONFIG_PATH.editor_config.exists():
with open(CONFIG_PATH.editor_config) as stream:
Expand All @@ -112,9 +108,7 @@ def _check_check_hook_options() -> None:
config = PrecommitConfig.load()
repo = config.find_repo(__REPO_URL)
if repo is None:
raise PrecommitError(
f"{CONFIG_PATH.precommit} is missing a repo: {__REPO_URL}"
)
raise PrecommitError(f"{CONFIG_PATH.precommit} is missing a repo: {__REPO_URL}")
expected_yaml = f"""
- repo: {__REPO_URL}
rev: ...
Expand All @@ -125,12 +119,10 @@ def _check_check_hook_options() -> None:
expected_dict = yaml.safe_load(expected_yaml)[0]
if (
list(repo_dict) != list(expected_dict)
or [h.dict(skip_defaults=True) for h in repo.hooks]
!= expected_dict["hooks"]
or [h.dict(skip_defaults=True) for h in repo.hooks] != expected_dict["hooks"]
):
raise PrecommitError(
"cSpell pre-commit hook should have the following form:\n"
+ expected_yaml
"cSpell pre-commit hook should have the following form:\n" + expected_yaml
)


Expand Down Expand Up @@ -174,9 +166,7 @@ def _sort_config_entries() -> None:
if fixed_sections:
__write_config(config)
error_message = __express_list_of_sections(fixed_sections)
error_message += (
f" in {CONFIG_PATH.cspell} has been sorted alphabetically."
)
error_message += f" in {CONFIG_PATH.cspell} has been sorted alphabetically."
raise PrecommitError(error_message)


Expand All @@ -192,17 +182,15 @@ def _check_editor_config() -> None:
)
if not cfg.has_section(str(CONFIG_PATH.cspell)):
raise PrecommitError(
f"{CONFIG_PATH.editor_config} has no section"
f' "[{CONFIG_PATH.cspell}]"'
f'{CONFIG_PATH.editor_config} has no section "[{CONFIG_PATH.cspell}]"'
)
expected_options = {
"indent_size": "4",
}
options = dict(cfg.items(str(CONFIG_PATH.cspell)))
if options != expected_options:
error_message = (
f"{CONFIG_PATH.editor_config} should have the following"
" section:\n\n"
f"{CONFIG_PATH.editor_config} should have the following section:\n\n"
)
section_content = f"[{CONFIG_PATH.cspell}]\n"
for option, value in expected_options.items():
Expand All @@ -228,14 +216,10 @@ def _update_prettier_ignore() -> None:
return
with open(prettier_ignore_path, "w+") as stream:
stream.write(expected_line)
raise PrecommitError(
f'Added "{CONFIG_PATH.cspell}" to {prettier_ignore_path}"'
)
raise PrecommitError(f'Added "{CONFIG_PATH.cspell}" to {prettier_ignore_path}"')


def __get_expected_content(
config: dict, section: str, *, extend: bool = False
) -> Any:
def __get_expected_content(config: dict, section: str, *, extend: bool = False) -> Any:
if section not in config:
return __EXPECTED_CONFIG[section]
section_content = config[section]
Expand Down
13 changes: 3 additions & 10 deletions src/repoma/check_dev_files/flake8.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@

from repoma.errors import PrecommitError
from repoma.utilities import CONFIG_PATH, natural_sorting
from repoma.utilities.cfg import (
extract_config_section,
format_config,
open_config,
)
from repoma.utilities.cfg import extract_config_section, format_config, open_config
from repoma.utilities.executor import Executor
from repoma.utilities.setup_cfg import open_setup_cfg

Expand Down Expand Up @@ -140,9 +136,7 @@ def _check_option_order(cfg: Optional[ConfigParser] = None) -> None:
values = content.split("\n")
if "" in values:
values.remove("")
if values != sorted(
values, key=lambda s: natural_sorting(s.lower())
):
if values != sorted(values, key=lambda s: natural_sorting(s.lower())):
raise PrecommitError(
f'Option "{option}" in section [{section}] is not sorted'
)
Expand All @@ -154,8 +148,7 @@ def _check_setup_cfg(cfg: Optional[ConfigParser] = None) -> None:
extras_require = "options.extras_require"
if not cfg.has_section(extras_require):
raise PrecommitError(
f"Please list flake8 under a section [{extras_require}] in"
" setup.cfg"
f"Please list flake8 under a section [{extras_require}] in setup.cfg"
)
requirements = indent("\n".join(__FLAKE8_REQUIREMENTS), 12 * " ")
error_message = f"""\
Expand Down
19 changes: 5 additions & 14 deletions src/repoma/check_dev_files/github_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,12 @@ def main() -> None:

def _check_issue_templates() -> None:
existing_templates = _list_template_files(__ISSUE_TEMPLATE_PATH)
expected_templates = _list_template_files(
REPOMA_DIR / __ISSUE_TEMPLATE_PATH
)
expected_templates = _list_template_files(REPOMA_DIR / __ISSUE_TEMPLATE_PATH)
error_message = ""
if set(existing_templates) != set(expected_templates):
shutil.rmtree(__ISSUE_TEMPLATE_PATH, ignore_errors=True)
os.makedirs(__ISSUE_TEMPLATE_PATH, exist_ok=True)
error_message = (
f"{__ISSUE_TEMPLATE_PATH} doesn't contain expected templates:\n"
)
error_message = f"{__ISSUE_TEMPLATE_PATH} doesn't contain expected templates:\n"
for basename in expected_templates:
import_path = REPOMA_DIR / __ISSUE_TEMPLATE_PATH / basename
export_path = __ISSUE_TEMPLATE_PATH / basename
Expand All @@ -53,13 +49,10 @@ def _check_issue_templates() -> None:
def _check_pr_template() -> None:
if not os.path.exists(__PR_TEMPLATE_PATH):
os.makedirs(os.path.dirname(__PR_TEMPLATE_PATH), exist_ok=True)
expected_content = __get_template_content(
REPOMA_DIR / __PR_TEMPLATE_PATH
)
expected_content = __get_template_content(REPOMA_DIR / __PR_TEMPLATE_PATH)
__write_template(expected_content, __PR_TEMPLATE_PATH)
raise PrecommitError(
f"This repository has no {__PR_TEMPLATE_PATH} file."
" Problem has been fixed."
f"This repository has no {__PR_TEMPLATE_PATH} file. Problem has been fixed."
)
with open(__PR_TEMPLATE_PATH) as stream:
template_content = stream.read()
Expand All @@ -79,9 +72,7 @@ def __get_template_content(path: Path) -> str:

def _list_template_files(directory: Path) -> List[str]:
template_files = []
for _, __, files in os.walk( # pyright: reportUnusedVariable=false
directory
):
for _, __, files in os.walk(directory): # pyright: reportUnusedVariable=false
template_files.extend(files)
return template_files

Expand Down
4 changes: 1 addition & 3 deletions src/repoma/check_dev_files/github_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ def check_docs_workflow() -> None:


def _copy_workflow_file(filename: str) -> None:
expected_workflow_path = (
REPOMA_DIR / CONFIG_PATH.github_workflow_dir / filename
)
expected_workflow_path = REPOMA_DIR / CONFIG_PATH.github_workflow_dir / filename
with open(expected_workflow_path) as stream:
expected_content = stream.read()
if not CONFIG_PATH.pip_constraints.exists():
Expand Down
3 changes: 1 addition & 2 deletions src/repoma/check_dev_files/nbstripout.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ def _update_extra_keys_argument(repo_index: int, repo: Repo) -> None:
index = repo.get_hook_index(__HOOK_ID)
if index is None:
raise PrecommitError(
f'The following repo is missing hook ID "{__HOOK_ID}":'
f" {__REPO_URL}"
f'The following repo is missing hook ID "{__HOOK_ID}": {__REPO_URL}'
)
expected_args = [
"--extra-keys",
Expand Down
Loading

0 comments on commit 27dba75

Please sign in to comment.