我怎么能有一部分代码永远不会在git中提交



假设我们有一个需要大量修改的文件。因此,在试错的情况下,我们编写一些用于测试的东西。我们不想把它发送到commit,甚至不想被git注意到。像

function testThis(){
console.log('helloworld');
}

我写这个函数,这是一个很大的文件的一部分。在登台期间,将考虑此更改。因为在一个文件中有许多这样的更改。因此,在手动选择要执行的更改时,可能会错误地执行此更改。

所以我的问题是:是否有任何包装器或特定于git的东西,如果我包装这些代码,那么这个更改甚至不会被考虑用于staging,更不用说承诺了。就像

<.gitignore>
function testThis(){
console.log('helloworld');
}
</.gitignore>

gitignore允许你忽略模式/文件。因此,一个非常简洁的解决方案是将您为自己的实验开发的所有代码分开并忽略它。假设您的站点使用的是myfile.js。但是,您可以在某个地方实现这样的逻辑:

如果<<ul>
  • strong> myfile-custom.js 存在,则使用
  • 否则使用myfile.js
  • gitignoremyfile-custom.js
  • 这意味着你可以创建一个myfile.js的副本myfile-custom.js从myfile.js的确切内容开始做你的改变。如果上面的逻辑被实现了,那么你的本地将会选择你的自定义代码并使用它,而你永远不会有提交它的危险。

    您可以选择一个特殊的关键字,可以在预提交钩子中拒绝。

    例如:我使用单词dontcommit,并且在我的.git/hooks/pre-commit文件中有以下部分:

    dontcommit=0
    # list files that are staged:
    for file in $(git diff-index --cached --name-only HEAD --diff-filter=ACMR); do
    # look for the forbidden keyword in their content:
    if git grep --cached -q -i dontcommit "$file"; then
    dontcommit=1
    git grep --cached -n -i dontcommit "$file"
    fi
    done
    if test $dontcommit -eq 1; then
    echo " *** aborting commit, 'dontcommit' tag found in staged files"
    exit 1
    fi
    

    这样,当我添加代码,知道我不应该提交它,我只是添加// dontcommit旁边:

    function testThis(){
    // dontcommit
    console.log('helloworld');
    }
    

    要暂存这样一个文件的其他部分,我仍然可以使用git add -p的部分暂存或图形化工具来只添加特定的块(例如:内置的git gui实用程序)