如何在存在调试代码时禁止git提交

uinbv5nw  于 2023-04-19  发布在  Git
关注(0)|答案(1)|浏览(109)

我有一些调试代码,我想确保我没有提交给Git。
类似于:

void myImportantFunction () {
    while (true) {
       //MyCode
#ifndef NDEBUG
       //TODO remove before commit
       std::this_thread::sleep_for (std::chrono::seconds(1));  
#endif
    }
}

ifndef NDEBUG将保护我不受此影响,使其意外地进入生产环境,但我仍然会让调试版本运行得非常慢,这让我的同事感到不安。
有没有一种方法可以让我在提交时设置GIT不接受这段代码。我不喜欢在TODO上这样做,因为可能会有其他的示例,但我很乐意添加另一个标签,如果可能的话。

r1wp621o

r1wp621o1#

下面是我使用的pre-commit钩子:
它会扫描所有准备提交的文件,查找一个特殊的单词:dontcommit ;如果这个字出现在某处,则提交命令失败。

#!/bin/bash                                                                     
                                                                            
# check if 'dontcommit' tag is present in files staged for commit
function dontcommit_tag () {                                                    
    git grep --cached -n -i "dontcommit" -- $(git diff --cached --name-only)                            
}                                                                               

# if 'dontcommit' tag is present, exit with error code                                                                        
if dontcommit_tag                                                               
then                                                                            
    echo "*** Found 'DONTCOMMIT' flag in staged files, commit refused"          
    exit 1                                                                      
fi

每当我添加一个调试代码块时,我打算在提交之前删除它,我输入一个额外的// dontcommit注解:

void myImportantFunction () {
    while (true) {
       //MyCode
#ifndef NDEBUG
       // dontcommit
       std::this_thread::sleep_for (std::chrono::seconds(1));  
#endif
    }
}

这不是万无一失的,但它为我工作。

相关问题