V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
git
Pro Git
Atlassian Git Tutorial
Pro Git 简体中文翻译
GitX
simuhunluo
V2EX  ›  git

git hooks 通过 pre-merge-commit 按照策略禁止合并分支

  •  
  •   simuhunluo · 50 天前 · 453 次点击
    这是一个创建于 50 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请教大家

    在 pre-merge-commit 脚本中如何获取 git merge <branch2025> 命令中的目标分支名称?

    背景

    比如当前我们开发分支是 dev/202403/r1, 同一时间也可能会有需求在 dev/202404/r1 上面进行开发。开发过程中禁止将 dev/202404/r1 分支的代码合并到 dev/202403/r1 。

    解决该问题的思路是获取两个分支的名称,并提取其中的日期,判断日期先后顺序进行拦截。

    现在遇到的问题就是能获取到当前分支名称 dev/202403/r1 ,但是获取不到 git merge <branch>后面的目标分支名称,请教大家是否有思路可以解决呢?

    曾做尝试:

    1. target_branch=cat $1 失败
    2. target_branch= $1 失败

    通过$0 打印出来的内容可以看出,脚本执行其实是.git/hooks/pre-merge-commit ,在执行钩子脚本的时候 git merge 命令还会真正执行。但是理论上讲,命令已经提给 git 了,应该有什么骚操作可以拿到目标分支名称。

    pnfuu8.png

    我的脚本代码(gpt 辅助写的)

    #!/bin/bash
    
    # 获取当前分支名称
    current_branch=$(git rev-parse --abbrev-ref HEAD)
    
    # 获取目标分支名称
    target_branch=`cat $1`
    
    # 提取分支名称中的日期
    current_date=$(echo $current_branch | grep -oP '\d{8}')
    echo "当前所处分支:"$current_branch", 检测到迭代日期:"$current_date
    target_date=$(echo $target_branch | grep -oP '\d{8}')
    echo "要合并的分支:"$target_branch", 检测到迭代日期:"$target_date
    
    # 检查日期是否存在
    if [[ -z "$current_date" ]] || [[ -z "$target_date" ]]; then
        echo "无法从分支名称中提取日期"
        exit 1
    fi
    
    # 比较日期
    if [[ "$current_date" -gt "$target_date" ]]; then
        echo "禁止将大的日期合并到小的日期分支上"
        exit 1
    fi
    
    # 允许合并
    exit 0
    
    4 条回复
    julyclyde
        1
    julyclyde  
       49 天前
    没明白,那到底是$1 还是,不是$1 呢?
    刚开始你说$1 失败,但是后面脚本还是用的$1
    simuhunluo
        2
    simuhunluo  
    OP
       49 天前
    @julyclyde $1 行不通。我贴的脚本是我的测试例子。
    julyclyde
        3
    julyclyde  
       49 天前
    @simuhunluo 哦。明白了
    就是“如果有参数”那程序应该是这样,但实际上却没有这个参数

    感觉没什么办法呢
    leemars
        4
    leemars  
       30 天前
    https://thomasvilhena.com/2021/11/prevent-merge-from-specific-branch-git-hook
    这里提供了一个根据 GIT_REFLOG_ACTION 来判断行为的拦截思路

    https://stackoverflow.com/a/74816940
    这里提供了另一个在 prepare-commit-msg 中进行拦截的思路
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2669 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 10:49 · PVG 18:49 · LAX 03:49 · JFK 06:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.