[pypy-svn] buildbot default: get rid of Handlers

RonnyPfannschmidt commits-noreply at bitbucket.org
Wed Apr 20 15:53:45 CEST 2011


Author: Ronny Pfannschmidt <Ronny.Pfannschmidt at gmx.de>
Branch: 
Changeset: r473:0b23291484ef
Date: 2011-04-20 07:58 +0200
http://bitbucket.org/pypy/buildbot/changeset/0b23291484ef/

Log:	get rid of Handlers

diff --git a/bitbucket_hook/hook.py b/bitbucket_hook/hook.py
--- a/bitbucket_hook/hook.py
+++ b/bitbucket_hook/hook.py
@@ -3,25 +3,15 @@
 import subprocess
 import sys
 import time
-from smtplib import SMTP
 
-from .irc import getpaths
+from . import irc
 from .main import app
 
 from . import scm
+from . import mail
 
 
 
-TEMPLATE = u"""\
-Author: {author}
-Branch: {branches}
-Changeset: r{rev}:{node|short}
-Date: {date|isodate}
-%(url)s
-
-Log:\t{desc|fill68|tabindent}
-
-"""
 
 
 seen_nodes = set()
@@ -44,103 +34,19 @@
         seen_nodes.add(key)
         yield commit
 
-def send(from_, to, subject, body, test=False):
-    from email.mime.text import MIMEText
-    # Is this a valid workaround for unicode errors?
-    body = body.encode('ascii', 'xmlcharrefreplace')
-    msg = MIMEText(body, _charset='utf-8')
-    msg['From'] = from_
-    msg['To'] = to
-    msg['Subject'] = subject
-    if test:
-        print '#' * 20
-        print "Email contents:\n"
-        print from_
-        print to
-        print msg.get_payload(decode=True)
-    else:
-        smtp = SMTP(app.config['SMTP_SERVER'], app.config['SMTP_PORT'])
-        smtp.sendmail(from_, [to], msg.as_string())
 
 
-def send_irc_message(message, test=False):
-    if test:
-        print message + '\n'
-    else:
-        return subprocess.call([
-            app.config['BOT'], app.config['CHANNEL'], message
-        ])
 
-def handle_irc_message(payload, test=False):
-    commits = get_commits('irc', payload)
-    if test:
-        print "#" * 20
-        print "IRC messages:"
-
-    for commit in commits:
-        author = commit['author']
-        branch = commit['branch']
-        node = commit['node']
-        timestamp = commit.get('timestamp')
-        print '[%s] %s %s %s' % (time.strftime('%Y-%m-%d %H:%M'), node, timestamp, author)
-
-        files = commit.get('files', [])
-        common_prefix, filenames = getpaths(files, app.config['LISTFILES'])
-        pathlen = len(common_prefix) + len(filenames) + 2
-        common_prefix = '/' + common_prefix
-
-        if app.config['USE_COLOR_CODES']:
-            author = '\x0312%s\x0F' % author   # in blue
-            branch = '\x02%s\x0F'   % branch   # in bold
-            node = '\x0311%s\x0F'   % node     # in azure
-            common_prefix = '\x0315%s\x0F' % common_prefix # in gray
-
-        message = commit['message'].replace('\n', ' ')
-        fields = (author, branch, node, common_prefix, filenames)
-        part1 = '%s %s %s %s%s: ' % fields
-        totallen = 160 + pathlen
-        if len(message) + len(part1) <= totallen:
-            irc_msg = part1 + message
-        else:
-            maxlen = totallen - (len(part1) + 3)
-            irc_msg = part1 + message[:maxlen] + '...'
-        send_irc_message(irc_msg, test)
-
-class BitbucketHookHandler(object):
-
-    def handle(self, payload, test=False):
-        path = payload['repository']['absolute_url']
-        self.payload = payload
-        self.local_repo = app.config['LOCAL_REPOS'].join(path)
-        self.remote_repo = app.config['REMOTE_BASE'] + path
-        if not check_for_local_repo(self.local_repo):
-            print >> sys.stderr, 'Ignoring unknown repo', path
-            return
-        scm.hg('pull', '-R', self.local_repo)
-        handle_irc_message(payload, test)
-        self.handle_diff_email(test)
-
-
-    def handle_diff_email(self, test=False):
-        commits = get_commits('email', self.payload)
-        for commit in commits:
-            self.send_diff_for_commit(commit, test)
-
-    def send_diff_for_commit(self, commit, test=False):
-        hgid = commit['raw_node']
-        sender = commit['author'] + ' <commits-noreply at bitbucket.org>'
-        lines = commit['message'].splitlines()
-        line0 = lines and lines[0] or ''
-        reponame = self.payload['repository']['name']
-        # TODO: maybe include the modified paths in the subject line?
-        url = self.remote_repo + 'changeset/' + commit['node'] + '/'
-        template = TEMPLATE % {'url': url}
-        subject = '%s %s: %s' % (reponame, commit['branch'], line0)
-        body = scm.hg('-R', self.local_repo, 'log', '-r', hgid,
-                 '--template', template)
-        diff = scm.get_diff(self.local_repo, hgid, commit['files'])
-        body = body+diff
-        send(sender, app.config['ADDRESS'], subject, body, test)
+def handle(payload, test=False):
+    path = payload['repository']['absolute_url']
+    local_repo = app.config['LOCAL_REPOS'].join(path)
+    remote_repo = app.config['REMOTE_BASE'] + path
+    if not check_for_local_repo(local_repo):
+        print >> sys.stderr, 'Ignoring unknown repo', path
+        return
+    scm.hg('pull', '-R', local_repo)
+    irc.handle_message(payload, test)
+    mail.handle_diff_email(payload, test)
 
 
 

diff --git a/bitbucket_hook/irc.py b/bitbucket_hook/irc.py
--- a/bitbucket_hook/irc.py
+++ b/bitbucket_hook/irc.py
@@ -3,6 +3,8 @@
 '''
 
 import os
+import time
+import subprocess
 
 def getpaths(files, listfiles=False):
 
@@ -36,3 +38,55 @@
     else:
         filenames = ''
     return common_prefix, filenames
+
+
+
+def send_message(message, test=False):
+    if test:
+        print message + '\n'
+    else:
+        from .main import app
+        return subprocess.call([
+            app.config['BOT'], app.config['CHANNEL'], message
+        ])
+
+
+def handle_message(payload, test=False):
+    #XXX
+    from .hook import get_commits
+    from .main import app
+    commits = get_commits('irc', payload)
+    if test:
+        print "#" * 20
+        print "IRC messages:"
+
+    for commit in commits:
+        author = commit['author']
+        branch = commit['branch']
+        node = commit['node']
+        timestamp = commit.get('timestamp')
+        print '[%s] %s %s %s' % (time.strftime('%Y-%m-%d %H:%M'), node, timestamp, author)
+
+        files = commit.get('files', [])
+        common_prefix, filenames = getpaths(files, app.config['LISTFILES'])
+        pathlen = len(common_prefix) + len(filenames) + 2
+        common_prefix = '/' + common_prefix
+
+        if app.config['USE_COLOR_CODES']:
+            author = '\x0312%s\x0F' % author   # in blue
+            branch = '\x02%s\x0F'   % branch   # in bold
+            node = '\x0311%s\x0F'   % node     # in azure
+            common_prefix = '\x0315%s\x0F' % common_prefix # in gray
+
+        message = commit['message'].replace('\n', ' ')
+        fields = (author, branch, node, common_prefix, filenames)
+        part1 = '%s %s %s %s%s: ' % fields
+        totallen = 160 + pathlen
+        if len(message) + len(part1) <= totallen:
+            irc_msg = part1 + message
+        else:
+            maxlen = totallen - (len(part1) + 3)
+            irc_msg = part1 + message[:maxlen] + '...'
+        send_message(irc_msg, test)
+
+

diff --git a/bitbucket_hook/mail.py b/bitbucket_hook/mail.py
new file mode 100644
--- /dev/null
+++ b/bitbucket_hook/mail.py
@@ -0,0 +1,66 @@
+from . import scm
+from smtplib import SMTP
+
+
+TEMPLATE = u"""\
+Author: {author}
+Branch: {branches}
+Changeset: r{rev}:{node|short}
+Date: {date|isodate}
+%(url)s
+
+Log:\t{desc|fill68|tabindent}
+
+"""
+
+
+def send_diff_for_commit(payload, commit, test=False):
+    from .main import app
+
+    path = payload['repository']['absolute_url']
+    local_repo = app.config['LOCAL_REPOS'].join(path)
+    remote_repo = app.config['REMOTE_BASE'] + path
+
+    hgid = commit['raw_node']
+    sender = commit['author'] + ' <commits-noreply at bitbucket.org>'
+    lines = commit['message'].splitlines()
+    line0 = lines and lines[0] or ''
+    reponame = payload['repository']['name']
+    # TODO: maybe include the modified paths in the subject line?
+    url = remote_repo + 'changeset/' + commit['node'] + '/'
+    template = TEMPLATE % {'url': url}
+    subject = '%s %s: %s' % (reponame, commit['branch'], line0)
+    body = scm.hg('-R', local_repo, 'log', '-r', hgid,
+             '--template', template)
+    diff = scm.get_diff(local_repo, hgid, commit['files'])
+    body = body+diff
+    send(sender, app.config['ADDRESS'], subject, body, test)
+
+
+def send(from_, to, subject, body, test=False):
+    from email.mime.text import MIMEText
+    # Is this a valid workaround for unicode errors?
+    body = body.encode('ascii', 'xmlcharrefreplace')
+    msg = MIMEText(body, _charset='utf-8')
+    msg['From'] = from_
+    msg['To'] = to
+    msg['Subject'] = subject
+    if test:
+        print '#' * 20
+        print "Email contents:\n"
+        print from_
+        print to
+        print msg.get_payload(decode=True)
+    else:
+        smtp = SMTP(app.config['SMTP_SERVER'], app.config['SMTP_PORT'])
+        smtp.sendmail(from_, [to], msg.as_string())
+
+
+def handle_diff_email(payload, test=False):
+    from . import hook
+    commits = hook.get_commits('email', payload)
+    for commit in commits:
+        send_diff_for_commit(payload, commit, test)
+
+
+

diff --git a/bitbucket_hook/test/conftest.py b/bitbucket_hook/test/conftest.py
--- a/bitbucket_hook/test/conftest.py
+++ b/bitbucket_hook/test/conftest.py
@@ -1,4 +1,4 @@
-from bitbucket_hook import hook
+from bitbucket_hook import irc, mail, hook
 
 def pytest_funcarg__mails(request):
     return []
@@ -6,17 +6,20 @@
 def pytest_funcarg__messages(request):
     return []
 
+def pytest_runtest_setup(item):
+    hook.seen_nodes.clear()
+
 def pytest_funcarg__monkeypatch(request):
     mp =  request.getfuncargvalue('monkeypatch')
     mails = request.getfuncargvalue('mails')
     def send(from_, to, subject, body,test=False, mails=mails):
         mails.append((from_, to, subject, body))
-    mp.setattr(hook, 'send', send)
+    mp.setattr(mail, 'send', send)
 
     messages = request.getfuncargvalue('messages')
     def send_irc_message(message, test=False):
         messages.append(message)
-    mp.setattr(hook, 'send_irc_message', send_irc_message)
+    mp.setattr(irc, 'send_message', send_irc_message)
 
 
     return mp

diff --git a/bitbucket_hook/test/test_hook.py b/bitbucket_hook/test/test_hook.py
--- a/bitbucket_hook/test/test_hook.py
+++ b/bitbucket_hook/test/test_hook.py
@@ -1,33 +1,22 @@
 # -*- encoding: utf-8 -*-
 import py
 import pytest
-from bitbucket_hook import hook, scm
+from bitbucket_hook import hook, scm, mail, irc
 
 #XXX
 hook.app.config['USE_COLOR_CODES'] = False
 
 
-class BaseHandler(hook.BitbucketHookHandler):
-
-    def __init__(self):
-        hook.BitbucketHookHandler.__init__(self)
-
 
 def test_sort_commits():
-    class MyHandler(BaseHandler):
-        def __init__(self):
-            BaseHandler.__init__(self)
-            self.sent_commits = []
-        def send_diff_for_commit(self, commit, test=False):
-            self.sent_commits.append(commit['node'])
     #
-    handler = MyHandler()
-    handler.payload = {
+    commits = hook.get_commits('test_sort', {
         'commits': [{'revision': 43, 'node': 'second', 'raw_node': 'first'},
                     {'revision': 42, 'node': 'first', 'raw_node': 'second'}]
-        }
-    handler.handle_diff_email()
-    assert handler.sent_commits == ['first', 'second']
+        })
+    commits = [x['node'] for x in commits]
+
+    assert commits == ['first', 'second']
 
 
 LONG_MESSAGE = u'This is a test with a long message: ' + 'x'*1000
@@ -94,7 +83,7 @@
                     ]}
 
     payload, expected = irc_cases(payload)
-    hook.handle_irc_message(payload)
+    irc.handle_message(payload)
 
     msg1, msg2 = messages[:2]
 
@@ -113,7 +102,6 @@
     sendmail = noop
 
 def test_handle(monkeypatch):
-    handler = hook.BitbucketHookHandler()
     commits, _ = irc_cases()
     test_payload = {u'repository': {u'absolute_url': '',
                                     u'name': u'test',
@@ -124,15 +112,15 @@
                     'commits': commits['commits']}
 
     monkeypatch.setattr(scm, 'Popen', mock)
-    monkeypatch.setattr(hook.subprocess, 'call', noop)
-    monkeypatch.setattr(hook, 'SMTP', mock)
+    monkeypatch.setattr(irc.subprocess, 'call', noop)
+    monkeypatch.setattr(mail, 'SMTP', mock)
 
-    handler.handle(test_payload)
-    handler.handle(test_payload, test=True)
+    hook.handle(test_payload)
+    hook.handle(test_payload, test=True)
 
-    handler.LISTFILES = True
-    handler.handle(test_payload)
-    handler.handle(test_payload, test=True)
+    hook.app.config['LISTFILES'] = True
+    hook.handle(test_payload)
+    hook.handle(test_payload, test=True)
 
 
 def test_ignore_duplicate_commits(monkeypatch, mails, messages):
@@ -142,7 +130,6 @@
     monkeypatch.setattr(hook, 'seen_nodes', set())
     monkeypatch.setattr(hook, 'check_for_local_repo', lambda _:True)
 
-    handler = BaseHandler()
     commits, _ = irc_cases()
     payload = {u'repository': {u'absolute_url': '',
                                u'name': u'test',
@@ -151,8 +138,8 @@
                                u'website': u''},
                u'user': u'antocuni',
                'commits': commits['commits']}
-    handler.handle(payload)
-    handler.handle(payload)
+    hook.handle(payload)
+    hook.handle(payload)
     #
     num_commits = len(commits['commits'])
     assert len(mails) == num_commits


More information about the Pypy-commit mailing list