Skip to content
Open
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
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: CI

on:
push:
branches: [master]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12"]

steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: python -m pip install --upgrade pip
- run: python -m pip install -e ".[dev]"
- run: python -m unittest discover -s tests -v
- run: python -m flake8 src tests
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.coverage
.mypy_cache/
.pytest_cache/
.ruff_cache/
.tox/
build/
dist/
*.egg-info/
__pycache__/
*.py[cod]
.venv/
venv/

22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2026 Hacktoolkit

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

69 changes: 69 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,70 @@
# flake8-htk-rules

Hacktoolkit Flake8 rules for structured Python code, datetime clarity,
debugger prevention, and naming precision.

## Installation

```bash
pip install flake8-htk-rules
```

For local development:

```bash
python -m pip install -e ".[dev]"
python -m unittest discover -s tests -v
```

## Rules

| Code | Description |
| --- | --- |
| `SP100` | Functions in configured files should prefer a single return statement. |
| `SP101` | Return values in configured files should be simple variables, attributes, literals, or bare returns. |
| `DT100` | Use `import datetime` instead of `from datetime import datetime`. |
| `DT101` | Use `import datetime` instead of `from datetime import date`. |
| `DT102` | Use `import datetime` instead of `from datetime import timedelta`. |
| `DB100` | Do not commit debugger imports such as `import pdb` or `from pdb import set_trace`. |
| `DB101` | Do not commit debugger calls such as `breakpoint()` or `pdb.set_trace()`. |
| `NM100` | Avoid the vague `get_` function or method prefix; choose a more precise verb. |

## Flake8 Configuration

Enable the rules:

```ini
[flake8]
select = SP,DT,DB,NM
structured-programming-files =
accounts/services.py
accounts/view_helpers.py
accounts/views.py
```

Or combine with existing checks:

```ini
[flake8]
extend-select = SP,DT,DB,NM
structured-programming-files =
accounts/services.py
accounts/view_helpers.py
accounts/views.py
```

The `SP` rules are gated by `structured-programming-files` so teams can roll them
out on a targeted set of modules. The `DT`, `DB`, and `NM` rules are always
active when selected.

## Development

The plugin uses a single Flake8 entry point and delegates rule logic to
family modules under `src/flake8_htk_rules/checks/`. Add new rule families
there and cover them in `tests/`.

Run the test suite without installing the package:

```bash
PYTHONPATH=src python -m unittest discover -s tests -v
```
46 changes: 46 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
[build-system]
requires = ["hatchling>=1.21"]
build-backend = "hatchling.build"

[project]
name = "flake8-htk-rules"
version = "0.1.0"
description = "Hacktoolkit Flake8 rules for structured Python, datetime clarity, debugger prevention, and naming precision."
readme = "README.md"
requires-python = ">=3.9"
license = "MIT"
authors = [
{ name = "Hacktoolkit" },
{ name = "Jonathan Tsai" }
]
classifiers = [
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Framework :: Flake8",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Software Development :: Quality Assurance",
]
dependencies = [
"flake8>=5",
]

[project.optional-dependencies]
dev = [
"build>=1.0",
"flake8>=5",
"pytest>=7",
]

[project.urls]
Homepage = "https://github.com/hacktoolkit/flake8-htk-rules"
Issues = "https://github.com/hacktoolkit/flake8-htk-rules/issues"

[project.entry-points."flake8.extension"]
HTK = "flake8_htk_rules:Plugin"

[tool.hatch.build.targets.wheel]
packages = ["src/flake8_htk_rules"]

60 changes: 60 additions & 0 deletions src/flake8_htk_rules/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""Flake8 entry point for Hacktoolkit rules."""

from __future__ import annotations

import ast
from collections.abc import Iterator

from .checks import HtkVisitor

__version__ = "0.1.0"


class Plugin:
"""Flake8 AST plugin entry point."""

name = "flake8-htk-rules"
version = __version__
structured_programming_files: tuple[str, ...] = ()

def __init__(self, tree: ast.AST, filename: str = "<unknown>") -> None:
self.tree = tree
self.filename = filename

@classmethod
def add_options(cls, parser) -> None:
parser.add_option(
"--structured-programming-files",
parse_from_config=True,
comma_separated_list=True,
default=[],
help=(
"Comma-separated file globs for structured programming "
"checks."
),
)

@classmethod
def parse_options(cls, options) -> None:
cls.structured_programming_files = tuple(
pattern.strip()
for pattern in getattr(options, "structured_programming_files", [])
if pattern.strip()
)

def run(self) -> Iterator[tuple[int, int, str, type["Plugin"]]]:
visitor = HtkVisitor(
filename=self.filename,
structured_programming_files=self.structured_programming_files,
)
visitor.visit(self.tree)
for violation in visitor.violations:
yield (
violation.line,
violation.column,
violation.message,
type(self),
)


__all__ = ["Plugin", "__version__"]
90 changes: 90 additions & 0 deletions src/flake8_htk_rules/checks/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Check orchestration for Hacktoolkit Flake8 rules."""

from __future__ import annotations

import ast

from . import datetime as datetime_checks
from . import debugger, naming, structured
from .types import Violation


class HtkVisitor(ast.NodeVisitor):
"""Collect Hacktoolkit rule violations from a Python AST."""

def __init__(
self,
*,
filename: str,
structured_programming_files: tuple[str, ...] = (),
) -> None:
self.filename = filename
self.structured_programming_files = structured_programming_files
self.violations: list[Violation] = []
self._debugger_state = debugger.DebuggerState()

def visit_Import(self, node: ast.Import) -> None:
for violation_node, message in debugger.check_import(
node,
self._debugger_state,
):
self._add(violation_node, node, message)
self.generic_visit(node)

def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
for violation_node, message in datetime_checks.check_import_from(node):
self._add(violation_node, node, message)
for violation_node, message in debugger.check_import_from(
node,
self._debugger_state,
):
self._add(violation_node, node, message)
self.generic_visit(node)

def visit_Call(self, node: ast.Call) -> None:
for violation_node, message in debugger.check_call(
node,
self._debugger_state,
):
self._add(violation_node, node, message)
self.generic_visit(node)

def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
self._check_function(node)
self.generic_visit(node)

def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
self._check_function(node)
self.generic_visit(node)

def _check_function(
self,
node: ast.FunctionDef | ast.AsyncFunctionDef,
) -> None:
for violation_node, message in naming.check_function(node):
self._add(violation_node, node, message)

if not structured.should_check_file(
self.filename,
self.structured_programming_files,
):
return

for violation_node, message in structured.check_function(node):
self._add(violation_node, node, message)

def _add(self, node: ast.AST, fallback: ast.AST, message: str) -> None:
self.violations.append(
Violation(
line=getattr(node, "lineno", getattr(fallback, "lineno", 1)),
column=getattr(
node,
"col_offset",
getattr(fallback, "col_offset", 0),
),
message=message,
)
)


__all__ = ["HtkVisitor", "Violation"]
37 changes: 37 additions & 0 deletions src/flake8_htk_rules/checks/datetime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Datetime clarity checks."""

from __future__ import annotations

import ast


DT100 = (
"DT100 use 'import datetime' instead of "
"'from datetime import datetime'"
)
DT101 = (
"DT101 use 'import datetime' instead of "
"'from datetime import date'"
)
DT102 = (
"DT102 use 'import datetime' instead of "
"'from datetime import timedelta'"
)

DATETIME_IMPORT_MESSAGES = {
"datetime": DT100,
"date": DT101,
"timedelta": DT102,
}


def check_import_from(node: ast.ImportFrom) -> list[tuple[ast.AST, str]]:
if node.module != "datetime" or node.level != 0:
return []

violations = []
for alias in node.names:
message = DATETIME_IMPORT_MESSAGES.get(alias.name)
if message is not None:
violations.append((alias, message))
return violations
Loading
Loading