Skip to content

Commit

Permalink
Fix: typing and inheritance errors
Browse files Browse the repository at this point in the history
Add: github workflow to automatically run mypy-checks
  • Loading branch information
Tom committed Dec 20, 2022
1 parent 9b8fbc9 commit 490882e
Show file tree
Hide file tree
Showing 12 changed files with 445 additions and 178 deletions.
4 changes: 3 additions & 1 deletion autohooks/api/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ class StatusEntry:
old_path: Set for renamed files
"""

def __init__(self, status_string: str, root_path: Path = None) -> None:
def __init__(
self, status_string: str, root_path: Optional[Path] = None
) -> None:
status = status_string[:2]
filename = status_string[3:]

Expand Down
2 changes: 1 addition & 1 deletion autohooks/cli/activate.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def install_hooks(term: Terminal, args: Namespace) -> None:

term.ok(f"autohooks settings written to {pyproject_toml}.")
elif args.force:
settings = config.settings
settings = config.settings # type: ignore
settings.mode = mode
settings.write(pyproject_toml)

Expand Down
14 changes: 7 additions & 7 deletions autohooks/cli/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def list_plugins(term: Terminal, args: Namespace) -> None:
config = load_config_from_pyproject_toml(pyproject_toml)

current_plugins = (
config.settings.pre_commit if config.has_autohooks_config() else []
config.settings.pre_commit if config.has_autohooks_config() else [] # type: ignore # pylint:disable = C0301
)
print_current_plugins(term, current_plugins)

Expand All @@ -73,11 +73,11 @@ def add_plugins(term: Terminal, args: Namespace) -> None:

if config.has_autohooks_config():
settings = config.settings
existing_plugins = set(settings.pre_commit)
existing_plugins = set(settings.pre_commit) # type: ignore
all_plugins = plugins_to_add | existing_plugins
duplicate_plugins = plugins_to_add & existing_plugins
new_plugins = plugins_to_add - existing_plugins
settings.pre_commit = all_plugins
settings.pre_commit = all_plugins # type: ignore

if duplicate_plugins:
term.info("Skipped already used plugins:")
Expand All @@ -90,7 +90,7 @@ def add_plugins(term: Terminal, args: Namespace) -> None:
settings = AutohooksSettings(pre_commit=all_plugins)
config.settings = settings

settings.write(pyproject_toml)
settings.write(pyproject_toml) # type: ignore

if new_plugins:
term.info("Added plugins:")
Expand All @@ -111,11 +111,11 @@ def remove_plugins(term: Terminal, args: Namespace) -> None:

if config.has_autohooks_config():
settings = config.settings
existing_plugins = set(settings.pre_commit)
existing_plugins = set(settings.pre_commit) # type: ignore
removed_plugins = existing_plugins & plugins_to_remove
all_plugins = existing_plugins - plugins_to_remove
skipped_plugins = plugins_to_remove - existing_plugins
settings.pre_commit = all_plugins
settings.pre_commit = all_plugins # type: ignore

if skipped_plugins:
term.info("Skipped not used plugins:")
Expand All @@ -129,7 +129,7 @@ def remove_plugins(term: Terminal, args: Namespace) -> None:
for plugin in sorted(removed_plugins):
term.ok(f'"{plugin}"')

settings.write(pyproject_toml)
settings.write(pyproject_toml) # type: ignore

print_current_plugins(term, all_plugins)
else:
Expand Down
12 changes: 6 additions & 6 deletions autohooks/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Config:
Config helper class for easier access to a tree of settings.
"""

def __init__(self, config_dict: Dict[str, Any] = None) -> None:
def __init__(self, config_dict: Optional[Dict[str, Any]] = None) -> None:
"""
Create a new Config from a dictionary.
Expand Down Expand Up @@ -84,11 +84,11 @@ def is_empty(self) -> bool:
return not bool(self._config_dict)


def _gather_mode(mode: Optional[str]) -> Mode:
def _gather_mode(mode_string: Optional[str]) -> Mode:
"""
Gather the mode from a mode string
"""
mode = Mode.from_string(mode)
mode = Mode.from_string(mode_string)
is_virtual_env = mode == Mode.PIPENV or mode == Mode.POETRY
if is_virtual_env and not is_split_env():
if mode == Mode.POETRY:
Expand All @@ -115,11 +115,11 @@ def has_autohooks_config(self) -> bool:
return self.settings is not None

def get_pre_commit_script_names(self) -> List[str]:
return self.settings.pre_commit if self.has_autohooks_config() else []
return self.settings.pre_commit if self.has_autohooks_config() else [] # type: ignore # pylint:disable

def get_mode(self) -> Mode:
return (
self.settings.mode
self.settings.mode # type: ignore
if self.has_autohooks_config()
else Mode.UNDEFINED
)
Expand Down Expand Up @@ -162,7 +162,7 @@ def from_toml(toml_file: Path) -> "AutohooksConfig":


def load_config_from_pyproject_toml(
pyproject_toml: Path = None,
pyproject_toml: Optional[Path] = None,
) -> AutohooksConfig:
"""
Load an AutohooksConfig from a pyproject.toml file
Expand Down
5 changes: 3 additions & 2 deletions autohooks/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import re
from pathlib import Path
from typing import Optional

from autohooks.settings import Mode
from autohooks.template import (
Expand All @@ -37,7 +38,7 @@ def get_pre_commit_hook_path():


class PreCommitHook:
def __init__(self, pre_commit_hook_path: Path = None) -> None:
def __init__(self, pre_commit_hook_path: Optional[Path] = None) -> None:
self._pre_commit_hook = None

if pre_commit_hook_path is None:
Expand All @@ -50,7 +51,7 @@ def pre_commit_hook(self) -> str:
if self._pre_commit_hook is None:
self._pre_commit_hook = self.pre_commit_hook_path.read_text()

return self._pre_commit_hook
return self._pre_commit_hook # type: ignore

def exists(self) -> bool:
return self.pre_commit_hook_path.exists()
Expand Down
9 changes: 6 additions & 3 deletions autohooks/precommit/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
from types import ModuleType
from typing import Generator, Optional

from rich.progress import TaskID

from autohooks.config import load_config_from_pyproject_toml
from autohooks.hooks import PreCommitHook
from autohooks.settings import Mode
Expand Down Expand Up @@ -120,6 +122,7 @@ def check_plugin(plugin_name: str) -> Optional[CheckPluginResult]:
return CheckPluginError(
f'"{plugin_name}" is not a valid autohooks plugin. {e}'
)
return None


class ReportProgress:
Expand All @@ -129,7 +132,7 @@ class ReportProgress:

def __init__(self, progress: Progress, task_id: int) -> None:
self._progress = progress
self._task_id = task_id
self._task_id = TaskID(task_id)

def init(self, total: int) -> None:
"""
Expand All @@ -141,7 +144,7 @@ def init(self, total: int) -> None:
"""
self._progress.update(self._task_id, total=total)

def update(self, advance: Optional[int] = 1) -> None:
def update(self, advance: int = 1) -> None:
"""
Update the number of already processed steps/items/files.
Expand Down Expand Up @@ -207,7 +210,7 @@ def run() -> int:
)
retval = plugin.precommit()

progress.finish_task(task_id)
progress.update(task_id, total=1, advance=1)

if retval:
return retval
Expand Down
8 changes: 4 additions & 4 deletions autohooks/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,20 @@ def write(self, filename: Path) -> None:
overridden.
"""
if filename.exists():
toml_doc = tomlkit.loads(filename.read_text())
toml_doc: tomlkit.TOMLDocument = tomlkit.loads(filename.read_text())
else:
toml_doc = tomlkit.document()

if "tool" not in toml_doc:
toml_doc["tool"] = tomlkit.table(is_super_table=True)
if "autohooks" not in toml_doc["tool"]:
toml_doc["tool"]["autohooks"] = tomlkit.table()
if "autohooks" not in toml_doc["tool"]: # type: ignore
toml_doc["tool"]["autohooks"] = tomlkit.table() # type: ignore

config_dict = {
"mode": str(self.mode.get_effective_mode()),
"pre-commit": sorted(self.pre_commit),
}

toml_doc["tool"]["autohooks"].update(config_dict)
toml_doc["tool"]["autohooks"].update(config_dict) # type: ignore

filename.write_text(tomlkit.dumps(toml_doc), encoding="utf8")
5 changes: 3 additions & 2 deletions autohooks/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from pathlib import Path
from string import Template
from typing import Dict, Optional, Union

from autohooks.settings import Mode
from autohooks.utils import get_autohooks_directory_path
Expand Down Expand Up @@ -49,7 +50,7 @@ def get_pre_commit_hook_template_path() -> Path:


class PreCommitTemplate:
def __init__(self, template_path: Path = None) -> None:
def __init__(self, template_path: Optional[Path] = None) -> None:
if template_path is None:
template_path = get_pre_commit_hook_template_path()
self._load(template_path)
Expand All @@ -60,7 +61,7 @@ def _load(self, template_path: Path) -> None:
def render(self, *, mode: Mode) -> str:
mode = mode.get_effective_mode()

params = dict(VERSION=TEMPLATE_VERSION)
params: Dict[str, Union[str, int]] = dict(VERSION=TEMPLATE_VERSION)

if mode == Mode.PIPENV:
params["SHEBANG"] = PIPENV_SHEBANG
Expand Down
15 changes: 12 additions & 3 deletions autohooks/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from typing import Optional

from pontos.helper import deprecated
from pontos.terminal.rich import RichTerminal as Terminal
from pontos.terminal.terminal import Signs
from rich.progress import BarColumn
Expand All @@ -36,7 +37,7 @@
"warning",
)

__term = None # pylint: disable=invalid-name
__term = Terminal()


def ok(message: str) -> None:
Expand Down Expand Up @@ -109,8 +110,11 @@ def out(message: str):
__term.out(message)


def overwrite(message: str, new_line: bool = False):
__term.print_overwrite(message, new_line=new_line)
@deprecated
def overwrite(
message: str, new_line: bool = False
): # pylint: disable=unused-argument
pass


def _set_terminal(term: Optional[Terminal] = None) -> Terminal:
Expand All @@ -135,3 +139,8 @@ def __init__(self, terminal: Terminal) -> None:

def finish_task(self, task_id):
self.update(task_id, total=1, advance=1)

def __enter__( # pylint: disable=useless-super-delegation
self,
) -> "Progress":
return super().__enter__() # type: ignore
13 changes: 7 additions & 6 deletions autohooks/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import shlex
import subprocess
from pathlib import Path
from typing import List, Optional


class GitError(subprocess.CalledProcessError):
Expand Down Expand Up @@ -49,7 +50,7 @@ def exec_git(*args: str, ignore_errors: bool = False) -> str:
exec_git("commit", "-m", "A new commit")
"""
try:
cmd_args = ["git"]
cmd_args: List[str] = ["git"]
cmd_args.extend(args)
process = subprocess.run(
cmd_args, check=True, capture_output=True, text=True
Expand All @@ -64,7 +65,7 @@ def exec_git(*args: str, ignore_errors: bool = False) -> str:
def get_git_directory_path() -> Path:
pwd = Path.cwd()

git_dir = exec_git("-C", pwd, "rev-parse", "--git-dir").rstrip()
git_dir = exec_git("-C", str(pwd), "rev-parse", "--git-dir").rstrip()

if pwd and str(pwd) not in git_dir:
git_dir_path = Path(pwd) / git_dir
Expand All @@ -78,7 +79,7 @@ def get_autohooks_directory_path() -> Path:
return Path(__file__).resolve().parent


def get_git_hook_directory_path(git_dir_path: Path = None) -> Path:
def get_git_hook_directory_path(git_dir_path: Optional[Path] = None) -> Path:
if git_dir_path is None:
git_dir_path = get_git_directory_path()
return git_dir_path / "hooks"
Expand All @@ -93,7 +94,7 @@ def is_project_root(path: Path) -> bool:
)


def get_project_root_path(path: Path = None) -> Path:
def get_project_root_path(path: Optional[Path] = None) -> Path:
if path is None:
path = Path.cwd()

Expand All @@ -109,12 +110,12 @@ def get_project_root_path(path: Path = None) -> Path:
return path


def get_project_autohooks_plugins_path(path: Path = None) -> Path:
def get_project_autohooks_plugins_path(path: Optional[Path] = None) -> Path:
root = get_project_root_path(path)
return root / ".autohooks"


def get_pyproject_toml_path(path: Path = None) -> Path:
def get_pyproject_toml_path(path: Optional[Path] = None) -> Path:
root = get_project_root_path(path)
return root / "pyproject.toml"

Expand Down
Loading

0 comments on commit 490882e

Please sign in to comment.