Skip to content

Commit e6dcc34

Browse files
committed
chore: enable more linting rules
1 parent 57eb02e commit e6dcc34

File tree

13 files changed

+95
-62
lines changed

13 files changed

+95
-62
lines changed

pyproject.toml

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,33 @@ log_level = "DEBUG"
9494
line-length = 79
9595

9696
[tool.ruff.lint]
97-
select = ["D", "E", "F", "I", "N", "PL", "RUF", "SIM"]
98-
ignore = ["D102", "D103", "D105", "D107", "D415", "PLR2004"]
97+
select = [
98+
"A",
99+
"ANN",
100+
"ARG",
101+
"D",
102+
"E",
103+
"ERA",
104+
"F",
105+
"I",
106+
"INP",
107+
"LOG",
108+
"N",
109+
"PL",
110+
"RUF",
111+
"SIM",
112+
"SLF",
113+
"T20",
114+
"TD",
115+
"UP",
116+
"W"
117+
]
118+
ignore = [
119+
"ANN003", "ANN401",
120+
"D102", "D103", "D105", "D107", "D415",
121+
"PLR2004",
122+
"TD002", "TD003",
123+
]
99124

100125
[tool.ruff.lint.isort]
101126
force-sort-within-sections = true
@@ -105,4 +130,4 @@ lines-after-imports = 2
105130
convention = "google"
106131

107132
[tool.ruff.lint.per-file-ignores]
108-
"tests/**" = ["D"]
133+
"tests/**" = ["ANN", "D", "SLF"]

src/git_draft/__main__.py

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22

33
from __future__ import annotations
44

5+
from collections.abc import Sequence
56
import importlib.metadata
67
import logging
78
import optparse
89
from pathlib import Path, PurePosixPath
910
import sys
10-
from typing import Sequence
1111

1212
from .bots import load_bot
1313
from .common import PROGRAM, Config, UnreachableError, ensure_state_home
@@ -41,7 +41,12 @@ def new_parser() -> optparse.OptionParser:
4141
)
4242

4343
def add_command(name: str, short: str | None = None, **kwargs) -> None:
44-
def callback(_option, _opt, _value, parser) -> None:
44+
def callback(
45+
_option: object,
46+
_opt: object,
47+
_value: object,
48+
parser: optparse.OptionParser,
49+
) -> None:
4550
parser.values.command = name
4651

4752
parser.add_option(
@@ -128,20 +133,20 @@ class ToolPrinter(ToolVisitor):
128133
def on_list_files(
129134
self, _paths: Sequence[PurePosixPath], _reason: str | None
130135
) -> None:
131-
print("Listing available files...")
136+
pass
132137

133138
def on_read_file(
134139
self, path: PurePosixPath, _contents: str | None, _reason: str | None
135140
) -> None:
136-
print(f"Reading {path!r}...")
141+
pass
137142

138143
def on_write_file(
139144
self, path: PurePosixPath, _contents: str, _reason: str | None
140145
) -> None:
141-
print(f"Updated {path!r}.")
146+
pass
142147

143148
def on_delete_file(self, path: PurePosixPath, _reason: str | None) -> None:
144-
print(f"Deleted {path!r}.")
149+
pass
145150

146151

147152
def edit(*, path: Path | None = None, text: str | None = None) -> str:
@@ -153,26 +158,23 @@ def edit(*, path: Path | None = None, text: str | None = None) -> str:
153158
# https://unix.stackexchange.com/q/604260
154159
elif path is None:
155160
assert text, "Empty path and text"
156-
print(text)
157161
sys.exit(198)
158162
else:
159163
if text is not None:
160164
with open(path, "w") as f:
161165
f.write(text)
162-
print(path)
163166
sys.exit(199)
164167

165168

166169
_PROMPT_PLACEHOLDER = "Enter your prompt here..."
167170

168171

169-
def main() -> None: # noqa: PLR0912 PLR0915
172+
def main() -> None: # noqa: PLR0912
170173
config = Config.load()
171174
(opts, args) = new_parser().parse_args()
172175

173176
log_path = ensure_state_home() / "log"
174177
if opts.log:
175-
print(log_path)
176178
return
177179
logging.basicConfig(level=config.log_level, filename=str(log_path))
178180

@@ -210,19 +212,16 @@ def main() -> None: # noqa: PLR0912 PLR0915
210212
reset=config.auto_reset if opts.reset is None else opts.reset,
211213
sync=opts.sync,
212214
)
213-
print(f"Refined {name}.")
214215
elif command == "finalize":
215216
name = drafter.exit_draft(
216217
revert=opts.revert, clean=opts.clean, delete=opts.delete
217218
)
218-
verb = "Reverted" if opts.revert else "Finalized"
219-
print(f"{verb} {name}.")
220219
elif command == "show-drafts":
221220
table = drafter.history_table(args[0] if args else None)
222221
if table:
223-
print(table.to_json() if opts.json else table)
222+
pass
224223
elif command == "show-prompts":
225-
raise NotImplementedError() # TODO
224+
raise NotImplementedError() # TODO: Implement
226225
elif command == "show-templates":
227226
if args:
228227
name = args[0]
@@ -232,21 +231,17 @@ def main() -> None: # noqa: PLR0912 PLR0915
232231
edit(path=tpl.local_path(), text=tpl.source)
233232
else:
234233
edit(path=Template.local_path_for(name))
235-
else:
236-
if not tpl:
237-
raise ValueError(f"No template named {name!r}")
238-
print(tpl.source)
234+
elif not tpl:
235+
raise ValueError(f"No template named {name!r}")
239236
else:
240237
table = templates_table()
241-
print(table.to_json() if opts.json else table)
242238
else:
243239
raise UnreachableError()
244240

245241

246242
if __name__ == "__main__":
247243
try:
248244
main()
249-
except Exception as err:
245+
except Exception:
250246
_logger.exception("Program failed.")
251-
print(f"Error: {err}", file=sys.stderr)
252247
sys.exit(1)

src/git_draft/bots/common.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,10 @@ class Action:
2929
request_count: int | None = None
3030
token_count: int | None = None
3131

32-
def increment_request_count(self, n=1, init=False) -> None:
32+
def increment_request_count(self, n: int = 1, init: bool = False) -> None:
3333
self._increment("request_count", n, init)
3434

35-
def increment_token_count(self, n, init=False) -> None:
35+
def increment_token_count(self, n: int, init: bool = False) -> None:
3636
self._increment("token_count", n, init)
3737

3838
def _increment(self, attr: str, count: int, init: bool) -> None:
@@ -48,7 +48,7 @@ class Bot:
4848
"""Code assistant bot"""
4949

5050
@classmethod
51-
def state_folder_path(cls, ensure_exists=False) -> Path:
51+
def state_folder_path(cls, ensure_exists: bool = False) -> Path:
5252
"""Returns a path unique to this bot class
5353
5454
The path can be used to store data specific to this bot implementation.

src/git_draft/bots/openai.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@
1212
* https://github.com/openai/openai-python/blob/main/src/openai/resources/beta/threads/runs/runs.py
1313
"""
1414

15+
from collections.abc import Mapping, Sequence
1516
import json
1617
import logging
1718
import os
1819
from pathlib import PurePosixPath
19-
from typing import Any, Mapping, Self, Sequence, TypedDict, override
20+
from typing import Any, Self, TypedDict, override
2021

2122
import openai
2223

@@ -61,7 +62,7 @@ def _param(
6162
name: str,
6263
description: str,
6364
inputs: Mapping[str, Any] | None = None,
64-
required_inputs: Sequence[str] | None = None,
65+
_required_inputs: Sequence[str] | None = None,
6566
) -> openai.types.beta.FunctionToolParam:
6667
param: openai.types.beta.FunctionToolParam = {
6768
"type": "function",
@@ -225,10 +226,10 @@ def _on_read_file(self, path: PurePosixPath, contents: str | None) -> str:
225226
return f"`{path}` does not exist."
226227
return f"The contents of `{path}` are:\n\n```\n{contents}\n```\n"
227228

228-
def _on_write_file(self, path: PurePosixPath) -> None:
229+
def _on_write_file(self, _path: PurePosixPath) -> None:
229230
return None
230231

231-
def _on_delete_file(self, path: PurePosixPath) -> None:
232+
def _on_delete_file(self, _path: PurePosixPath) -> None:
232233
return None
233234

234235
def _on_list_files(self, paths: Sequence[PurePosixPath]) -> str:
@@ -316,7 +317,7 @@ def on_run_step_done(
316317
else:
317318
_logger.warning("Missing usage in threads run step")
318319

319-
def _handle_action(self, run_id: str, data: Any) -> None:
320+
def _handle_action(self, _run_id: str, data: Any) -> None:
320321
tool_outputs = list[Any]()
321322
for tool in data.required_action.submit_tool_outputs.tool_calls:
322323
handler = _ThreadToolHandler(self._toolbox, tool.id)
@@ -347,15 +348,15 @@ def _wrap(self, output: str) -> _ToolOutput:
347348
return _ToolOutput(tool_call_id=self._call_id, output=output)
348349

349350
def _on_read_file(
350-
self, path: PurePosixPath, contents: str | None
351+
self, _path: PurePosixPath, contents: str | None
351352
) -> _ToolOutput:
352353
return self._wrap(contents or "")
353354

354-
def _on_write_file(self, path: PurePosixPath) -> _ToolOutput:
355+
def _on_write_file(self, _path: PurePosixPath) -> _ToolOutput:
355356
return self._wrap("OK")
356357

357-
def _on_delete_file(self, path: PurePosixPath) -> _ToolOutput:
358+
def _on_delete_file(self, _path: PurePosixPath) -> _ToolOutput:
358359
return self._wrap("OK")
359360

360361
def _on_list_files(self, paths: Sequence[PurePosixPath]) -> _ToolOutput:
361-
return self._wrap("\n".join((str(p) for p in paths)))
362+
return self._wrap("\n".join(str(p) for p in paths))

src/git_draft/common.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
from collections.abc import Mapping, Sequence
56
import dataclasses
67
import itertools
78
import logging
@@ -11,7 +12,7 @@
1112
import string
1213
import textwrap
1314
import tomllib
14-
from typing import Any, ClassVar, Mapping, Self, Sequence, Type
15+
from typing import Any, ClassVar, Self
1516

1617
import prettytable
1718
import xdg_base_dirs
@@ -84,7 +85,7 @@ class UnreachableError(RuntimeError):
8485
"""Indicates unreachable code was unexpectedly executed"""
8586

8687

87-
def reindent(s: str, width=0) -> str:
88+
def reindent(s: str, width: int = 0) -> str:
8889
"""Reindents text by dedenting and optionally wrapping paragraphs"""
8990
paragraphs = (
9091
" ".join(textwrap.dedent("\n".join(g)).splitlines())
@@ -96,7 +97,7 @@ def reindent(s: str, width=0) -> str:
9697
)
9798

9899

99-
def qualified_class_name(cls: Type) -> str:
100+
def qualified_class_name(cls: type) -> str:
100101
name = cls.__qualname__
101102
return f"{cls.__module__}.{name}" if cls.__module__ else name
102103

src/git_draft/drafter.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
from collections.abc import Callable, Sequence
56
import dataclasses
67
from datetime import datetime
78
import json
@@ -10,9 +11,9 @@
1011
import os.path as osp
1112
from pathlib import PurePosixPath
1213
import re
14+
from re import Match
1315
import textwrap
1416
import time
15-
from typing import Callable, Match, Sequence
1617

1718
import git
1819

@@ -53,7 +54,7 @@ def active(cls, repo: git.Repo, name: str | None = None) -> _Branch | None:
5354
return _Branch(match[1])
5455

5556
@staticmethod
56-
def new_suffix():
57+
def new_suffix() -> str:
5758
return random_id(9)
5859

5960

@@ -85,7 +86,7 @@ def generate_draft( # noqa: PLR0913
8586
timeout: float | None = None,
8687
) -> str:
8788
if timeout is not None:
88-
raise NotImplementedError() # TODO
89+
raise NotImplementedError() # TODO: Implement
8990

9091
if self._repo.is_dirty(working_tree=False):
9192
if not reset:
@@ -174,7 +175,9 @@ def generate_draft( # noqa: PLR0913
174175
_logger.info("Completed generation for %s.", branch)
175176
return str(branch)
176177

177-
def exit_draft(self, *, revert: bool, clean=False, delete=False) -> str:
178+
def exit_draft(
179+
self, *, revert: bool, clean: bool = False, delete: bool = False
180+
) -> str:
178181
branch = _Branch.active(self._repo)
179182
if not branch:
180183
raise RuntimeError("Not currently on a draft branch")
@@ -312,7 +315,7 @@ def _untracked(self) -> frozenset[str]:
312315
text = self._repo.git.ls_files(exclude_standard=True, others=True)
313316
return frozenset(text.splitlines())
314317

315-
def _delta(self, spec) -> _Delta:
318+
def _delta(self, spec: str) -> _Delta:
316319
changed = list[str]()
317320
deleted = list[str]()
318321
for line in self._repo.git.diff(spec, name_status=True).splitlines():

src/git_draft/editor.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,16 @@ def _guess_editor_binpath() -> str:
2222
return ""
2323

2424

25-
def _get_tty_filename():
25+
def _get_tty_filename() -> str:
2626
return "CON:" if sys.platform == "win32" else "/dev/tty"
2727

2828

29-
def open_editor(text="", path: Path | None = None, *, _open_tty=open) -> str:
29+
def open_editor(
30+
text: str = "",
31+
path: Path | None = None,
32+
*,
33+
_open_tty=open, # noqa
34+
) -> str:
3035
"""Open an editor to edit a file and return its contents
3136
3237
The method returns once the editor is closed. It respects the `$EDITOR`
@@ -46,7 +51,7 @@ def edit(path: str) -> str:
4651
proc = subprocess.Popen([binpath, path], close_fds=True, stdout=stdout)
4752
proc.communicate()
4853

49-
with open(path, mode="r") as reader:
54+
with open(path) as reader:
5055
return reader.read()
5156

5257
if path:

0 commit comments

Comments
 (0)