代码之家  ›  专栏  ›  技术社区  ›  Varun Gupta

检查代码存在的Git钩子

  •  0
  • Varun Gupta  · 技术社区  · 8 年前

    我的git知识有限,无法理解上的文档 git-hooks .我想知道是否有办法添加 git-hook 或者一些其他构造,使得它可以检查在文件之一中是否存在/注释掉某些代码。我的工作流程是我有一个配置文件 globalConfig.js 其包含两组配置: development production 配置和注释 生产 配置,但当我将任何代码提交到我的repo时,我希望确保 生产 配置未注释,并且 发展 配置已注释。

    摘自globalConfig。js文件

    发展

      // Production config - Always uncomment it before commiting
      // const firebaseConfig = {
      //   apiKey: "prod",
      //   authDomain: "prod",
      //   databaseURL: "prod",
      //   storageBucket: "prod",
      //   messagingSenderId: "prod"
      // };
    
      // Dev config - Always comment out before commiting
      const firebaseConfig = {
        apiKey: "dev",
        authDomain: "dev",
        databaseURL: "dev",
        storageBucket: "dev",
        messagingSenderId: "dev"
      };
    

    生产

      // Production config - Always uncomment it before commiting
      const firebaseConfig = {
       apiKey: "prod",
       authDomain: "prod",
       databaseURL: "prod",
       storageBucket: "prod",
       messagingSenderId: "prod"
      };
    
      // Dev config - Always comment out before commiting
      // const firebaseConfig = {
      //  apiKey: "dev",
      //  authDomain: "dev",
      //  databaseURL: "dev",
      //  storageBucket: "dev",
      //  messagingSenderId: "dev"
      //};
    

    有可能通过以下方式实现吗 或者其他git构造?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ashutosh Jindal    8 年前

    下面的pre-commit钩子应该可以让您开始。如果文件中有 development 在它中,它必须是注释,否则不允许提交。

    步骤:

    1. 创造 .git/hooks/pre-commit 具有以下内容:
    
        git diff --cached --name-status | while read file; 
        do
                    if egrep "development" $file ; then
                        echo "ERROR: Disallowed development configuration in file: ${file}"
                        exit 1
                    fi
        done || exit $?
    

    请注意,egrep表达式是非常简单的atm,但您应该能够根据您的要求修改它(即 globalConfig.js )或者,您可以使用以下代码片段更新您的问题

    1. 更改权限

    chmod 755 .git/hooks/pre-commit

    1. 然后尝试提交一个无效的 globalConfig.js 文件以下是我的测试结果:
    
    ☻  cat globalConfig.js                                 SomeOtherFeature/abc 0d174e2 ✗
    //Configuration
    var Production = new String("Production Configuration");
    var development = new String("development Configuration");
    
    $ git add globalConfig.js
    
    $ git commit -m "Commit should not be allowed"
    Checking if globalConfig.js is valid
    var development = new String("development Configuration");
    ERROR: Disallowed development configuration in file: globalConfig.js