Domanda

Sto eseguendo un ambiente Windows con Trac/SVN e desidero che i commit nel repository si integrino in Trac e chiudano i bug annotati nel commento SVN.

So che ci sono alcuni hook post commit per farlo, ma non ci sono molte informazioni su come farlo su Windows.

Qualcuno lo ha fatto con successo?E quali sono stati i passi che hai seguito per raggiungerlo?

Ecco l'hook che devo inserire in SVN, ma non sono esattamente sicuro di come farlo in ambiente Windows.

Gancio di commit del post Trac

È stato utile?

Soluzione 2

Va bene, ora che ho un po' di tempo per pubblicare la mia esperienza dopo aver capito tutto, e grazie a Craig per avermi messo sulla strada giusta.Ecco cosa devi fare (almeno con SVN v1.4 e Trac v0.10.3):

  1. Individua il repository SVN per il quale desideri abilitare il Post Commit Hook.
  2. all'interno del repository SVN c'è una directory chiamata hooks, qui è dove posizionerai l'hook post commit.
  3. creare un file post-commit.bat (questo è il file batch che viene automaticamente chiamato da SVN post commit).
  4. Inserisci il seguente codice all'interno del file post-commit.bat (questo chiamerà il tuo file cmd post commit passando i parametri che SVN passa automaticamente %1 è il repository, %2 è la revisione che è stata sottoposta a commit.

%~dp0 rac-post-commit-hook.cmd %1 %2

  1. Ora crea il file trac-post-commit-hook.cmd come segue:

@ECHO DISATTIVATO
::
::Script post-commit-hook TRAC per Windows
::
::Contributo da Markus, modificato da CBOO.

::Utilizzo:
::
::1) Inserire la seguente riga nello script post-commit.bat
::
::Call %~ dp0 trac-post-commit-hook.cmd %1 %2
::
::2) Controllare la sezione "Modifica percorsi" di seguito, assicurati di impostare almeno TRAC_ENV


:: ----------------------------------------------------------
::Modifica i percorsi qui:

::-- Questo dovere essere impostato
Imposta Trac_env = c: trac myspecialProject

::- Imposta se Python non è nel percorso del sistema
::Imposta python_path =

::-Imposta sulla cartella contenente TRAC/ Se installato in una posizione non standard
::Imposta trac_path =
:: ----------------------------------------------------------

::Non eseguire un gancio se non esiste un ambiente TRAC
In caso contrario

imposta PERCORSO=%PYTHON_PATH%;%PATH%
Imposta pythonpath =%trac_path%;%pythonpath%

IMPOSTA REV=%2

::Ottieni l'autore e il messaggio di registro
per /f %% a in ('svnlook auto -r%rev%1') imposta autore = %% a
per /f "delims ==" %% b in ('svnlook log -r%rev%1') set log = %% b

::CHIAMA LO SCRIPT PYTHON
Python "%~ dp0 trac -post -commit -hook" -p "%trac_env%" -r "%rev%" -u "%autore%" -m "%log%"

La parte più importante qui è impostare TRAC_ENV che è il percorso alla radice del repository (SET TRAC_ENV=C: rac\MySpecialProject)

La prossima COSA MOLTO IMPORTANTE in questo script è fare quanto segue:

::Ottieni l'autore e il messaggio di registro
per /f %% a in ('svnlook auto -r%rev%1') imposta autore = %% a
per /f "delims ==" %% b in ('svnlook log -r%rev%1') set log = %% b

se vedi nel file di script sopra, sto usando svnlook (che è un'utilità da riga di comando con SVN) per ottenere il messaggio LOG e l'autore che ha effettuato il commit nel repository.

Quindi, la riga successiva dello script chiama effettivamente il codice Python per eseguire la chiusura dei ticket e analizzare il messaggio di log.Ho dovuto modificarlo per passare il messaggio di registro e l'autore (i nomi utente che utilizzo in Trac corrispondono ai nomi utente in SVN, quindi è stato facile).

CHIAMA LO SCRIPT PYTHON
Python "%~ dp0 trac -post -commit -hook" -p "%trac_env%" -r "%rev%" -u "%autore%" -m "%log%"

La riga sopra nello script passerà nello script Python l'ambiente Trac, la revisione, la persona che ha effettuato il commit e il suo commento.

Ecco lo script Python che ho usato.Una cosa che ho fatto in aggiunta allo script normale è l'utilizzo di un campo personalizzato (fixed_in_ver) utilizzato dal nostro team QA per stabilire se la correzione che stanno convalidando è nella versione del codice che stanno testando nel QA.Quindi, ho modificato il codice nello script Python per aggiornare quel campo sul ticket.Puoi rimuovere quel codice perché non ne avrai bisogno, ma è un buon esempio di cosa puoi fare per aggiornare i campi personalizzati in Trac se vuoi farlo anche tu.

L'ho fatto chiedendo agli utenti di includere facoltativamente nel loro commento qualcosa come:

(versione 2.1.2223.0)

Quindi utilizzo la stessa tecnica utilizzata dallo script Python con le espressioni regolari per ottenere le informazioni.Non era poi così male.

Ad ogni modo, ecco lo script Python che ho usato. Spero che questo sia un buon tutorial su esattamente cosa ho fatto per farlo funzionare nel mondo Windows in modo che tutti voi possiate sfruttarlo nel vostro negozio...

Se non vuoi occuparti del mio codice aggiuntivo per l'aggiornamento del campo personalizzato, ottieni lo script di base da questa posizione come menzionato sopra da Craig (Script da 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()

Altri suggerimenti

La risposta di Benjamin è vicina, ma su Windows è necessario fornire ai file dello script di hook un'estensione eseguibile, come .bat o .cmd.Io uso .cmd.Puoi prendere gli script modello, che sono script di shell unix, script di shell e convertirli nella sintassi .bat/.cmd.

Ma per rispondere alla domanda sull'integrazione con Trac, segui questi passaggi.

  1. Assicurarsi che Python.exe sia nel percorso di sistema.Questo ti renderà la vita più facile.

  2. Crea post-commit.cmd nella cartella \hooks.Questo è l'effettivo hook script che Subversion eseguirà sull'evento 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. Crea trac-post-commit.cmd nella cartella \hooks:

    @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. Crea trac-post-commit-resolve-ticket-ref.py nella cartella \hooks.ero solito lo stesso script di EdgeWall, solo che l'ho rinominato per chiarirne meglio lo scopo.

Gli hook di commit post risiedono nella directory "hooks" ovunque tu abbia il repository che vive sul lato server.Non so dove li hai nel tuo ambiente, quindi questo è solo un esempio

per esempio.(finestre):

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

per esempio.(Linux/Unix):

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

Una cosa che aggiungerò "La risposta di Code Monkey è PERFETTA" è diffidare di questo (errore mio)

:: 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**

Non avevo impostato i percorsi non di sistema e mi ci è voluto un po' per vedere l'ovvio: D

Assicurati solo che nessun altro commetta lo stesso errore!Grazie Code Monkey!1000000000 punti :D

Innanzitutto un grande ringraziamento a Code Monkey!

Tuttavia, è importante ottenere lo script Python corretto a seconda della versione di Trac.Per ottenere la versione appropriata, SVN controlla la cartella:

http://svn.edgewall.com/repos/trac/branches/xxx-stabile/contributo

Dove xxx corrisponde alla versione trac che stai utilizzando, ad esempio:0,11

Altrimenti riceverai un errore post-commit simile al seguente:

commit non riuscito (segue i dettagli):UNISCI di '/svn/project/trunk/web/directory/':200 ok

Per tutti gli utenti Windows che desiderano installare il trac più recente (0.11.5):Seguire le istruzioni sul sito di Trac denominato TracOnWindows.

Scarica Python 1.5 a 32 bit anche se hai Windows a 64 bit.Nota:Ho visto da qualche parte le istruzioni su come compilare trac per funzionare in modo nativo su un sistema a 64 bit.

Quando installi tutto ciò che è richiesto, vai alla cartella del repository.Ci sono ganci per cartelle.Al suo interno inserisci i file menzionati da Code Monkey, ma non creare "trac-post-commit-resolve-ticket-ref.py" come ha fatto lui.Chiedi consiglio a Quant Analyst e fai come ha detto:

"Tuttavia, è importante ottenere lo script Python corretto a seconda della versione di Trac.Per ottenere la versione appropriata, SVN controlla la cartella:http://svn.edgewall.com/repos/trac/branches/XXX-STABLE/APPATTO DOVE XXX corrisponde alla versione TRAC che stai utilizzando, ad esempio:0,11"

Da lì scarica il file "trac-post-commit-hook" e inseriscilo nella cartella degli hook.

Modifica queste righe in trac-post-commit.cmd

SET PYTHON_PATH="Percorso della cartella di installazione di Python"

Imposta Trac_env = "Path to Folder in cui hai fatto TRACD INITENV"

Non ricordare l'ultimo \ !!!

Ho rimosso le virgolette dall'ultima riga -r "%REV%" per essere -r %REV% ma non so se sia necessario.Questo non funzionerà ora (almeno sul mio server Win 2008), perché l'hook fallirà (il commit andrà bene).Questo ha a che fare con i permessi.Per impostazione predefinita le autorizzazioni sono limitate e dobbiamo consentire a Python, svn o trac (qualunque cosa non conosca) di modificare le informazioni di trac.Quindi vai alla cartella trac, alla cartella del progetto, alla cartella db, fai clic con il pulsante destro del mouse su trac.db e scegli Proprietà.Vai alla scheda Sicurezza e modifica le autorizzazioni per consentire a tutti il ​​pieno controllo.Non è così sicuro, ma ho sprecato tutto il giorno su questa questione di sicurezza e non voglio sprecarne un altro solo per scoprire per quale utente dovresti abilitare le autorizzazioni.

Spero che questo ti aiuti....

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top