Skip to content

Commit 7710b7d

Browse files
committed
chore: add Git pre-push hook
防止直接推送到 main 分支
1 parent ace2ccb commit 7710b7d

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

.githooks/pre-push

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/bin/sh
2+
3+
# 获取当前分支名称
4+
current_branch=$(git symbolic-ref --short HEAD)
5+
6+
# 获取目标远程库名称及 URL
7+
remote_name="$1"
8+
remote_url="$2"
9+
10+
if [ -z "$remote_url" ]; then
11+
remote_url=$(git remote get-url "$remote_name" 2>/dev/null)
12+
fi
13+
14+
# 如果是 main 分支,并且目标是主仓,则阻止 push
15+
if [ "$current_branch" = "main" ]; then
16+
if echo "$remote_url" | grep -qi "OneDragon-Anything/ZenlessZoneZero-OneDragon"; then
17+
echo "=========================================================="
18+
echo " [ERROR] 拦截:请不要直接推送(push)代码到主仓的 main 分支!"
19+
echo " Direct push to the main repo's main branch is not allowed!"
20+
echo ""
21+
echo " 请在本地切出 feature 分支并提交 Pull Request/Merge Request。"
22+
echo " Please create a feature branch and submit a Pull/Merge Request."
23+
echo "=========================================================="
24+
exit 1
25+
fi
26+
fi
27+
28+
exit 0

src/one_dragon/base/operation/one_dragon_context.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,11 +297,55 @@ def init(self) -> None:
297297
self.gh_proxy_service.update_proxy_url()
298298

299299
self.init_others()
300+
self._setup_git_hooks()
300301
except Exception:
301302
log.error('初始化出错', exc_info=True)
302303
finally:
303304
self._init_lock.release()
304305

306+
def _setup_git_hooks(self) -> None:
307+
"""
308+
自动配置本地的 git hooks 指向项目中的 .githooks 目录
309+
"""
310+
try:
311+
import subprocess
312+
313+
cls_file = inspect.getfile(self.__class__)
314+
src_dir = file_utils.find_src_dir(cls_file)
315+
if src_dir is None:
316+
return
317+
project_root = src_dir.parent
318+
git_dir = project_root / ".git"
319+
githooks_dir = project_root / ".githooks"
320+
321+
if git_dir.exists() and githooks_dir.exists():
322+
# 检查当前的 hooksPath
323+
result = subprocess.run(
324+
["git", "config", "core.hooksPath"],
325+
capture_output=True,
326+
text=True,
327+
cwd=str(project_root)
328+
)
329+
current_hooks_path = result.stdout.strip()
330+
331+
# 如果没有指向 .githooks 则配置
332+
if current_hooks_path != ".githooks":
333+
subprocess.run(
334+
["git", "config", "core.hooksPath", ".githooks"],
335+
cwd=str(project_root)
336+
)
337+
log.info("Git hooks 路径已成功配置为 .githooks")
338+
339+
# 赋予执行权限
340+
pre_push_file = githooks_dir / "pre-push"
341+
if pre_push_file.exists():
342+
try:
343+
pre_push_file.chmod(0o755)
344+
except Exception:
345+
pass
346+
except Exception as e:
347+
log.warning(f"自动配置 Git hooks 失败: {e}")
348+
305349
def init_controller(self) -> None:
306350
"""
307351
初始化控制器

0 commit comments

Comments
 (0)