如何允许Git提交消息,如“修复#3”来更新Trac票证?

时间:2013-04-07 16:16:19

标签: git trac

我刚刚在一台同时拥有Git存储库的服务器上安装了Trac 1.0.1。我希望能够通过在Git提交消息中包含诸如“修复#3”之类的内容来关闭Trac票证。这应该非常简单 - 通过在我的存储库中包含post-receive hook,我可以在每个git push之后执行一些代码(例如Python脚本)到服务器。但是要使用哪些代码?

1 个答案:

答案 0 :(得分:4)

经过一段时间并且经历了几个死胡同(包括the Trac Git page(对此话题模糊不清)和Git plugin之后,它们实际上不起作用(?!)直到bug #7301已修复),我找到了解决方案。

  1. 通过“setting up a Trac environment”的步骤将您的Git存储库连接到Trac。

  2. 启用Commit Ticket Updater插件,可以通过Trac的“管理员”部分或修改trac.ini

  3. 在您的Git存储库的post-receive目录中创建一个名为hooks的文件,其中包含以下内容:

    #!/usr/bin/ruby
    
    ARGF.lines do |line|
      fields = line.split
      oldrev = fields[0]
      newrev = fields[1]
      refname = fields[2].chomp
    
      if oldrev =~ /^0+$/
        revspec = newrev
      else
        revspec = oldrev + '..' + newrev
      end
    
      other_branches = `git for-each-ref --format='%(refname)' refs/heads/ | grep -F -v "#{refname}"`
      other_branches = other_branches.chomp.gsub /[\r\n]+/, ' '
    
      commits = `git rev-parse --not #{other_branches} | git rev-list --stdin #{revspec}`
    
      commits.each_line do |commit|
        system "trac-admin .../trac changeset added '(default)' #{commit.chomp}"
      end
    end
    

    当然,将“... / trac”替换为Trac安装的绝对路径。

    我实际上是通过Virtualenv使用Trac。如果您也是,请将其添加到文件顶部:

    require 'tempfile'
    
    def virtualenv_system(cmd)
      script = Tempfile.new('post_receive')
      script.write 'source .../virtualenvs/trac/bin/activate'
      script.write "\n"
      script.write cmd
      script.close
      system "bash #{script.path}"
      script.unlink
    end
    

    并将system来电替换为virtualenv_system

  4. 使此post-receive文件可执行。

  5. 这受到the Repository Administration page上给出的方法的启发,结合this SO answer关于在后接收脚本中获取所有新提交的方法。我相信这个脚本虽然很长,但是当您推送多个提交和/或将提交推送到当前已检出的分支以外的分支时,其行为正确。 (在“存储库管理”页面上给出的脚本在这些情况下表现正常 - 它只查看来自HEAD的最新提交消息。)

    在此设置过程之后,任何包含“fixes#7”等字符串的Git提交都将关闭Trac中的相应票证。您可以使用Commit Ticket Updater page上列出的选项稍微配置一下。具体来说,您可能想要更改commit_ticket_update_envelope的值;它并不完全清楚,但我认为设置了默认值,因此您必须将命令包含在方括号中,例如“Refactored MyAwesomeClass [fixes#42]”。