如何在Windows环境中使用Trac&SVN实现Post Commit Hook?

我在Trac / SVNWindows环境中运行,我想提交到存储库整合到Trac和closures在SVN注释中logging的错误。

我知道有一些后提交挂钩来做到这一点,但没有太多关于如何在Windows上做的信息。

任何人都成功了吗? 你遵循的步骤是什么?

这里是我需要在SVN中安装的钩子,但是我不确定如何在Windows环境中执行此操作。

Trac后提交钩

Solutions Collecting From Web of "如何在Windows环境中使用Trac&SVN实现Post Commit Hook?"

本杰明的答案是接近的,但在Windows上,你需要给钩子脚本文件一个可执行的扩展名,如.bat或.cmd。 我使用.cmd。 您可以使用模板脚本,这些脚本是unix shell脚本,shell脚本并将其转换为.bat / .cmd语法。

但要回答与Trac集成的问题,请按照以下步骤操作。

  1. 确保Python.exe位于系统路径中。 这会让你的生活更轻松。

  2. 在\ hooks文件夹中创建post-commit.cmd。 这是Subversion在post-commit事件中执行的实际钩子脚本。

    @ECHO OFF :: POST-COMMIT HOOK :: :: The post-commit hook is invoked after a commit. Subversion runs :: this hook by invoking a program (script, executable, binary, etc.) :: named 'post-commit' (for which this file is a template) with the :: following ordered arguments: :: :: [1] REPOS-PATH (the path to this repository) :: [2] REV (the number of the revision just committed) :: :: The default working directory for the invocation is undefined, so :: the program should set one explicitly if it cares. :: :: Because the commit has already completed and cannot be undone, :: the exit code of the hook program is ignored. The hook program :: can use the 'svnlook' utility to help it examine the :: newly-committed tree. :: :: On a Unix system, the normal procedure is to have 'post-commit' :: invoke other programs to do the real work, though it may do the :: work itself too. :: :: Note that 'post-commit' must be executable by the user(s) who will :: invoke it (typically the user httpd runs as), and that user must :: have filesystem-level permission to access the repository. :: :: On a Windows system, you should name the hook program :: 'post-commit.bat' or 'post-commit.exe', :: but the basic idea is the same. :: :: The hook program typically does not inherit the environment of :: its parent process. For example, a common problem is for the :: PATH environment variable to not be set to its usual value, so :: that subprograms fail to launch unless invoked via absolute path. :: If you're having unexpected problems with a hook program, the :: culprit may be unusual (or missing) environment variables. :: :: Here is an example hook script, for a Unix /bin/sh interpreter. :: For more examples and pre-written hooks, see those in :: the Subversion repository at :: http://svn.collab.net/repos/svn/trunk/tools/hook-scripts/ and :: http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/ setlocal :: Debugging setup :: 1. Make a copy of this file. :: 2. Enable the command below to call the copied file. :: 3. Remove all other commands ::call %~dp0post-commit-run.cmd %* > %1/hooks/post-commit.log 2>&1 :: Call Trac post-commit hook call %~dp0trac-post-commit.cmd %* || exit 1 endlocal 
  3. 在\ hooks文件夹中创建trac-post-commit.cmd:

     @ECHO OFF :: :: Trac post-commit-hook script for Windows :: :: Contributed by markus, modified by cboos. :: Usage: :: :: 1) Insert the following line in your post-commit.bat script :: :: call %~dp0\trac-post-commit-hook.cmd %1 %2 :: :: 2) Check the 'Modify paths' section below, be sure to set at least TRAC_ENV setlocal :: ---------------------------------------------------------- :: Modify paths here: :: -- this one *must* be set SET TRAC_ENV=D:\projects\trac\membershipdnn :: -- set if Python is not in the system path SET PYTHON_PATH= :: -- set to the folder containing trac/ if installed in a non-standard location SET TRAC_PATH= :: ---------------------------------------------------------- :: Do not execute hook if trac environment does not exist IF NOT EXIST %TRAC_ENV% GOTO :EOF set PATH=%PYTHON_PATH%;%PATH% set PYTHONPATH=%TRAC_PATH%;%PYTHONPATH% SET REV=%2 :: Resolve ticket references (fixes, closes, refs, etc.) Python "%~dp0trac-post-commit-resolve-ticket-ref.py" -p "%TRAC_ENV%" -r "%REV%" endlocal 
  4. 在\ hooks文件夹中创建trac-post-commit-resolve-ticket-ref.py。 我使用了EdgeWall中的相同脚本 ,只是为了更好地阐明其目的,我重命名了它。

好吧,现在我已经有了一些时间来发表我的经验后,全力以赴,并感谢克雷格让我在正确的轨道上。 这是你需要做的(至少在SVN v1.4和Trac v0.10.3中):

  1. 找到您想启用Post Commit Hook的SVN仓库。
  2. 在SVN仓库里面有一个叫做hooks的目录,这是你放置post commit钩子的地方。
  3. 创建一个文件post-commit.bat(这是SVN提交后自动调用的批处理文件)。
  4. 在post-commit.bat文件中放置下面的代码(这会调用你的post commit cmd文件传入SVN自动传递的参数,%1是存储库,%2是提交的修订。

%〜dp0 \ trac-post-commit-hook.cmd%1%2

  1. 现在创建trac-post-commit-hook.cmd文件,如下所示:

@ECHO关闭
::
:: Trac post-commit-hook脚本
::
::供稿人:markus,由cboos修改。

::用法:
::
:: 1)在你的post-commit.bat脚本中插入以下行
::
:: call%〜dp0 \ trac-post-commit-hook.cmd%1%2
::
:: 2)检查下面的“修改路径”部分,确保至少设置TRAC_ENV

:: ———————————————— ———-
::在这里修改路径:

:: – 这个必须设置
SET TRAC_ENV = C:\ trac \ MySpecialProject

:: – 如果Python不在系统路径中,则设置
:: SET PYTHON_PATH =

:: – 设置为包含trac /的文件夹(如果安装在非标准位置)
:: SET TRAC_PATH =
:: ———————————————— ———-

::如果trac环境不存在,则不要执行hook
如果不存在%TRAC_ENV%GOTO:EOF

设置PATH =%PYTHON_PATH%;%PATH%
设置PYTHONPATH =%TRAC_PATH%;%PYTHONPATH%

SET REV =%2

::获取作者和日志消息
('svnlook author -r%REV%%1')中的/ F %% A设置AUTHOR = %% A
('svnlook log -r%REV%%1')/ F“delims ==”%% B设置LOG = %% B

::打电话给PYTHON SCRIPT
Python“%〜dp0 \ trac-post-commit-hook”-p“%TRAC_ENV%”-r“%REV%”-u“%AUTHOR%”-m“%LOG%”

这里最重要的部分是设置TRAC_ENV,它是存储库根目录的路径(SET TRAC_ENV = C:\ trac \ MySpecialProject)

这个脚本中的下一个重要事项是执行以下操作:

::获取作者和日志消息
('svnlook author -r%REV%%1')中的/ F %% A设置AUTHOR = %% A
('svnlook log -r%REV%%1')/ F“delims ==”%% B设置LOG = %% B

如果你在上面的脚本文件中看到,我正在使用svnlook(这是一个与SVN的命令行实用程序)获取LOG消息和提交到存储库的作者。

然后,脚本的下一行实际上是调用Python代码来执行关闭票据并解析日志消息。 我不得不修改这个以传递日志消息和作者(我在Trac中使用的用户名与SVN中的用户名相匹配,这很容易)。

打电话给PYTHON SCRIPT
Python“%〜dp0 \ trac-post-commit-hook”-p“%TRAC_ENV%”-r“%REV%”-u“%AUTHOR%”-m“%LOG%”

脚本中的上面一行将传递到Trac环境的python脚本,修订版,提交者以及他们的评论。

这是我使用的Python脚本。 有一件事情是我们对常规脚本做了额外的补充,我们使用了一个自定义字段(fixed_in_ver),我们的QA团队使用该字段来判断他们正在验证的修正是否在他们在QA中测试的代码版本中。 所以,我修改了python脚本中的代码来更新票证上的字段。 您可以删除该代码,因为您不需要它,但是如果您还想要更新Trac中的自定义字段,那么这是一个很好的示例。

我通过让用户在他们的评论中包含如下内容来做到这一点:

(版本2.1.2223.0)

然后,我使用python脚本使用正则表达式来获取信息的相同技术。 这不是太糟糕。

无论如何,这里是我使用的Python脚本,希望这是一个很好的教程,正是我所做的,让它在Windows世界中工作,所以你们都可以利用这个在你自己的商店…

如果您不想处理更新自定义字段的其他代码,请从上面的Craig提到的( Script From Edgewall )获取此位置的基本脚本,

 #!/usr/bin/env python # trac-post-commit-hook # ---------------------------------------------------------------------------- # Copyright (c) 2004 Stephen Hansen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # ---------------------------------------------------------------------------- # This Subversion post-commit hook script is meant to interface to the # Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc # system. # # It should be called from the 'post-commit' script in Subversion, such as # via: # # REPOS="$1" # REV="$2" # LOG=`/usr/bin/svnlook log -r $REV $REPOS` # AUTHOR=`/usr/bin/svnlook author -r $REV $REPOS` # TRAC_ENV='/somewhere/trac/project/' # TRAC_URL='http://trac.mysite.com/project/' # # /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \ # -p "$TRAC_ENV" \ # -r "$REV" \ # -u "$AUTHOR" \ # -m "$LOG" \ # -s "$TRAC_URL" # # It searches commit messages for text in the form of: # command #1 # command #1, #2 # command #1 & #2 # command #1 and #2 # # You can have more then one command in a message. The following commands # are supported. There is more then one spelling for each command, to make # this as user-friendly as possible. # # closes, fixes # The specified issue numbers are closed with the contents of this # commit message being added to it. # references, refs, addresses, re # The specified issue numbers are left in their current status, but # the contents of this commit message are added to their notes. # # A fairly complicated example of what you can do is with a commit message # of: # # Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12. # # This will close #10 and #12, and add a note to #12. import re import os import sys import time from trac.env import open_environment from trac.ticket.notification import TicketNotifyEmail from trac.ticket import Ticket from trac.ticket.web_ui import Ticketmodulee # TODO: move grouped_changelog_entries to model.py from trac.util.text import to_unicode from trac.web.href import Href try: from optparse import OptionParser except ImportError: try: from optik import OptionParser except ImportError: raise ImportError, 'Requires Python 2.3 or the Optik option parsing library.' parser = OptionParser() parser.add_option('-e', '--require-envelope', dest='env', default='', help='Require commands to be enclosed in an envelope. If -e[], ' 'then commands must be in the form of [closes #4]. Must ' 'be two characters.') parser.add_option('-p', '--project', dest='project', help='Path to the Trac project.') parser.add_option('-r', '--revision', dest='rev', help='Repository revision number.') parser.add_option('-u', '--user', dest='user', help='The user who is responsible for this action') parser.add_option('-m', '--msg', dest='msg', help='The log message to search.') parser.add_option('-c', '--encoding', dest='encoding', help='The encoding used by the log message.') parser.add_option('-s', '--siteurl', dest='url', help='The base URL to the project\'s trac website (to which ' '/ticket/## is appended). If this is not specified, ' 'the project URL from trac.ini will be used.') (options, args) = parser.parse_args(sys.argv[1:]) if options.env: leftEnv = '\\' + options.env[0] rghtEnv = '\\' + options.env[1] else: leftEnv = '' rghtEnv = '' commandPattern = re.compile(leftEnv + r'(?P<action>[A-Za-z]*).?(?P<ticket>#[0-9]+(?:(?:[, &]*|[ ]?and[ ]?)#[0-9]+)*)' + rghtEnv) ticketPattern = re.compile(r'#([0-9]*)') versionPattern = re.compile(r"\(version[ ]+(?P<version>([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+))\)") class CommitHook: _supported_cmds = {'close': '_cmdClose', 'closed': '_cmdClose', 'closes': '_cmdClose', 'fix': '_cmdClose', 'fixed': '_cmdClose', 'fixes': '_cmdClose', 'addresses': '_cmdRefs', 're': '_cmdRefs', 'references': '_cmdRefs', 'refs': '_cmdRefs', 'see': '_cmdRefs'} def __init__(self, project=options.project, author=options.user, rev=options.rev, msg=options.msg, url=options.url, encoding=options.encoding): msg = to_unicode(msg, encoding) self.author = author self.rev = rev self.msg = "(In [%s]) %s" % (rev, msg) self.now = int(time.time()) self.env = open_environment(project) if url is None: url = self.env.config.get('project', 'url') self.env.href = Href(url) self.env.abs_href = Href(url) cmdGroups = commandPattern.findall(msg) tickets = {} for cmd, tkts in cmdGroups: funcname = CommitHook._supported_cmds.get(cmd.lower(), '') if funcname: for tkt_id in ticketPattern.findall(tkts): func = getattr(self, funcname) tickets.setdefault(tkt_id, []).append(func) for tkt_id, cmds in tickets.iteritems(): try: db = self.env.get_db_cnx() ticket = Ticket(self.env, int(tkt_id), db) for cmd in cmds: cmd(ticket) # determine sequence number... cnum = 0 tm = Ticketmodulee(self.env) for change in tm.grouped_changelog_entries(ticket, db): if change['permanent']: cnum += 1 # get the version number from the checkin... and update the ticket with it. version = versionPattern.search(msg) if version != None and version.group("version") != None: ticket['fixed_in_ver'] = version.group("version") ticket.save_changes(self.author, self.msg, self.now, db, cnum+1) db.commit() tn = TicketNotifyEmail(self.env) tn.notify(ticket, newticket=0, modtime=self.now) except Exception, e: # import traceback # traceback.print_exc(file=sys.stderr) print>>sys.stderr, 'Unexpected error while processing ticket ' \ 'ID %s: %s' % (tkt_id, e) def _cmdClose(self, ticket): ticket['status'] = 'closed' ticket['resolution'] = 'fixed' def _cmdRefs(self, ticket): pass if __name__ == "__main__": if len(sys.argv) < 5: print "For usage: %s --help" % (sys.argv[0]) else: CommitHook() 

提交钩子生活在“钩子”目录中,在这个目录中,你将服务器端的版本库存放在这个目录中。 我不知道你的环境中有他们,所以这只是一个例子

例如(窗口):

 C:\Subversion\repositories\repo1\hooks\post-commit 

例如(llinux / unix):

 /usr/local/subversion/repositories/repo1/hooks/post-commit 

有一件事我会加上“猴子的答案是完美的” – 是要警惕这个(我的错误)

 :: Modify paths here: :: -- this one must be set SET TRAC_ENV=d:\trac\MySpecialProject :: -- set if Python is not in the system path :: SET PYTHON_PATH=**d:\python** :: -- set to the folder containing trac/ if installed in a non-standard location :: SET TRAC_PATH=**d:\python\Lib\site-packages\trac** 

我没有设置非系统路径,并花了我一段时间看到明显的:D

只要匹配,没有人会犯同样的错误! 感谢Code Monkey! D

首先非常感谢Code Monkey!

但是,取决于您的trac版本,获取正确的python脚本非常重要。 为了获得适当的版本,SVN检出文件夹:

http://svn.edgewall.com/repos/trac/branches/ xxx -stable / contrib

其中xxx对应于您正在使用的trac版本,例如:0.11

否则,你会得到一个提交后的错误,如下所示:

提交失败(详情如下):'/ svn / project / trunk / web / directory /'的MERGE:200 OK

对于想要安装最新trac(0.11.5)的所有Windows用户:请按照Trac站点上的说明TracOnWindows。

即使你有64位的Windows下载32位1.5 Python。 注意:我看了一些地方的说明如何编译trac在64位系统上本地工作。

当你安装所有需要的时候去储存库文件夹。 有文件夹挂钩。 在里面把文件Code Monkey提到,但是不像他那样创建“trac-post-commit-resolve-ticket-ref.py”。 接受Quant Analyst的建议,就像他说的那样:

“然而,根据你的trac版本来获取正确的python脚本是非常重要的,为了得到合适的版本,SVN检查这个文件夹: http : //svn.edgewall.com/repos/trac/branches/ xxx-stable / contrib其中xxx对应于您正在使用的trac版本,例如:0.11“

从那里下载文件“trac-post-commit-hook”并把它放在hooks文件夹中。

在trac-post-commit.cmd中编辑这些行

SET PYTHON_PATH =“python安装文件夹的路径”

SET TRAC_ENV =“你做tracd initenv的文件夹的路径”

记住没有最后\ !!!

我已经删除了最后一行-r“%REV%”的引号为-r%REV%,但是我不知道这是否需要。 这现在不起作用(至少在我的胜利2008年服务器),因为挂钩将失败(提交将确定)。 这与权限有关。 默认情况下权限是受限的,我们需要允许python或svn或trac(不管我不知道)来改变trac信息。 所以去你的trac文件夹,项目文件夹,db文件夹,右键单击trac.db并选择属性。 转到安全选项卡并编辑权限以允许所有人完全控制。 这不是很安全,但我整天浪费在这个安全问题,我不想浪费另一个只是为了找到哪个用户,你应该启用权限。

希望这可以帮助….