-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.py
More file actions
264 lines (227 loc) · 9.4 KB
/
Copy pathinstall.py
File metadata and controls
264 lines (227 loc) · 9.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
import argparse
import os
import shutil
from pathlib import Path
class InstallerBase:
TEMPLATE_DIR = Path(__file__).parent / "templates"
TEMPLATES = {}
@staticmethod
def get_full_path(path_name: str) -> str:
return str(Path(os.path.expandvars(path_name)).expanduser().resolve())
@classmethod
def get_and_check_path(cls, path_name: str) -> str:
path_name = cls.get_full_path(path_name)
if not Path(path_name).is_dir():
raise AssertionError(f'Error: "{path_name}" is not a directory')
return path_name
@staticmethod
def write_to_file(filename, data):
Path(filename).write_text(data, encoding="utf-8")
@classmethod
def load_template_file(cls, template):
filename = cls.TEMPLATES.get(template, {}).get("file", "")
if not filename:
raise AssertionError(f"Error: No file configured for {template}")
filepath = cls.TEMPLATE_DIR / filename
if not filepath.is_file():
raise AssertionError(f'Error: Template file "{filepath}" not found')
return filepath.read_text()
class ConfigInstaller(InstallerBase):
TEMPLATES = {"RUFF": {"file": "ruff.pyproject.toml"}}
DEFAULT_LINE_LENGTH = 120
DEFAULT_TARGET_VERSION = "py312"
DEFAULT_NO_DJANGO = False
def __init__(self, target_dir, line_length=None, target_version=None, no_django=False, toml_path=None):
self.target_dir = self.get_and_check_path(target_dir)
self.line_length = int(line_length) if line_length else None
self.target_version = str(target_version) if target_version else None
self.no_django = bool(no_django)
if toml_path:
# Absolute path overrides target_dir; relative path is resolved against it
toml_dir = (Path(self.target_dir) / toml_path).resolve()
if not toml_dir.is_dir():
raise AssertionError(f'Error: toml-path "{toml_dir}" is not a directory')
self.toml_file = toml_dir / "pyproject.toml"
else:
self.toml_file = Path(self.target_dir) / "pyproject.toml"
def _strip_ruff_sections(self, toml_data: str) -> str:
"""Remove all existing [tool.ruff*] sections so they can be replaced cleanly."""
lines = toml_data.split("\n")
result = []
in_ruff = False
for line in lines:
if line.strip().startswith("["):
in_ruff = line.strip().startswith("[tool.ruff]") or line.strip().startswith("[tool.ruff.")
if not in_ruff:
result.append(line)
return ("\n".join(result).rstrip("\n")).strip() + "\n"
def _apply_overrides(self, template: str) -> str:
line_length = self.line_length if self.line_length else self.DEFAULT_LINE_LENGTH
target_version = self.target_version if self.target_version else self.DEFAULT_TARGET_VERSION
django_entry = "" if self.no_django else '"DJ", '
template = template.replace("{%%LINE_LENGTH%%}", str(line_length))
template = template.replace("{%%TARGET_VERSION%%}", target_version)
template = template.replace("{%%DJANGO%%}", django_entry)
return template
def install(self):
existing = ""
if self.toml_file.is_file():
existing = self.toml_file.read_text()
base = self._strip_ruff_sections(existing)
template = self._apply_overrides(self.load_template_file("RUFF"))
if base.strip():
base = base.rstrip("\n") + "\n\n"
else:
base = ""
self.write_to_file(self.toml_file, base + template)
class HookInstaller(InstallerBase):
TEMPLATES = {"PRE_COMMIT": {"file": "pre-commit.sh"}}
def __init__(self, target_dir, venv_dir=None, ruff_path=None, lint_dir=None):
resolved_target = Path(self.get_full_path(str(target_dir)))
git_path = resolved_target / ".git"
if git_path.is_dir():
hooks_path = str(git_path / "hooks")
elif git_path.is_file():
gitdir_text = git_path.read_text().strip()
if not gitdir_text.startswith("gitdir: "):
raise AssertionError(f'Error: Cannot parse .git file at "{git_path}"')
gitdir = Path(gitdir_text[8:])
if not gitdir.is_absolute():
gitdir = resolved_target / gitdir
# worktree gitdir is <common>/.git/worktrees/<name>; hooks live two levels up
hooks_path = str(gitdir.parent.parent / "hooks")
else:
raise AssertionError(f'Error: No .git directory or file found at "{resolved_target}"')
self.git_hook_dir = Path(self.get_and_check_path(hooks_path))
self.venv_dir = self.get_full_path(venv_dir) if venv_dir else None
self.ruff_path = ruff_path or "ruff"
if lint_dir:
lint_path = (resolved_target / lint_dir).resolve()
if not lint_path.is_dir():
raise AssertionError(f'Error: lint-dir "{lint_path}" is not a directory')
try:
self.lint_dir = str(lint_path.relative_to(resolved_target))
except ValueError as e:
raise AssertionError(
f'Error: lint-dir "{lint_path}" is not inside the project directory "{resolved_target}"'
) from e
else:
self.lint_dir = "."
def generate_template(self):
template = self.load_template_file("PRE_COMMIT")
template = template.replace("{%%USEVENV%%}", "0" if self.venv_dir else "1")
template = template.replace("{%%VENVDIR%%}", self.venv_dir if self.venv_dir else ".")
template = template.replace("{%%RUFFBIN%%}", self.ruff_path)
template = template.replace("{%%LINTDIR%%}", self.lint_dir)
return template
def install(self):
hook_file = self.git_hook_dir / "pre-commit"
if hook_file.is_file():
shutil.copy2(hook_file, hook_file.parent / (hook_file.name + ".bak"))
hook_data = self.generate_template()
self.write_to_file(hook_file, hook_data)
hook_file.chmod(hook_file.stat().st_mode | 0o111)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog="Precommit Ruff Setup",
description=(
"Sets up and configures a pre-commit git hook that automatically runs ruff "
"(format + lint) on your code before each commit."
),
)
parser.add_argument(
"--line-length",
required=False,
default=None,
type=int,
dest="line_length",
metavar="120",
help=f"Line length for ruff (optional, defaults to {ConfigInstaller.DEFAULT_LINE_LENGTH})",
)
parser.add_argument(
"--target-version",
required=False,
default=None,
type=str,
dest="target_version",
metavar="py312",
help=f"Target Python version for ruff (optional, defaults to {ConfigInstaller.DEFAULT_TARGET_VERSION})",
)
parser.add_argument(
"--toml-path",
required=False,
default=None,
type=str,
dest="toml_path",
metavar="/path/to/dir",
help=(
"Directory containing the pyproject.toml to write the ruff config into. "
"Accepts an absolute path or a path relative to the install directory. "
"Defaults to the install directory."
),
)
parser.add_argument(
"--no-django",
required=False,
default=False,
action="store_true",
dest="no_django",
help="Exclude Django-specific lint rules (DJ) from the ruff config",
)
parser.add_argument(
"--ruff-path",
required=False,
default="ruff",
type=str,
dest="ruff_path",
metavar="/path/to/ruff",
help="Absolute path to the ruff binary to embed in the hook (defaults to 'ruff')",
)
parser.add_argument(
"--venv",
required=False,
default=None,
type=str,
dest="venv_dir",
metavar="/path/to/venv",
help="Activate this virtual environment before running ruff in the hook",
)
parser.add_argument(
"--lint-dir",
required=False,
default=None,
type=str,
dest="lint_dir",
metavar="path/to/dir",
help=(
"Restrict the hook to only lint staged files under this directory. "
"Accepts an absolute path or a path relative to the install directory. "
"Defaults to the project root (all staged Python files are linted)."
),
)
parser.add_argument(
"--config-only",
required=False,
default=False,
action="store_true",
dest="config_only",
help="Only write config files; skip installing the git hook",
)
parser.add_argument(
"--githook-only",
required=False,
default=False,
action="store_true",
dest="githook_only",
help="Only install the git hook; skip writing config files",
)
parser.add_argument("install_directory", type=str, help="Target project directory")
argsd = vars(parser.parse_args())
target_dir = argsd["install_directory"]
if not argsd["githook_only"]:
ConfigInstaller(
target_dir, argsd["line_length"], argsd["target_version"], argsd["no_django"], argsd["toml_path"]
).install()
if not argsd["config_only"]:
HookInstaller(target_dir, argsd["venv_dir"], argsd["ruff_path"], argsd["lint_dir"]).install()