6

Trac / SVN を使用して Windows 環境で実行しています。リポジトリへのコミットを Trac に統合し、SVN コメントに記載されているバグをクローズする必要があります。

それを行うためのコミット後のフックがいくつかあることは知っていますが、Windowsでそれを行う方法についての情報はあまりありません。

成功した人いますか?また、それを達成するためにどのような手順を踏んだのですか?

これがSVNに配置する必要があるフックですが、Windows環境でこれを行う方法が正確にはわかりません。

Trac ポスト コミット フック

4

6 に答える 6

4

Benjamin の答えは近いですが、Windows では、フック スクリプト ファイルに .bat や .cmd などの実行可能な拡張子を付ける必要があります。.cmd を使用します。テンプレート スクリプト (UNIX シェル スクリプト、シェル スクリプト) を取得して、それらを .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 の同じスクリプトを使用しましたが、目的を明確にするために名前を変更しただけです。

于 2008-09-17T16:33:54.833 に答える
3

さて、これをすべて理解した後、私の経験を投稿する時間ができたので、正しい軌道に乗せてくれたCraigに感謝します. 必要なことは次のとおりです (少なくとも SVN v1.4 と Trac v0.10.3 では):

  1. Post Commit フックを有効にする SVN リポジトリを見つけます。
  2. SVN リポジトリ内に hooks というディレクトリがあり、ここに post commit フックを配置します。
  3. ファイル post-commit.bat を作成します (これは、SVN post commit によって自動的に呼び出されるバッチ ファイルです)。
  4. 次のコードを post-commit.bat ファイル内に配置します (これにより、SVN が自動的に渡すパラメーターを渡す post commit cmd ファイルが呼び出されます。%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 環境が存在しない場合はフックを実行しない
IF NOT EXIST % TRAC_ENV% GOTO :EOF

set PATH=%PYTHON_PATH%;%PATH%
set PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%

SET REV=%2

:: GET THE AUTHOR AND THE LOG MESSAGE
for /F %%A in ('svnlook author -r %REV% %1') do set AUTHOR=%%A
for /F "delims==" %%B in ('svnlook log -r %REV% %1') do set LOG=%%B

:: PYTHON スクリプト
を呼び出す Python "%~dp0\trac-post-commit-hook" -p "%TRAC_ENV%" -r "%REV%" -u "%AUTHOR%" -m "%ログ%"

ここで最も重要な部分は、リポジトリ ルートへのパスである TRAC_ENV を設定することです (SET TRAC_ENV=C:\trac\MySpecialProject)。

このスクリプトで次に重要なことは、次のことを行うことです。

:: GET THE AUTHOR AND THE LOG MESSAGE
for /F %%A in ('svnlook author -r %REV% %1') do set AUTHOR=%%A
for /F "delims==" %%B in (' svnlook log -r %REV% %1') do set LOG=%%B

上記のスクリプト ファイルを見ると、svnlook (SVN のコマンド ライン ユーティリティ) を使用してログ メッセージと、リポジトリにコミットした作成者を取得しています。

次に、スクリプトの次の行で実際に Python コードを呼び出して、チケットのクローズを実行し、ログ メッセージを解析しています。これを変更して、ログ メッセージと作成者を渡す必要がありました (Trac で使用するユーザー名は SVN のユーザー名と一致するため、簡単でした)。

PYTHON スクリプト
を呼び出す Python "%~dp0\trac-post-commit-hook" -p "%TRAC_ENV%" -r "%REV%" -u "%AUTHOR%" -m "%LOG%"

スクリプトの上記の行は、Trac 環境、リビジョン、コミットを行った人物、およびそのコメントを Python スクリプトに渡します。

これが私が使用したPythonスクリプトです。通常のスクリプトに加えて行ったことの 1 つは、カスタム フィールド (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()
于 2008-09-21T04:28:19.530 に答える
0

最新の trac (0.11.5) をインストールしたいすべての Windows ユーザーの場合: TracOnWindows という名前の Trac のサイトの指示に従ってください。

64 ビット Windows を使用している場合でも、32 ビット 1.5 Python をダウンロードしてください。注: 64 ビット システムでネイティブに動作するように trac をコンパイルする方法をどこかで見ました。

必要なものをすべてインストールしたら、リポジトリ フォルダに移動します。フォルダーフックがあります。その中に 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サーバーでは)機能しません。これはパーミッションと関係があります。デフォルトでは権限が制限されており、python、svn、または trac (私が知らないものは何でも) が trac 情報を変更できるようにする必要があります。trac フォルダ、プロジェクト フォルダ、db フォルダに移動し、trac.db を右クリックしてプロパティを選択します。セキュリティ タブに移動し、アクセス許可を編集して、全員が完全に制御できるようにします。これはあまり安全ではありませんが、私はこのセキュリティの問題で一日を無駄にしました。どのユーザーに対してアクセス許可を有効にする必要があるかを見つけるためだけに、別の時間を無駄にしたくありません。

お役に立てれば....

于 2009-08-21T02:50:34.023 に答える
0

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

于 2009-08-02T20:22:03.290 に答える
0

ポスト コミット フックは、サーバー側にリポジトリが存在する「hooks」ディレクトリにあります。あなたの環境のどこにあるのかわからないので、これは単なる例です

例 (Windows):

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

例 (llinux/unix):

/usr/local/subversion/repositories/repo1/hooks/post-commit
于 2008-09-17T15:13:17.227 に答える