簡體   English   中英

如何在Windows環境中使用Trac和SVN實現Post Commit Hook?

[英]How do I implement the Post Commit Hook with Trac & SVN in a Windows Environment?

我正在使用Trac / SVN在Windows環境中運行,我希望提交到存儲庫以集成到Trac並關閉SVN Comment中記錄的錯誤。

我知道有一些帖子提交鈎子可以做到這一點,但沒有太多關於如何在Windows上執行此操作的信息。

有人成功完成了嗎? 你實現了它的步驟是什么?

這是我需要在SVN中使用的鈎子,但我不確定如何在Windows環境中執行此操作。

Trac Post Commit Hook

Benjamin的答案很接近,但在Windows上,您需要為鈎子腳本文件提供可執行的擴展名,例如.bat或.cmd。 我用.cmd。 您可以使用模板腳本,它們是unix shell腳本,shell腳本並將它們轉換為.bat / .cmd語法。

但要回答與Trac集成的問題,請按照以下步驟操作。

  1. 確保Python.exe位於系統路徑上。 這將使您的生活更輕松。

  2. 在\\ hooks文件夾中創建post-commit.cmd。 這是Subversion將在提交后事件上執行的實際鈎子腳本。

     @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中的相同腳本 ,只是我重命名它以更好地闡明其目的。

好吧,現在我已經有了一些時間來發布我的經驗,並且感謝Craig讓我走上了正確的軌道。 這是你需要做的事情(至少對於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 OFF
::
::適用於Windows的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
for / F“delims ==”%% B in('svnlook log -r%REV %% 1')設置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
for / F“delims ==”%% B in('svnlook log -r%REV %% 1')設置LOG = %% B

如果你在上面的腳本文件中看到我正在使用svnlook(這是一個帶有SVN的命令行實用程序)來獲取LOG消息和提交到存儲庫的作者。

然后,腳本的下一行實際上是調用Python代碼來執行票證的關閉並解析日志消息。 我必須修改它以傳遞Log消息和作者(我在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 TicketModule
# 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 = TicketModule(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()

有一件事我會添加“Code Monkey的答案是完美的” - 是要警惕(我的錯誤)

:: 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! 10億點: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%但我不知道是否需要這樣做。 現在這不起作用(至少在我的win 2008服務器上),因為hook會失敗(提交就行了)。 這與權限有關。 默認情況下,權限受到限制,我們需要允許python或svn或trac(我不知道)改變trac信息。 所以轉到你的trac文件夾,項目文件夾,db文件夾,右鍵單擊trac.db並選擇屬性。 轉到安全選項卡並編輯權限以允許每個人完全控制。 這不是那么安全,但我整天浪費在這個安全問題上,我不想浪費另一個只是為了找到你應該啟用權限的用戶。

希望這可以幫助....

后提交掛鈎存在於“hooks”目錄中,在該目錄中,存儲庫位於服務器端。 我不知道你的環境在哪里,所以這只是一個例子

例如(窗口):

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

例如(llinux / unix):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM