Edgewall Software

TracMultipleProjects/ComprehensiveSolution: trac-post-commit-hook

File trac-post-commit-hook, 9.1 KB (added by Dave Abrahams <dave@…>, 7 years ago)

SVN post-commit hook augmented to recognize strings of the form project:ticket

Line 
1#!/usr/bin/env python
2
3# trac-post-commit-hook
4# ----------------------------------------------------------------------------
5# Copyright (c) 2004 Stephen Hansen
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to
9# deal in the Software without restriction, including without limitation the
10# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11# sell copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14#   The above copyright notice and this permission notice shall be included in
15#   all copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23# IN THE SOFTWARE.
24# ----------------------------------------------------------------------------
25
26# This Subversion post-commit hook script is meant to interface to the
27# Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc
28# system.
29#
30# It should be called from the 'post-commit' script in Subversion, such as
31# via:
32#
33# REPOS="$1"
34# REV="$2"
35# LOG=`/usr/bin/svnlook log -r $REV $REPOS`
36# AUTHOR=`/usr/bin/svnlook author -r $REV $REPOS`
37# TRAC_ENV='/somewhere/trac/project/'
38# TRAC_URL='http://trac.mysite.com/project/'
39#
40# /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \
41#  -p "$TRAC_ENV"  \
42#  -r "$REV"       \
43#  -u "$AUTHOR"    \
44#  -m "$LOG"       \
45#  -s "$TRAC_URL"
46#
47# It searches commit messages for text in the form of:
48#   command #1
49#   command #1, #2
50#   command #1 & #2
51#   command #1 and #2
52#
53# Instead of the short-hand syntax "#1", "ticket:1" can be used as well, e.g.:
54#   command ticket:1
55#   command ticket:1, ticket:2
56#   command ticket:1 & ticket:2
57#   command ticket:1 and ticket:2
58#
59# In addition, the ':' character can be omitted and issue or bug can be used
60# instead of ticket.
61#
62# You can have more then one command in a message. The following commands
63# are supported. There is more then one spelling for each command, to make
64# this as user-friendly as possible.
65#
66#   close, closed, closes, fix, fixed, fixes
67#     The specified issue numbers are closed with the contents of this
68#     commit message being added to it.
69#   references, refs, addresses, re, see
70#     The specified issue numbers are left in their current status, but
71#     the contents of this commit message are added to their notes.
72#
73# A fairly complicated example of what you can do is with a commit message
74# of:
75#
76#    Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.
77#
78# This will close #10 and #12, and add a note to #12.
79
80import re
81import os
82import sys
83from datetime import datetime
84
85from trac.env import open_environment
86from trac.ticket.notification import TicketNotifyEmail
87from trac.ticket import Ticket
88from trac.ticket.web_ui import TicketModule
89# TODO: move grouped_changelog_entries to model.py
90from trac.util.text import to_unicode
91from trac.util.datefmt import utc
92from trac.versioncontrol.api import NoSuchChangeset
93
94from optparse import OptionParser
95
96parser = OptionParser()
97depr = '(not used anymore)'
98parser.add_option('-e', '--require-envelope', dest='envelope', default='',
99                  help="""
100Require commands to be enclosed in an envelope.
101If -e[], then commands must be in the form of [closes #4].
102Must be two characters.""")
103parser.add_option('-p', '--project', dest='project',
104                  help='Path to the Trac project.')
105parser.add_option('-r', '--revision', dest='rev',
106                  help='Repository revision number.')
107parser.add_option('-u', '--user', dest='user',
108                  help='The user who is responsible for this action '+depr)
109parser.add_option('-m', '--msg', dest='msg',
110                  help='The log message to search '+depr)
111parser.add_option('-c', '--encoding', dest='encoding',
112                  help='The encoding used by the log message '+depr)
113parser.add_option('-s', '--siteurl', dest='url',
114                  help=depr+' the base_url from trac.ini will always be used.')
115
116(options, args) = parser.parse_args(sys.argv[1:])
117
118
119svnlog = None
120def log(*args):
121    global svnlog
122    if svnlog is None:
123        svnlog = open('/var/log/svnlog', 'a+',0)
124    for x in args:
125        print  >> svnlog, x,
126    print >> svnlog
127
128env_id = '[^:/ ]+'
129ticket_prefix = '(?:#|(?:ticket|issue|bug)[: ]?)'
130ticket_reference = '(?:%s:)?' % env_id + ticket_prefix + '[0-9]+'
131ticket_command =  (r'(?P<action>[A-Za-z]*).?'
132                   '(?P<ticket>%s(?:(?:[, &]*|[ ]?and[ ]?)%s)*)' %
133                   (ticket_reference, ticket_reference))
134
135if options.envelope:
136    ticket_command = r'\%s%s\%s' % (options.envelope[0], ticket_command,
137                                    options.envelope[1])
138# log('initializing patterns...')
139command_re = re.compile(ticket_command)
140ticket_re = re.compile('(?:(%s):)?' % env_id + ticket_prefix + '([0-9]+)')
141# log('done')
142
143class CommitHook:
144    _supported_cmds = {'close':      '_cmdClose',
145                       'closed':     '_cmdClose',
146                       'closes':     '_cmdClose',
147                       'fix':        '_cmdClose',
148                       'fixed':      '_cmdClose',
149                       'fixes':      '_cmdClose',
150                       'addresses':  '_cmdRefs',
151                       're':         '_cmdRefs',
152                       'references': '_cmdRefs',
153                       'refs':       '_cmdRefs',
154                       'see':        '_cmdRefs'}
155
156    def __init__(self, project=options.project, author=options.user,
157                 rev=options.rev, url=options.url):
158        # log('opening default environment:', project)
159        self.env = open_environment(project)
160        repos = self.env.get_repository()
161        repos.sync()
162       
163        # Instead of bothering with the encoding, we'll use unicode data
164        # as provided by the Trac versioncontrol API (#1310).
165        try:
166            chgset = repos.get_changeset(rev)
167        except NoSuchChangeset:
168            return # out of scope changesets are not cached
169        self.author = chgset.author
170        self.rev = rev
171        self.msg = "(In [%s]) %s" % (rev, chgset.message)
172        self.now = datetime.now(utc)
173
174        cmd_groups = command_re.findall(self.msg)
175        # log('cmd_groups=', cmd_groups)
176       
177        project_root, project_name = os.path.split(project)
178        if project_name == '': # deal with a possible trailing slash
179            project_root, project_name = os.path.split(project_root)
180           
181       
182        tracs = {}
183        for cmd, tkts in cmd_groups:
184            funcname = CommitHook._supported_cmds.get(cmd.lower(), '')
185            if funcname:
186                for trac_id,tkt_id in ticket_re.findall(tkts):
187                    # log('trac_id=', trac_id, 'tkt_id=', tkt_id)
188                    func = getattr(self, funcname)
189                    if not trac_id:
190                        trac_id = project_name
191                    tracs.setdefault(trac_id, {}).setdefault(tkt_id, []).append(func)
192           
193        for trac, tickets in tracs.iteritems():
194            if trac != project_name:
195                self.env = open_environment(
196                    os.path.join(project_root,trac))
197
198            for tkt_id, cmds in tickets.iteritems():
199                try:
200                    db = self.env.get_db_cnx()
201
202                    ticket = Ticket(self.env, int(tkt_id), db)
203                    for cmd in cmds:
204                        cmd(ticket)
205
206                    # determine sequence number...
207                    cnum = 0
208                    tm = TicketModule(self.env)
209                    for change in tm.grouped_changelog_entries(ticket, db):
210                        if change['permanent']:
211                            cnum += 1
212
213                    ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)
214                    db.commit()
215
216                    tn = TicketNotifyEmail(self.env)
217                    tn.notify(ticket, newticket=0, modtime=self.now)
218                except Exception, e:
219                    # import traceback
220                    # traceback.print_exc(file=sys.stderr)
221                    # log('Unexpected error while processing ticket ID %s: %s' % (tkt_id, e))
222                    print>>sys.stderr, 'Unexpected error while processing ticket ' \
223                                       'ID %s: %s' % (tkt_id, e)
224           
225
226    def _cmdClose(self, ticket):
227        ticket['status'] = 'closed'
228        ticket['resolution'] = 'fixed'
229
230    def _cmdRefs(self, ticket):
231        pass
232
233
234if __name__ == "__main__":
235    if len(sys.argv) < 5:
236        # log('failed...')
237        print "For usage: %s --help" % (sys.argv[0])
238        print
239        print "Note that the deprecated options will be removed in Trac 0.12."
240    else:
241        # log('doing hook...')
242        CommitHook()