문제

나에서 실행되는 윈도우 환경 Trac/SVN 고 싶 커밋 저장소를 통합하 Trac 고 가까운 버그에 기록 SVN Comment.

내가 알고 있는 일부 게시 commit 후크를 할,하지만 많은 정보에 대해 그것을 어떻게 응용 프로그램을 시작합니다.

사람이 그것을 성공적으로?고 무엇이었는 단계를 따랐을 달성하기 위하여 그것은?

여기에 걸이요 두 SVN 지만,나는 정확하게 확인하는 방법이 Windows 환경에서.

Trac 게시 Commit 후크

도움이 되었습니까?

해결책 2

자,이제는 내가 약간의 시간을 경험한 후에 파악이 모두 밖으로 덕분에 크레이그 얻기 위해 나에게 오른쪽에는 트랙에 있습니다.여기에 당신이 무엇을 할 필요가(적어도 SVN v1.4Trac v0.10.3):

  1. 를 찾 SVN 저장소를 사용하도록 설정할 Post Commit 에 대한 후크.
  2. 내부 SVN 저장소가 있는 디렉토리라는 후크,이것은 당신이 배치 될 수있 후 commit 후크.
  3. 파일을 만들 post-다.bat(이하는 배치 파일을 자동으로 호출에 의해 SVN 게시 commit).
  4. 다음 코드가 내부에 post-다.bat 파일을(이 부를 것이 귀하의 게시물 commit cmd 파일을 전달하는 매개변수 SVN 자동으로 전달%1 저장소%2 는 개정된 노력했습니다.

%~dp0 rac-후 commit 후크.cmd%1%2

  1. 지금 만들기 trac-후 commit 후크.cmd 파일에 다음과 같다:

@ECHO OFF
::
::Trac post-commit 훅에 대한 스크립트 Windows
::
::에 기여 마르쿠스,수정 cboos.

::사용법:
::
::1)삽입 다음 줄에서 당신의 post-다.bat 스크립트
::
::전화 %~dp0 rac-후 commit 후크.cmd%1 %2
::
::2)체크하는'수정 경로를'섹션에서 아래를 설정해야 합니다 최소 TRAC_ENV


:: ----------------------------------------------------------
::수정할 수로 여기:

::-- 이 설정
설정 TRAC_ENV=C: rac\MySpecialProject

::--설정하는 경우에는 파이썬에 없 경로를 시스템
::설정 PYTHON_PATH=

::--설정 을 포함하는 폴더 trac/설치되어 있는 경우 에서 표준이 아닌 위치
::설정 TRAC_PATH=
:: ----------------------------------------------------------

::를 실행하지 않는 훅 경우 trac 환경에 존재하지 않는
하지 않을 경우 이 존재하%TRAC_ENV%GOTO:EOF

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

설정 REV=%2

::을 얻 작성자 로그 메시지
에 대한/F %%A('svnlook 저자-r%REV%%1') 설정 저자=%%A
에 대한/F "delims=="%%B('svnlook log-r %REV%%1')설정 로그인=%%B

::전화 PYTHON 스크립트
Python "%~dp0 rac-후 commit-hook"-p "%TRAC_ENV%"-r"%REV%"u"%저%" -m"%로그%"

가장 중요한 부분에 여기를 설정하 TRAC_ENV 는 저장소에 대한 경로를 뿌리(설정 TRAC_ENV=C: rac\MySpecialProject)

다음 주요 중요한 것은 이 스크립트는 다음 작업을 수행:

::을 얻을 작성자 로그인 메시지
에 대한/F%%A('svnlook 저자-r%REV%%1')설정 저자=%%A
에 대한/F"delims=="%%B 에('svnlook log-r%REV%%1')설정 LOG=%%B

당신이 볼 스크립트 파일에서 위의 내용 svnlook(는 유틸리티와 SVN)을 얻을 로그 메시지를 그리고 저자는 이에 투입합니다.

그 다음으로 라인의 스크립트 실제로 부르는 파이썬을 수행하는 코드를 폐쇄 티켓 및 분석 로그 메시지입니다.나는 수정이 전달하는 로그에 메시지를 그리고 저자(는 사용자 이름에서 사용 Trac 경기는 사용자 이름에서 SVN 도록 쉽).

전화 PYTHON 스크립트
Python "%~dp0 rac-후 commit-hook"-p "%TRAC_ENV%"-r"%REV%"u"%저%" -m"%로그%"

위의 라인에서 스크립트를 통과할 것으로 python 스크립트 Trac 환경을 개정하는 사람을 만들어 커미,그리고 그들의 코멘트입니다.

여기에는 Python 스크립트는 내가 사용됩니다.개국 고객들의 추가 일정한 스크립트가 우리가 사용하는 사용자 정의 필드(fixed_in_ver)에 의해 사용되는 품질보증 팀을 말한 경우에는 수정은 그들이 유효성 검사에 이 버전은 코드들을 테스트에서 품질보증을 수행합니다.그래서 저는 코드를 수정하에서 python 스크립트를 업데이트하는 분야 티켓에.를 제거할 수 있는 코드로 당신이 그것을 필요하지 않습니다만,그것의 좋은 예를 들어 당신은 무엇을 할 수 있을 업데이트 사용자 정의 필드에서 Trac 는 경우에 당신은 또한 당신하고 싶다.

았다는함으로써 사용자 선택적으로 포함에서 자신의 댓글을 다음과 같습니다.

(버전 2.1.2223.0)

나는 다음을 사용하는 것과 동일한 기술 python 스크립트를 사용하여 정기적인 표현하는 정보를 얻을 수니다.그것은 너무 나쁘지 않았습니다.

어쨌든,여기에 python 스크립트가 사용하는 희망이 좋은 튜토리얼에서 정확히 무엇을 했는지,그것을 얻을 작동하는 세계에서 그래서 당신은 모든 활용할 수 있습니다 이 자신의 가게에서...

당신이 원하지 않는 경우를 다루는 내 추가 코드에 대한 업데이트 사용자 정의 필드를 얻을,베이스 스크립트에서 이 위치에 의해 언급 크레이그의 위(스크립트에서 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()

다른 팁

벤자민의 대답은 가깝지만,Windows 을 제공하는 데 필요한 훅 스크립트 파일을 실행 파일 확장자 등을 갖추고 있습니다.bat 로 하시는지.cmd.내가 사용합니다.cmd.취할 수 있는 템플 스크립트는 유닉스 쉘 스크립트,쉘 스크립트로 변환합니다.bat/.cmd 문입니다.

하지만 질문에 대답하의 통합 Trac,다음과 같이 하십시오.

  1. 는지 확인 Python.exe 은 시스템에 있는 경로입니다.이 당신의 인생을 더 쉽게 만들 것입니다.

  2. 을 만들 post-다.cmd\후크 폴더에 있습니다.이는 실제적인 훅는 스크립트 파괴에서 실행됩 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. 을 만들 trac-post-다.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. 성 trac-post-commit-resolve-ticket-ref.py 에\후크 폴더에 있습니다.내가 사용하는 같은 스크립트에서 EdgeWall, 만 내가 이름을 더 명확히 그것의 목적이 있다.

게시 commit 후크에서 라이브"후크"디렉토리는 이제까지 당신은 저장소 생활에서 server side.나는 어디 있는지 몰라 당신은 그들이 환경에서,그래서 이것은 단지 예입니다

예:(windows):

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

그냥 일치하지 아무도 다른 사람은 동일한 실수!감사 코드는 원숭이!1,000,000,000 에 포인트:D

첫째로 큰 덕분에 코드는 원숭이!

그러나,그것의 중요한 권리를 얻 python 스크립트에 따라 trac 버전입니다.을 얻을 적절한 버전,SVN 체크아웃 폴더:

http://svn.edgewall.com/repos/trac/branches/xxx안정/contrib

xxx 에 해당하 trac 버전을 사용하여,예를 들어:0.11

그렇지 않으면 당신이 얻을 게시하는 오류는 다음과 같습니다.

커밋하지 못했(상세정보를 따릅):병합의'/svn/프로젝트/트렁크/web/디렉터리/':200OK

에 대한 모든 창을하고자하는 사용자 설치를 최신 trac(0.11.5):의 지침에 따라 Trac 의 사이트는 이름 TracOnWindows.

다운로드 32bit1.5Python 이 있는 경우 64 비트 윈도우.참고:나는 보았다 어딘가의 지침을 컴파일하는 방법 trac 을 기본적으로 작동하에서 64 비트 시스템입니다.

설치할 때 필요한 모든 것은 이동하는 저장소의 폴더에 있습니다.있는 폴더의 후크.그 안에 넣어 파일 코드는 원숭이 언급했지 만들기"trac-post-commit-resolve-ticket-ref.py"좋아했습니다.을에서 조언을 퀀트분석과 마음 그는 말했다:

"그러나,그것의 중요한 권리를 얻 python 스크립트에 따라 trac 버전입니다.을 얻을 적절한 버전,SVN 체크아웃 폴더:http://svn.edgewall.com/repos/trac/branches/xxx-안정/contrib xxx 에 해당하 trac 버전을 사용하여,예를 들어:0.11"

거기에서 downoad 파일"trac-후 commit-hook"에 넣어 후크 폴더에 있습니다.

편집 이 라인에서 trac-post-다.cmd

설정 PYTHON_PATH="파이썬 경로는 설치 폴더"

설정 TRAC_ENV="경로의 폴더에 당신 았다 tracd initenv"

시 기억지 아니하리라 하는 마지막\!!!

나는 따옴표를 제거에서 마지막 줄-r"%REV%"될-r%REV%지는 않지만 알고 있는 경우 이 필요합니다.이 작동하지 않습니다 이제(도에 승 2008server)기 때문에,후크 실패(commit 갈 것이 확인).함께 할 수 있어 권한이 있습니다.기본적으로 권한을 제한하고 우리가 필요한을 허용하는 파이썬 또는 svn 또는 trac(어떤 모르겠어)를 변경 trac 정보입니다.그래서 trac 폴더의 프로젝트 폴더,db 폴더를 마우스 오른쪽 클릭 trac.db 고 속성을 선택합니다.보안 탭으로 이동하고 편집할 수 있는 권한을 모두 완벽하게 제어할 수 있습니다.이 되지 않도록 안전하지만 나는 낭비되는 모든 일에 보안 문제이고 내가고 싶지 않은 다른 낭만을 찾는 사용자가 사용하도록 설정해야 합 권한이 있습니다.

이게 도움이 되었으면 좋겠습니다....

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top