-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpre-commit.py
More file actions
221 lines (176 loc) · 6.6 KB
/
Copy pathpre-commit.py
File metadata and controls
221 lines (176 loc) · 6.6 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
import json
import os
import re
import subprocess
import sys
from pathlib import Path
VERSION_FILE = Path("magazarr/version.py")
def run(cmd, check=True, capture=False, text=True):
print(f"⚙️ Exec: {' '.join(cmd)}")
return subprocess.run(cmd, check=check, capture_output=capture, text=text)
def get_env(key, default=None):
return os.environ.get(key, default)
def git_status_has_changes():
return bool(run(["git", "status", "--porcelain"], capture=True).stdout.strip())
def task_format():
print("\n🔍 --- 1. FORMATTING ---")
result = run(["uv", "run", "ruff", "check", "--fix", "."], check=False)
if result.returncode != 0:
print("❌ Critical errors found. Fix them before staging.")
sys.exit(1)
run(["uv", "run", "ruff", "format", "."], check=False)
if git_status_has_changes():
print("✅ Linting fixes applied.")
run(["git", "add", "."])
return True
print("✨ Code style is already perfect.")
return False
def task_tests():
print("\n🧪 --- 2. TESTS ---")
result = run(["uv", "run", "pytest"], check=False)
if result.returncode != 0:
print("❌ Tests failed. Fix before staging.")
sys.exit(1)
print("✅ Tests passed.")
def task_version_bump():
print("\n🏷️ --- 3. VERSION CHECK ---")
new_v = ""
def get_ver(content):
m = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', content)
return m.group(1) if m else None
def bump(v):
p = v.split(".")
while len(p) < 3:
p.append("0")
try:
p[-1] = str(int(p[-1]) + 1)
except Exception:
p.append("1")
return ".".join(p)
def ver_tuple(v):
try:
return tuple(map(int, v.split(".")))
except Exception:
return (0, 0, 0)
try:
remote_ref = "origin/main"
has_origin = (
subprocess.run(
["git", "remote", "get-url", "origin"],
check=False,
capture_output=True,
text=True,
).returncode
== 0
)
if has_origin:
run(["git", "fetch", "origin", "main"], check=False)
remote_ok = (
subprocess.run(
["git", "rev-parse", "--verify", remote_ref],
check=False,
capture_output=True,
).returncode
== 0
)
if not remote_ok:
print("ℹ️ origin/main not available. Skipping version comparison.")
remote_ref = None
else:
print("ℹ️ No 'origin' remote. Skipping version comparison.")
remote_ref = None
main_v = None
if remote_ref:
try:
main_v_content = subprocess.check_output(
["git", "show", f"{remote_ref}:{VERSION_FILE.as_posix()}"],
text=True,
)
main_v = get_ver(main_v_content)
except Exception:
pass
curr_v = get_ver(VERSION_FILE.read_text())
print(f"📊 Main: {main_v} | Current: {curr_v}")
if main_v and curr_v and ver_tuple(curr_v) <= ver_tuple(main_v):
new_v = bump(main_v)
print(f"🚀 Bumping version to: {new_v}")
content = VERSION_FILE.read_text().replace(f'"{curr_v}"', f'"{new_v}"')
VERSION_FILE.write_text(content)
run(["git", "add", "."])
return True, new_v
except Exception as e:
print(f"⚠️ Version check warning (non-fatal): {e}")
return False, new_v
def main():
is_ci = "--ci" in sys.argv
fixed_format = task_format()
task_tests()
fixed_version, new_v = task_version_bump()
if is_ci and (fixed_format or fixed_version):
print("\n📤 --- 4. PUSH ---")
run(["git", "config", "--global", "user.name", "github-actions[bot]"])
run(
[
"git",
"config",
"--global",
"user.email",
"41898282+github-actions[bot]@users.noreply.github.com",
]
)
parts = []
if fixed_format:
parts.append("fixed linting")
if fixed_version:
parts.append(f"increased version to {new_v}")
msg_body = (
", ".join(parts[:-1]) + " and " + parts[-1] if len(parts) > 1 else parts[0]
)
try:
run(["git", "commit", "-m", f"chore: 🤖 {msg_body}"])
target_ref = get_env("TARGET_REF") or get_env("GITHUB_HEAD_REF")
if not target_ref:
print("ℹ️ Not on a PR branch (no GITHUB_HEAD_REF). Skipping push.")
sys.exit(0)
print(f"🔄 Rebase and pushing to {target_ref}...")
run(["git", "pull", "--rebase", "origin", target_ref], check=False)
run(["git", "push", "origin", f"HEAD:{target_ref}"])
if "GITHUB_OUTPUT" in os.environ:
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write("changes_pushed=true\n")
except subprocess.CalledProcessError as e:
print(f"❌ ::error::Failed to push fixes. ({e})")
sys.exit(1)
pr_num = get_env("PR_NUMBER")
if not pr_num:
try:
pr_json = subprocess.check_output(
["gh", "pr", "list", "--head", target_ref, "--json", "number"],
text=True,
)
prs = json.loads(pr_json)
if prs:
pr_num = str(prs[0]["number"])
except Exception:
pass
if pr_num:
fixes_list = ""
if fixed_format:
fixes_list += "- ✅ **Formatted Code**\n"
if fixed_version:
fixes_list += f"- ✅ **Bumped Version** ({new_v})\n"
body = f"### 🤖 Auto-Fix Applied\nI fixed the following issues so we can merge:\n{fixes_list}\n"
body += f"**Note:** Build is now **GREEN** 🟢. Please run `git pull origin {target_ref}` locally.\n"
Path("comment.md").write_text(body, encoding="utf-8")
run(
["gh", "pr", "comment", pr_num, "--body-file", "comment.md"],
check=False,
)
sys.exit(0)
else:
print("\n✨ Clean run. No changes needed.")
if "GITHUB_OUTPUT" in os.environ:
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write("changes_pushed=false\n")
if __name__ == "__main__":
main()