Edgewall Software

Ticket #3464: trac-post-commit-hook.2

File trac-post-commit-hook.2, 7.8 KB (added by viktor@…, 2 years ago)

updated to trunk version, the previous was from 0.9.5

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# You can have more then one command in a message. The following commands
54# are supported. There is more then one spelling for each command, to make
55# this as user-friendly as possible.
56#
57#   closes, fixes
58#     The specified issue numbers are closed with the contents of this
59#     commit message being added to it.
60#   references, refs, addresses, re
61#     The specified issue numbers are left in their current status, but
62#     the contents of this commit message are added to their notes.
63#
64# A fairly complicated example of what you can do is with a commit message
65# of:
66#
67#    Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.
68#
69# This will close #10 and #12, and add a note to #12.
70
71import re
72import os
73import sys
74import time 
75
76from trac.env import open_environment
77from trac.ticket.notification import TicketNotifyEmail
78from trac.ticket import Ticket
79from trac.ticket.web_ui import TicketModule
80# TODO: move grouped_changelog_entries to model.py
81from trac.web.href import Href
82
83try:
84    from optparse import OptionParser
85except ImportError:
86    try:
87        from optik import OptionParser
88    except ImportError:
89        raise ImportError, 'Requires Python 2.3 or the Optik option parsing library.'
90
91parser = OptionParser()
92parser.add_option('-e', '--require-envelope', dest='env', default='',
93                  help='Require commands to be enclosed in an envelope. If -e[], '
94                       'then commands must be in the form of [closes #4]. Must '
95                       'be two characters.')
96parser.add_option('-p', '--project', dest='project',
97                  help='Path to the Trac project.')
98parser.add_option('-r', '--revision', dest='rev',
99                  help='Repository revision number.')
100parser.add_option('-u', '--user', dest='user',
101                  help='The user who is responsible for this action')
102parser.add_option('-m', '--msg', dest='msg',
103                  help='The log message to search.')
104parser.add_option('-f', '--msgfile', dest='file', 
105                  help='The file containing log message to search.')                 
106parser.add_option('-s', '--siteurl', dest='url',
107                  help='The base URL to the project\'s trac website (to which '
108                       '/ticket/## is appended).  If this is not specified, '
109                       'the project URL from trac.ini will be used.')
110
111(options, args) = parser.parse_args(sys.argv[1:])
112
113if options.env:
114    leftEnv = '\\' + options.env[0]
115    rghtEnv = '\\' + options.env[1]
116else:
117    leftEnv = ''
118    rghtEnv = ''
119
120commandPattern = re.compile(leftEnv + r'(?P<action>[A-Za-z]*).?(?P<ticket>#[0-9]+(?:(?:[, &]*|[ ]?and[ ]?)#[0-9]+)*)' + rghtEnv)
121ticketPattern = re.compile(r'#([0-9]*)')
122
123class CommitHook:
124    _supported_cmds = {'close':      '_cmdClose',
125                       'closed':     '_cmdClose',
126                       'closes':     '_cmdClose',
127                       'fix':        '_cmdClose',
128                       'fixed':      '_cmdClose',
129                       'fixes':      '_cmdClose',
130                       'addresses':  '_cmdRefs',
131                       're':         '_cmdRefs',
132                       'references': '_cmdRefs',
133                       'refs':       '_cmdRefs',
134                       'see':        '_cmdRefs'}
135
136    def __init__(self, project=options.project, author=options.user,
137                 rev=options.rev, msg=options.msg, url=options.url, file=options.file):
138        self.author = author
139        self.rev = rev
140# if msg empty, read it from file
141        if not msg:
142            f = open (file)
143            for line in f:
144                if not msg:
145                    msg=line + '\n'
146                else:
147                    msg = msg + line + '\n'
148            f.close()
149# reformat msg
150        self.msg = "(In [%s]) %s" % (rev, msg)
151        self.now = int(time.time()) 
152        self.env = open_environment(project)
153        if url is None:
154            url = self.env.config.get('project', 'url')
155
156        cmdGroups = commandPattern.findall(msg)
157
158        tickets = {}
159        for cmd, tkts in cmdGroups:
160            funcname = CommitHook._supported_cmds.get(cmd.lower(), '')
161            if funcname:
162                for tkt_id in ticketPattern.findall(tkts):
163                    func = getattr(self, funcname)
164                    tickets.setdefault(tkt_id, []).append(func)
165
166        for tkt_id, cmds in tickets.iteritems():
167            try:
168                db = self.env.get_db_cnx()
169               
170                ticket = Ticket(self.env, int(tkt_id), db)
171                for cmd in cmds:
172                    cmd(ticket)
173
174                # determine sequence number...
175                cnum = 0
176                tm = TicketModule(self.env)
177                for change in tm.grouped_changelog_entries(ticket, db):
178                    if change['permanent']:
179                        cnum += 1
180               
181                ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)
182                db.commit()
183               
184                tn = TicketNotifyEmail(self.env)
185                tn.notify(ticket, newticket=0, modtime=self.now)
186            except Exception, e:
187                # import traceback
188                # traceback.print_exc(file=sys.stderr)
189                print>>sys.stderr, 'Unexpected error while processing ticket ' \
190                                   'ID %s: %s' % (tkt_id, e)
191           
192
193    def _cmdClose(self, ticket):
194        ticket['status'] = 'closed'
195        ticket['resolution'] = 'fixed'
196
197    def _cmdRefs(self, ticket):
198        pass
199
200
201if __name__ == "__main__":
202    if len(sys.argv) < 5:
203        print "For usage: %s --help" % (sys.argv[0])
204    else:
205        CommitHook()