Blame progit/hooks/files/git_multimail.py

Pierre-Yves Chibon 0a9634
#! /usr/bin/env python2
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
# Copyright (c) 2012-2014 Michael Haggerty and others
Pierre-Yves Chibon 0a9634
# Derived from contrib/hooks/post-receive-email, which is
Pierre-Yves Chibon 0a9634
# Copyright (c) 2007 Andy Parkins
Pierre-Yves Chibon 0a9634
# and also includes contributions by other authors.
Pierre-Yves Chibon 0a9634
#
Pierre-Yves Chibon 0a9634
# This file is part of git-multimail.
Pierre-Yves Chibon 0a9634
#
Pierre-Yves Chibon 0a9634
# git-multimail is free software: you can redistribute it and/or
Pierre-Yves Chibon 0a9634
# modify it under the terms of the GNU General Public License version
Pierre-Yves Chibon 0a9634
# 2 as published by the Free Software Foundation.
Pierre-Yves Chibon 0a9634
#
Pierre-Yves Chibon 0a9634
# This program is distributed in the hope that it will be useful, but
Pierre-Yves Chibon 0a9634
# WITHOUT ANY WARRANTY; without even the implied warranty of
Pierre-Yves Chibon 0a9634
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Pierre-Yves Chibon 0a9634
# General Public License for more details.
Pierre-Yves Chibon 0a9634
#
Pierre-Yves Chibon 0a9634
# You should have received a copy of the GNU General Public License
Pierre-Yves Chibon 0a9634
# along with this program.  If not, see
Pierre-Yves Chibon 0a9634
# <http: licenses="" www.gnu.org="">.</http:>
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
"""Generate notification emails for pushes to a git repository.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
This hook sends emails describing changes introduced by pushes to a
Pierre-Yves Chibon 0a9634
git repository.  For each reference that was changed, it emits one
Pierre-Yves Chibon 0a9634
ReferenceChange email summarizing how the reference was changed,
Pierre-Yves Chibon 0a9634
followed by one Revision email for each new commit that was introduced
Pierre-Yves Chibon 0a9634
by the reference change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Each commit is announced in exactly one Revision email.  If the same
Pierre-Yves Chibon 0a9634
commit is merged into another branch in the same or a later push, then
Pierre-Yves Chibon 0a9634
the ReferenceChange email will list the commit's SHA1 and its one-line
Pierre-Yves Chibon 0a9634
summary, but no new Revision email will be generated.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
This script is designed to be used as a "post-receive" hook in a git
Pierre-Yves Chibon 0a9634
repository (see githooks(5)).  It can also be used as an "update"
Pierre-Yves Chibon 0a9634
script, but this usage is not completely reliable and is deprecated.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
To help with debugging, this script accepts a --stdout option, which
Pierre-Yves Chibon 0a9634
causes the emails to be written to standard output rather than sent
Pierre-Yves Chibon 0a9634
using sendmail.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
See the accompanying README file for the complete documentation.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
import sys
Pierre-Yves Chibon 0a9634
import os
Pierre-Yves Chibon 0a9634
import re
Pierre-Yves Chibon 0a9634
import bisect
Pierre-Yves Chibon 0a9634
import socket
Pierre-Yves Chibon 0a9634
import subprocess
Pierre-Yves Chibon 0a9634
import shlex
Pierre-Yves Chibon 0a9634
import optparse
Pierre-Yves Chibon 0a9634
import smtplib
Pierre-Yves Chibon 0a9634
import time
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
try:
Pierre-Yves Chibon 0a9634
    from email.utils import make_msgid
Pierre-Yves Chibon 0a9634
    from email.utils import getaddresses
Pierre-Yves Chibon 0a9634
    from email.utils import formataddr
Pierre-Yves Chibon 0a9634
    from email.utils import formatdate
Pierre-Yves Chibon 0a9634
    from email.header import Header
Pierre-Yves Chibon 0a9634
except ImportError:
Pierre-Yves Chibon 0a9634
    # Prior to Python 2.5, the email module used different names:
Pierre-Yves Chibon 0a9634
    from email.Utils import make_msgid
Pierre-Yves Chibon 0a9634
    from email.Utils import getaddresses
Pierre-Yves Chibon 0a9634
    from email.Utils import formataddr
Pierre-Yves Chibon 0a9634
    from email.Utils import formatdate
Pierre-Yves Chibon 0a9634
    from email.Header import Header
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
DEBUG = False
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
ZEROS = '0' * 40
Pierre-Yves Chibon 0b6d99
LOGBEGIN = '- Log -------------------------------------------------------'\
Pierre-Yves Chibon 0b6d99
    '----------\n'
Pierre-Yves Chibon 0b6d99
LOGEND = '---------------------------------------------------------------'\
Pierre-Yves Chibon 0b6d99
    '--------\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
ADDR_HEADERS = set(['from', 'to', 'cc', 'bcc', 'reply-to', 'sender'])
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
# It is assumed in many places that the encoding is uniformly UTF-8,
Pierre-Yves Chibon 0a9634
# so changing these constants is unsupported.  But define them here
Pierre-Yves Chibon 0a9634
# anyway, to make it easier to find (at least most of) the places
Pierre-Yves Chibon 0a9634
# where the encoding is important.
Pierre-Yves Chibon 0a9634
(ENCODING, CHARSET) = ('UTF-8', 'utf-8')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
REF_CREATED_SUBJECT_TEMPLATE = (
Pierre-Yves Chibon 0a9634
    '%(emailprefix)s%(refname_type)s %(short_refname)s created'
Pierre-Yves Chibon 0a9634
    ' (now %(newrev_short)s)'
Pierre-Yves Chibon 0a9634
    )
Pierre-Yves Chibon 0a9634
REF_UPDATED_SUBJECT_TEMPLATE = (
Pierre-Yves Chibon 0a9634
    '%(emailprefix)s%(refname_type)s %(short_refname)s updated'
Pierre-Yves Chibon 0a9634
    ' (%(oldrev_short)s -> %(newrev_short)s)'
Pierre-Yves Chibon 0a9634
    )
Pierre-Yves Chibon 0a9634
REF_DELETED_SUBJECT_TEMPLATE = (
Pierre-Yves Chibon 0a9634
    '%(emailprefix)s%(refname_type)s %(short_refname)s deleted'
Pierre-Yves Chibon 0a9634
    ' (was %(oldrev_short)s)'
Pierre-Yves Chibon 0a9634
    )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
REFCHANGE_HEADER_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
Date: %(send_date)s
Pierre-Yves Chibon 0a9634
To: %(recipients)s
Pierre-Yves Chibon 0a9634
Subject: %(subject)s
Pierre-Yves Chibon 0a9634
MIME-Version: 1.0
Pierre-Yves Chibon 0a9634
Content-Type: text/plain; charset=%(charset)s
Pierre-Yves Chibon 0a9634
Content-Transfer-Encoding: 8bit
Pierre-Yves Chibon 0a9634
Message-ID: %(msgid)s
Pierre-Yves Chibon 0a9634
From: %(fromaddr)s
Pierre-Yves Chibon 0a9634
Reply-To: %(reply_to)s
Pierre-Yves Chibon 0a9634
X-Git-Host: %(fqdn)s
Pierre-Yves Chibon 0a9634
X-Git-Repo: %(repo_shortname)s
Pierre-Yves Chibon 0a9634
X-Git-Refname: %(refname)s
Pierre-Yves Chibon 0a9634
X-Git-Reftype: %(refname_type)s
Pierre-Yves Chibon 0a9634
X-Git-Oldrev: %(oldrev)s
Pierre-Yves Chibon 0a9634
X-Git-Newrev: %(newrev)s
Pierre-Yves Chibon 0a9634
Auto-Submitted: auto-generated
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
REFCHANGE_INTRO_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
This is an automated email from the git hooks/post-receive script.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
%(pusher)s pushed a change to %(refname_type)s %(short_refname)s
Pierre-Yves Chibon 0a9634
in repository %(repo_shortname)s.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
FOOTER_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
-- \n\
Pierre-Yves Chibon 0a9634
To stop receiving notification emails like this one, please contact
Pierre-Yves Chibon 0a9634
%(administrator)s.
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
REWIND_ONLY_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
This update removed existing revisions from the reference, leaving the
Pierre-Yves Chibon 0a9634
reference pointing at a previous point in the repository history.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
 * -- * -- N   %(refname)s (%(newrev_short)s)
Pierre-Yves Chibon 0a9634
            \\
Pierre-Yves Chibon 0a9634
             O -- O -- O   (%(oldrev_short)s)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Any revisions marked "omits" are not gone; other references still
Pierre-Yves Chibon 0a9634
refer to them.  Any revisions marked "discards" are gone forever.
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
NON_FF_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
This update added new revisions after undoing existing revisions.
Pierre-Yves Chibon 0a9634
That is to say, some revisions that were in the old version of the
Pierre-Yves Chibon 0a9634
%(refname_type)s are not in the new version.  This situation occurs
Pierre-Yves Chibon 0a9634
when a user --force pushes a change and generates a repository
Pierre-Yves Chibon 0a9634
containing something like this:
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
 * -- * -- B -- O -- O -- O   (%(oldrev_short)s)
Pierre-Yves Chibon 0a9634
            \\
Pierre-Yves Chibon 0a9634
             N -- N -- N   %(refname)s (%(newrev_short)s)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
You should already have received notification emails for all of the O
Pierre-Yves Chibon 0a9634
revisions, and so the following emails describe only the N revisions
Pierre-Yves Chibon 0a9634
from the common base, B.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Any revisions marked "omits" are not gone; other references still
Pierre-Yves Chibon 0a9634
refer to them.  Any revisions marked "discards" are gone forever.
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
NO_NEW_REVISIONS_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
No new revisions were added by this update.
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
DISCARDED_REVISIONS_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
This change permanently discards the following revisions:
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
NO_DISCARDED_REVISIONS_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
The revisions that were on this %(refname_type)s are still contained in
Pierre-Yves Chibon 0a9634
other references; therefore, this change does not discard any commits
Pierre-Yves Chibon 0a9634
from the repository.
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
NEW_REVISIONS_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
The %(tot)s revisions listed above as "new" are entirely new to this
Pierre-Yves Chibon 0a9634
repository and will be described in separate emails.  The revisions
Pierre-Yves Chibon 0a9634
listed as "adds" were already present in the repository and have only
Pierre-Yves Chibon 0a9634
been added to this reference.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
TAG_CREATED_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
        at  %(newrev_short)-9s (%(newrev_type)s)
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
TAG_UPDATED_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
*** WARNING: tag %(short_refname)s was modified! ***
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
      from  %(oldrev_short)-9s (%(oldrev_type)s)
Pierre-Yves Chibon 0a9634
        to  %(newrev_short)-9s (%(newrev_type)s)
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
TAG_DELETED_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
*** WARNING: tag %(short_refname)s was deleted! ***
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
# The template used in summary tables.  It looks best if this uses the
Pierre-Yves Chibon 0a9634
# same alignment as TAG_CREATED_TEMPLATE and TAG_UPDATED_TEMPLATE.
Pierre-Yves Chibon 0a9634
BRIEF_SUMMARY_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
%(action)10s  %(rev_short)-9s %(text)s
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
NON_COMMIT_UPDATE_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
This is an unusual reference change because the reference did not
Pierre-Yves Chibon 0a9634
refer to a commit either before or after the change.  We do not know
Pierre-Yves Chibon 0a9634
how to provide full information about this reference change.
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
REVISION_HEADER_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
Date: %(send_date)s
Pierre-Yves Chibon 0a9634
To: %(recipients)s
Pierre-Yves Chibon 0a9634
Subject: %(emailprefix)s%(num)02d/%(tot)02d: %(oneline)s
Pierre-Yves Chibon 0a9634
MIME-Version: 1.0
Pierre-Yves Chibon 0a9634
Content-Type: text/plain; charset=%(charset)s
Pierre-Yves Chibon 0a9634
Content-Transfer-Encoding: 8bit
Pierre-Yves Chibon 0a9634
From: %(fromaddr)s
Pierre-Yves Chibon 0a9634
Reply-To: %(reply_to)s
Pierre-Yves Chibon 0a9634
In-Reply-To: %(reply_to_msgid)s
Pierre-Yves Chibon 0a9634
References: %(reply_to_msgid)s
Pierre-Yves Chibon 0a9634
X-Git-Host: %(fqdn)s
Pierre-Yves Chibon 0a9634
X-Git-Repo: %(repo_shortname)s
Pierre-Yves Chibon 0a9634
X-Git-Refname: %(refname)s
Pierre-Yves Chibon 0a9634
X-Git-Reftype: %(refname_type)s
Pierre-Yves Chibon 0a9634
X-Git-Rev: %(rev)s
Pierre-Yves Chibon 0a9634
Auto-Submitted: auto-generated
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
REVISION_INTRO_TEMPLATE = """\
Pierre-Yves Chibon 0a9634
This is an automated email from the git hooks/post-receive script.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
%(pusher)s pushed a commit to %(refname_type)s %(short_refname)s
Pierre-Yves Chibon 0a9634
in repository %(repo_shortname)s.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
REVISION_FOOTER_TEMPLATE = FOOTER_TEMPLATE
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class CommandError(Exception):
Pierre-Yves Chibon 0a9634
    def __init__(self, cmd, retcode):
Pierre-Yves Chibon 0a9634
        self.cmd = cmd
Pierre-Yves Chibon 0a9634
        self.retcode = retcode
Pierre-Yves Chibon 0a9634
        Exception.__init__(
Pierre-Yves Chibon 0a9634
            self,
Pierre-Yves Chibon 0a9634
            'Command "%s" failed with retcode %s' % (' '.join(cmd), retcode,)
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ConfigurationException(Exception):
Pierre-Yves Chibon 0a9634
    pass
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
# The "git" program (this could be changed to include a full path):
Pierre-Yves Chibon 0a9634
GIT_EXECUTABLE = 'git'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
# How "git" should be invoked (including global arguments), as a list
Pierre-Yves Chibon 0a9634
# of words.  This variable is usually initialized automatically by
Pierre-Yves Chibon 0a9634
# read_git_output() via choose_git_command(), but if a value is set
Pierre-Yves Chibon 0a9634
# here then it will be used unconditionally.
Pierre-Yves Chibon 0a9634
GIT_CMD = None
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def choose_git_command():
Pierre-Yves Chibon 0a9634
    """Decide how to invoke git, and record the choice in GIT_CMD."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    global GIT_CMD
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    if GIT_CMD is None:
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            # Check to see whether the "-c" option is accepted (it was
Pierre-Yves Chibon 0a9634
            # only added in Git 1.7.2).  We don't actually use the
Pierre-Yves Chibon 0a9634
            # output of "git --version", though if we needed more
Pierre-Yves Chibon 0a9634
            # specific version information this would be the place to
Pierre-Yves Chibon 0a9634
            # do it.
Pierre-Yves Chibon 0a9634
            cmd = [GIT_EXECUTABLE, '-c', 'foo.bar=baz', '--version']
Pierre-Yves Chibon 0a9634
            read_output(cmd)
Pierre-Yves Chibon 0b6d99
            GIT_CMD = [
Pierre-Yves Chibon 0b6d99
                GIT_EXECUTABLE, '-c',
Pierre-Yves Chibon 0b6d99
                'i18n.logoutputencoding=%s' % (ENCODING,)]
Pierre-Yves Chibon 0a9634
        except CommandError:
Pierre-Yves Chibon 0a9634
            GIT_CMD = [GIT_EXECUTABLE]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def read_git_output(args, input=None, keepends=False, **kw):
Pierre-Yves Chibon 0a9634
    """Read the output of a Git command."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    if GIT_CMD is None:
Pierre-Yves Chibon 0a9634
        choose_git_command()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0b6d99
    return read_output(
Pierre-Yves Chibon 0b6d99
        GIT_CMD + args, input=input, keepends=keepends, **kw)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def read_output(cmd, input=None, keepends=False, **kw):
Pierre-Yves Chibon 0a9634
    if input:
Pierre-Yves Chibon 0a9634
        stdin = subprocess.PIPE
Pierre-Yves Chibon 0a9634
    else:
Pierre-Yves Chibon 0a9634
        stdin = None
Pierre-Yves Chibon 0a9634
    p = subprocess.Popen(
Pierre-Yves Chibon 0b6d99
        cmd, stdin=stdin, stdout=subprocess.PIPE,
Pierre-Yves Chibon 0b6d99
        stderr=subprocess.PIPE, **kw
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
    (out, err) = p.communicate(input)
Pierre-Yves Chibon 0a9634
    retcode = p.wait()
Pierre-Yves Chibon 0a9634
    if retcode:
Pierre-Yves Chibon 0a9634
        raise CommandError(cmd, retcode)
Pierre-Yves Chibon 0a9634
    if not keepends:
Pierre-Yves Chibon 0a9634
        out = out.rstrip('\n\r')
Pierre-Yves Chibon 0a9634
    return out
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def read_git_lines(args, keepends=False, **kw):
Pierre-Yves Chibon 0a9634
    """Return the lines output by Git command.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    Return as single lines, with newlines stripped off."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    return read_git_output(args, keepends=True, **kw).splitlines(keepends)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def header_encode(text, header_name=None):
Pierre-Yves Chibon 0a9634
    """Encode and line-wrap the value of an email header field."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    try:
Pierre-Yves Chibon 0a9634
        if isinstance(text, str):
Pierre-Yves Chibon 0a9634
            text = text.decode(ENCODING, 'replace')
Pierre-Yves Chibon 0a9634
        return Header(text, header_name=header_name).encode()
Pierre-Yves Chibon 0a9634
    except UnicodeEncodeError:
Pierre-Yves Chibon 0a9634
        return Header(text, header_name=header_name, charset=CHARSET,
Pierre-Yves Chibon 0a9634
                      errors='replace').encode()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def addr_header_encode(text, header_name=None):
Pierre-Yves Chibon 0a9634
    """Encode and line-wrap the value of an email header field containing
Pierre-Yves Chibon 0a9634
    email addresses."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    return Header(
Pierre-Yves Chibon 0a9634
        ', '.join(
Pierre-Yves Chibon 0a9634
            formataddr((header_encode(name), emailaddr))
Pierre-Yves Chibon 0a9634
            for name, emailaddr in getaddresses([text])
Pierre-Yves Chibon 0a9634
            ),
Pierre-Yves Chibon 0a9634
        header_name=header_name
Pierre-Yves Chibon 0a9634
        ).encode()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class Config(object):
Pierre-Yves Chibon 0a9634
    def __init__(self, section, git_config=None):
Pierre-Yves Chibon 0a9634
        """Represent a section of the git configuration.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        If git_config is specified, it is passed to "git config" in
Pierre-Yves Chibon 0a9634
        the GIT_CONFIG environment variable, meaning that "git config"
Pierre-Yves Chibon 0a9634
        will read the specified path rather than the Git default
Pierre-Yves Chibon 0a9634
        config paths."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        self.section = section
Pierre-Yves Chibon 0a9634
        if git_config:
Pierre-Yves Chibon 0a9634
            self.env = os.environ.copy()
Pierre-Yves Chibon 0a9634
            self.env['GIT_CONFIG'] = git_config
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            self.env = None
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    @staticmethod
Pierre-Yves Chibon 0a9634
    def _split(s):
Pierre-Yves Chibon 0a9634
        """Split NUL-terminated values."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        words = s.split('\0')
Pierre-Yves Chibon 0a9634
        assert words[-1] == ''
Pierre-Yves Chibon 0a9634
        return words[:-1]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get(self, name, default=None):
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            values = self._split(read_git_output(
Pierre-Yves Chibon 0b6d99
                ['config', '--get', '--null', '%s.%s' % (self.section, name)],
Pierre-Yves Chibon 0b6d99
                env=self.env, keepends=True,
Pierre-Yves Chibon 0b6d99
                ))
Pierre-Yves Chibon 0a9634
            assert len(values) == 1
Pierre-Yves Chibon 0a9634
            return values[0]
Pierre-Yves Chibon 0a9634
        except CommandError:
Pierre-Yves Chibon 0a9634
            return default
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_bool(self, name, default=None):
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            value = read_git_output(
Pierre-Yves Chibon 0a9634
                ['config', '--get', '--bool', '%s.%s' % (self.section, name)],
Pierre-Yves Chibon 0a9634
                env=self.env,
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
        except CommandError:
Pierre-Yves Chibon 0a9634
            return default
Pierre-Yves Chibon 0a9634
        return value == 'true'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_all(self, name, default=None):
Pierre-Yves Chibon 0a9634
        """Read a (possibly multivalued) setting from the configuration.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return the result as a list of values, or default if the name
Pierre-Yves Chibon 0a9634
        is unset."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            return self._split(read_git_output(
Pierre-Yves Chibon 0b6d99
                ['config', '--get-all', '--null', '%s.%s' % (
Pierre-Yves Chibon 0b6d99
                    elf.section, name)],
Pierre-Yves Chibon 0a9634
                env=self.env, keepends=True,
Pierre-Yves Chibon 0a9634
                ))
Pierre-Yves Chibon 0a9634
        except CommandError, e:
Pierre-Yves Chibon 0a9634
            if e.retcode == 1:
Pierre-Yves Chibon 0a9634
                # "the section or key is invalid"; i.e., there is no
Pierre-Yves Chibon 0a9634
                # value for the specified key.
Pierre-Yves Chibon 0a9634
                return default
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                raise
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_recipients(self, name, default=None):
Pierre-Yves Chibon 0a9634
        """Read a recipients list from the configuration.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return the result as a comma-separated list of email
Pierre-Yves Chibon 0a9634
        addresses, or default if the option is unset.  If the setting
Pierre-Yves Chibon 0a9634
        has multiple values, concatenate them with comma separators."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        lines = self.get_all(name, default=None)
Pierre-Yves Chibon 0a9634
        if lines is None:
Pierre-Yves Chibon 0a9634
            return default
Pierre-Yves Chibon 0a9634
        return ', '.join(line.strip() for line in lines)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def set(self, name, value):
Pierre-Yves Chibon 0a9634
        read_git_output(
Pierre-Yves Chibon 0a9634
            ['config', '%s.%s' % (self.section, name), value],
Pierre-Yves Chibon 0a9634
            env=self.env,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def add(self, name, value):
Pierre-Yves Chibon 0a9634
        read_git_output(
Pierre-Yves Chibon 0a9634
            ['config', '--add', '%s.%s' % (self.section, name), value],
Pierre-Yves Chibon 0a9634
            env=self.env,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def has_key(self, name):
Pierre-Yves Chibon 0a9634
        return self.get_all(name, default=None) is not None
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def unset_all(self, name):
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            read_git_output(
Pierre-Yves Chibon 0a9634
                ['config', '--unset-all', '%s.%s' % (self.section, name)],
Pierre-Yves Chibon 0a9634
                env=self.env,
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
        except CommandError, e:
Pierre-Yves Chibon 0a9634
            if e.retcode == 5:
Pierre-Yves Chibon 0a9634
                # The name doesn't exist, which is what we wanted anyway...
Pierre-Yves Chibon 0a9634
                pass
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                raise
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def set_recipients(self, name, value):
Pierre-Yves Chibon 0a9634
        self.unset_all(name)
Pierre-Yves Chibon 0a9634
        for pair in getaddresses([value]):
Pierre-Yves Chibon 0a9634
            self.add(name, formataddr(pair))
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def generate_summaries(*log_args):
Pierre-Yves Chibon 0a9634
    """Generate a brief summary for each revision requested.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    log_args are strings that will be passed directly to "git log" as
Pierre-Yves Chibon 0a9634
    revision selectors.  Iterate over (sha1_short, subject) for each
Pierre-Yves Chibon 0a9634
    commit specified by log_args (subject is the first line of the
Pierre-Yves Chibon 0a9634
    commit message as a string without EOLs)."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    cmd = [
Pierre-Yves Chibon 0a9634
        'log', '--abbrev', '--format=%h %s',
Pierre-Yves Chibon 0a9634
        ] + list(log_args) + ['--']
Pierre-Yves Chibon 0a9634
    for line in read_git_lines(cmd):
Pierre-Yves Chibon 0a9634
        yield tuple(line.split(' ', 1))
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def limit_lines(lines, max_lines):
Pierre-Yves Chibon 0a9634
    for (index, line) in enumerate(lines):
Pierre-Yves Chibon 0a9634
        if index < max_lines:
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    if index >= max_lines:
Pierre-Yves Chibon 0a9634
        yield '... %d lines suppressed ...\n' % (index + 1 - max_lines,)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def limit_linelength(lines, max_linelength):
Pierre-Yves Chibon 0a9634
    for line in lines:
Pierre-Yves Chibon 0a9634
        # Don't forget that lines always include a trailing newline.
Pierre-Yves Chibon 0a9634
        if len(line) > max_linelength + 1:
Pierre-Yves Chibon 0a9634
            line = line[:max_linelength - 7] + ' [...]\n'
Pierre-Yves Chibon 0a9634
        yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class CommitSet(object):
Pierre-Yves Chibon 0a9634
    """A (constant) set of object names.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    The set should be initialized with full SHA1 object names.  The
Pierre-Yves Chibon 0a9634
    __contains__() method returns True iff its argument is an
Pierre-Yves Chibon 0a9634
    abbreviation of any the names in the set."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, names):
Pierre-Yves Chibon 0a9634
        self._names = sorted(names)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __len__(self):
Pierre-Yves Chibon 0a9634
        return len(self._names)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __contains__(self, sha1_abbrev):
Pierre-Yves Chibon 0b6d99
        """Return True iff this set contains sha1_abbrev (which might
Pierre-Yves Chibon 0b6d99
        be abbreviated)."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        i = bisect.bisect_left(self._names, sha1_abbrev)
Pierre-Yves Chibon 0a9634
        return i < len(self) and self._names[i].startswith(sha1_abbrev)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class GitObject(object):
Pierre-Yves Chibon 0a9634
    def __init__(self, sha1, type=None):
Pierre-Yves Chibon 0a9634
        if sha1 == ZEROS:
Pierre-Yves Chibon 0a9634
            self.sha1 = self.type = self.commit_sha1 = None
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            self.sha1 = sha1
Pierre-Yves Chibon 0b6d99
            self.type = type or read_git_output(
Pierre-Yves Chibon 0b6d99
                ['cat-file', '-t', self.sha1])
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            if self.type == 'commit':
Pierre-Yves Chibon 0a9634
                self.commit_sha1 = self.sha1
Pierre-Yves Chibon 0a9634
            elif self.type == 'tag':
Pierre-Yves Chibon 0a9634
                try:
Pierre-Yves Chibon 0a9634
                    self.commit_sha1 = read_git_output(
Pierre-Yves Chibon 0a9634
                        ['rev-parse', '--verify', '%s^0' % (self.sha1,)]
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
                except CommandError:
Pierre-Yves Chibon 0a9634
                    # Cannot deref tag to determine commit_sha1
Pierre-Yves Chibon 0a9634
                    self.commit_sha1 = None
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                self.commit_sha1 = None
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        self.short = read_git_output(['rev-parse', '--short', sha1])
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_summary(self):
Pierre-Yves Chibon 0a9634
        """Return (sha1_short, subject) for this commit."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if not self.sha1:
Pierre-Yves Chibon 0a9634
            raise ValueError('Empty commit has no summary')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return iter(generate_summaries('--no-walk', self.sha1)).next()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __eq__(self, other):
Pierre-Yves Chibon 0a9634
        return isinstance(other, GitObject) and self.sha1 == other.sha1
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __hash__(self):
Pierre-Yves Chibon 0a9634
        return hash(self.sha1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __nonzero__(self):
Pierre-Yves Chibon 0a9634
        return bool(self.sha1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __str__(self):
Pierre-Yves Chibon 0a9634
        return self.sha1 or ZEROS
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class Change(object):
Pierre-Yves Chibon 0a9634
    """A Change that has been made to the Git repository.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    Abstract class from which both Revisions and ReferenceChanges are
Pierre-Yves Chibon 0a9634
    derived.  A Change knows how to generate a notification email
Pierre-Yves Chibon 0a9634
    describing itself."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, environment):
Pierre-Yves Chibon 0a9634
        self.environment = environment
Pierre-Yves Chibon 0a9634
        self._values = None
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def _compute_values(self):
Pierre-Yves Chibon 0a9634
        """Return a dictionary {keyword : expansion} for this Change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Derived classes overload this method to add more entries to
Pierre-Yves Chibon 0a9634
        the return value.  This method is used internally by
Pierre-Yves Chibon 0a9634
        get_values().  The return value should always be a new
Pierre-Yves Chibon 0a9634
        dictionary."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return self.environment.get_values()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_values(self, **extra_values):
Pierre-Yves Chibon 0a9634
        """Return a dictionary {keyword : expansion} for this Change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return a dictionary mapping keywords to the values that they
Pierre-Yves Chibon 0a9634
        should be expanded to for this Change (used when interpolating
Pierre-Yves Chibon 0a9634
        template strings).  If any keyword arguments are supplied, add
Pierre-Yves Chibon 0a9634
        those to the return value as well.  The return value is always
Pierre-Yves Chibon 0a9634
        a new dictionary."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if self._values is None:
Pierre-Yves Chibon 0a9634
            self._values = self._compute_values()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        values = self._values.copy()
Pierre-Yves Chibon 0a9634
        if extra_values:
Pierre-Yves Chibon 0a9634
            values.update(extra_values)
Pierre-Yves Chibon 0a9634
        return values
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def expand(self, template, **extra_values):
Pierre-Yves Chibon 0a9634
        """Expand template.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Expand the template (which should be a string) using string
Pierre-Yves Chibon 0a9634
        interpolation of the values for this Change.  If any keyword
Pierre-Yves Chibon 0a9634
        arguments are provided, also include those in the keywords
Pierre-Yves Chibon 0a9634
        available for interpolation."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return template % self.get_values(**extra_values)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def expand_lines(self, template, **extra_values):
Pierre-Yves Chibon 0a9634
        """Break template into lines and expand each line."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        values = self.get_values(**extra_values)
Pierre-Yves Chibon 0a9634
        for line in template.splitlines(True):
Pierre-Yves Chibon 0a9634
            yield line % values
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def expand_header_lines(self, template, **extra_values):
Pierre-Yves Chibon 0b6d99
        """Break template into lines and expand each line as an RFC 2822
Pierre-Yves Chibon 0b6d99
        header.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Encode values and split up lines that are too long.  Silently
Pierre-Yves Chibon 0a9634
        skip lines that contain references to unknown variables."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        values = self.get_values(**extra_values)
Pierre-Yves Chibon 0a9634
        for line in template.splitlines():
Pierre-Yves Chibon 0a9634
            (name, value) = line.split(':', 1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            try:
Pierre-Yves Chibon 0a9634
                value = value % values
Pierre-Yves Chibon 0a9634
            except KeyError, e:
Pierre-Yves Chibon 0a9634
                if DEBUG:
Pierre-Yves Chibon 0a9634
                    sys.stderr.write(
Pierre-Yves Chibon 0b6d99
                        'Warning: unknown variable %r in the following '
Pierre-Yves Chibon 0b6d99
                        'line; line skipped:\n'
Pierre-Yves Chibon 0a9634
                        '    %s\n'
Pierre-Yves Chibon 0a9634
                        % (e.args[0], line,)
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                if name.lower() in ADDR_HEADERS:
Pierre-Yves Chibon 0a9634
                    value = addr_header_encode(value, name)
Pierre-Yves Chibon 0a9634
                else:
Pierre-Yves Chibon 0a9634
                    value = header_encode(value, name)
Pierre-Yves Chibon 0b6d99
                for splitline in (
Pierre-Yves Chibon 0b6d99
                        '%s: %s\n' % (name, value)).splitlines(True):
Pierre-Yves Chibon 0a9634
                    yield splitline
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_header(self):
Pierre-Yves Chibon 0b6d99
        """Generate the RFC 2822 email headers for this Change, a line at a
Pierre-Yves Chibon 0b6d99
        time.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        The output should not include the trailing blank line."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_intro(self):
Pierre-Yves Chibon 0a9634
        """Generate the email intro for this Change, a line at a time.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        The output will be used as the standard boilerplate at the top
Pierre-Yves Chibon 0a9634
        of the email body."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_body(self):
Pierre-Yves Chibon 0a9634
        """Generate the main part of the email body, a line at a time.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        The text in the body might be truncated after a specified
Pierre-Yves Chibon 0a9634
        number of lines (see multimailhook.emailmaxlines)."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_footer(self):
Pierre-Yves Chibon 0a9634
        """Generate the footer of the email, a line at a time.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        The footer is always included, irrespective of
Pierre-Yves Chibon 0a9634
        multimailhook.emailmaxlines."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email(self, push, body_filter=None, extra_header_values={}):
Pierre-Yves Chibon 0a9634
        """Generate an email describing this change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Iterate over the lines (including the header lines) of an
Pierre-Yves Chibon 0a9634
        email describing this change.  If body_filter is not None,
Pierre-Yves Chibon 0a9634
        then use it to filter the lines that are intended for the
Pierre-Yves Chibon 0a9634
        email body.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        The extra_header_values field is received as a dict and not as
Pierre-Yves Chibon 0a9634
        **kwargs, to allow passing other keyword arguments in the
Pierre-Yves Chibon 0a9634
        future (e.g. passing extra values to generate_email_intro()"""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.generate_email_header(**extra_header_values):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
        yield '\n'
Pierre-Yves Chibon 0a9634
        for line in self.generate_email_intro():
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        body = self.generate_email_body(push)
Pierre-Yves Chibon 0a9634
        if body_filter is not None:
Pierre-Yves Chibon 0a9634
            body = body_filter(body)
Pierre-Yves Chibon 0a9634
        for line in body:
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.generate_email_footer():
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class Revision(Change):
Pierre-Yves Chibon 0a9634
    """A Change consisting of a single git commit."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, reference_change, rev, num, tot):
Pierre-Yves Chibon 0a9634
        Change.__init__(self, reference_change.environment)
Pierre-Yves Chibon 0a9634
        self.reference_change = reference_change
Pierre-Yves Chibon 0a9634
        self.rev = rev
Pierre-Yves Chibon 0a9634
        self.change_type = self.reference_change.change_type
Pierre-Yves Chibon 0a9634
        self.refname = self.reference_change.refname
Pierre-Yves Chibon 0a9634
        self.num = num
Pierre-Yves Chibon 0a9634
        self.tot = tot
Pierre-Yves Chibon 0b6d99
        self.author = read_git_output(
Pierre-Yves Chibon 0b6d99
            ['log', '--no-walk', '--format=%aN <%aE>', self.rev.sha1])
Pierre-Yves Chibon 0a9634
        self.recipients = self.environment.get_revision_recipients(self)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def _compute_values(self):
Pierre-Yves Chibon 0a9634
        values = Change._compute_values(self)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        oneline = read_git_output(
Pierre-Yves Chibon 0a9634
            ['log', '--format=%s', '--no-walk', self.rev.sha1]
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        values['rev'] = self.rev.sha1
Pierre-Yves Chibon 0a9634
        values['rev_short'] = self.rev.short
Pierre-Yves Chibon 0a9634
        values['change_type'] = self.change_type
Pierre-Yves Chibon 0a9634
        values['refname'] = self.refname
Pierre-Yves Chibon 0a9634
        values['short_refname'] = self.reference_change.short_refname
Pierre-Yves Chibon 0a9634
        values['refname_type'] = self.reference_change.refname_type
Pierre-Yves Chibon 0a9634
        values['reply_to_msgid'] = self.reference_change.msgid
Pierre-Yves Chibon 0a9634
        values['num'] = self.num
Pierre-Yves Chibon 0a9634
        values['tot'] = self.tot
Pierre-Yves Chibon 0a9634
        values['recipients'] = self.recipients
Pierre-Yves Chibon 0a9634
        values['oneline'] = oneline
Pierre-Yves Chibon 0a9634
        values['author'] = self.author
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        reply_to = self.environment.get_reply_to_commit(self)
Pierre-Yves Chibon 0a9634
        if reply_to:
Pierre-Yves Chibon 0a9634
            values['reply_to'] = reply_to
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return values
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_header(self, **extra_values):
Pierre-Yves Chibon 0a9634
        for line in self.expand_header_lines(
Pierre-Yves Chibon 0b6d99
                REVISION_HEADER_TEMPLATE, **extra_values):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_intro(self):
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(REVISION_INTRO_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_body(self, push):
Pierre-Yves Chibon 0a9634
        """Show this revision."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return read_git_lines(
Pierre-Yves Chibon 0a9634
            ['log'] + self.environment.commitlogopts + ['-1', self.rev.sha1],
Pierre-Yves Chibon 0a9634
            keepends=True,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_footer(self):
Pierre-Yves Chibon 0a9634
        return self.expand_lines(REVISION_FOOTER_TEMPLATE)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ReferenceChange(Change):
Pierre-Yves Chibon 0a9634
    """A Change to a Git reference.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    An abstract class representing a create, update, or delete of a
Pierre-Yves Chibon 0a9634
    Git reference.  Derived classes handle specific types of reference
Pierre-Yves Chibon 0a9634
    (e.g., tags vs. branches).  These classes generate the main
Pierre-Yves Chibon 0a9634
    reference change email summarizing the reference change and
Pierre-Yves Chibon 0a9634
    whether it caused any any commits to be added or removed.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    ReferenceChange objects are usually created using the static
Pierre-Yves Chibon 0a9634
    create() method, which has the logic to decide which derived class
Pierre-Yves Chibon 0a9634
    to instantiate."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    REF_RE = re.compile(r'^refs\/(?P<area>[^\/]+)\/(?P<shortname>.*)$')</shortname>
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    @staticmethod
Pierre-Yves Chibon 0a9634
    def create(environment, oldrev, newrev, refname):
Pierre-Yves Chibon 0a9634
        """Return a ReferenceChange object representing the change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return an object that represents the type of change that is being
Pierre-Yves Chibon 0a9634
        made. oldrev and newrev should be SHA1s or ZEROS."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        old = GitObject(oldrev)
Pierre-Yves Chibon 0a9634
        new = GitObject(newrev)
Pierre-Yves Chibon 0a9634
        rev = new or old
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # The revision type tells us what type the commit is, combined with
Pierre-Yves Chibon 0a9634
        # the location of the ref we can decide between
Pierre-Yves Chibon 0a9634
        #  - working branch
Pierre-Yves Chibon 0a9634
        #  - tracking branch
Pierre-Yves Chibon 0a9634
        #  - unannotated tag
Pierre-Yves Chibon 0a9634
        #  - annotated tag
Pierre-Yves Chibon 0a9634
        m = ReferenceChange.REF_RE.match(refname)
Pierre-Yves Chibon 0a9634
        if m:
Pierre-Yves Chibon 0a9634
            area = m.group('area')
Pierre-Yves Chibon 0a9634
            short_refname = m.group('shortname')
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            area = ''
Pierre-Yves Chibon 0a9634
            short_refname = refname
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if rev.type == 'tag':
Pierre-Yves Chibon 0a9634
            # Annotated tag:
Pierre-Yves Chibon 0a9634
            klass = AnnotatedTagChange
Pierre-Yves Chibon 0a9634
        elif rev.type == 'commit':
Pierre-Yves Chibon 0a9634
            if area == 'tags':
Pierre-Yves Chibon 0a9634
                # Non-annotated tag:
Pierre-Yves Chibon 0a9634
                klass = NonAnnotatedTagChange
Pierre-Yves Chibon 0a9634
            elif area == 'heads':
Pierre-Yves Chibon 0a9634
                # Branch:
Pierre-Yves Chibon 0a9634
                klass = BranchChange
Pierre-Yves Chibon 0a9634
            elif area == 'remotes':
Pierre-Yves Chibon 0a9634
                # Tracking branch:
Pierre-Yves Chibon 0a9634
                sys.stderr.write(
Pierre-Yves Chibon 0a9634
                    '*** Push-update of tracking branch %r\n'
Pierre-Yves Chibon 0b6d99
                    '***  - incomplete email generated.\n' % (refname,)
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
                klass = OtherReferenceChange
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                # Some other reference namespace:
Pierre-Yves Chibon 0a9634
                sys.stderr.write(
Pierre-Yves Chibon 0a9634
                    '*** Push-update of strange reference %r\n'
Pierre-Yves Chibon 0b6d99
                    '***  - incomplete email generated.\n' % (refname,)
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
                klass = OtherReferenceChange
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            # Anything else (is there anything else?)
Pierre-Yves Chibon 0a9634
            sys.stderr.write(
Pierre-Yves Chibon 0a9634
                '*** Unknown type of update to %r (%s)\n'
Pierre-Yves Chibon 0b6d99
                '***  - incomplete email generated.\n' % (refname, rev.type,)
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
            klass = OtherReferenceChange
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return klass(
Pierre-Yves Chibon 0a9634
            environment,
Pierre-Yves Chibon 0a9634
            refname=refname, short_refname=short_refname,
Pierre-Yves Chibon 0a9634
            old=old, new=new, rev=rev,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, environment, refname, short_refname, old, new, rev):
Pierre-Yves Chibon 0a9634
        Change.__init__(self, environment)
Pierre-Yves Chibon 0a9634
        self.change_type = {
Pierre-Yves Chibon 0b6d99
            (False, True): 'create',
Pierre-Yves Chibon 0b6d99
            (True, True): 'update',
Pierre-Yves Chibon 0b6d99
            (True, False): 'delete',
Pierre-Yves Chibon 0a9634
            }[bool(old), bool(new)]
Pierre-Yves Chibon 0a9634
        self.refname = refname
Pierre-Yves Chibon 0a9634
        self.short_refname = short_refname
Pierre-Yves Chibon 0a9634
        self.old = old
Pierre-Yves Chibon 0a9634
        self.new = new
Pierre-Yves Chibon 0a9634
        self.rev = rev
Pierre-Yves Chibon 0a9634
        self.msgid = make_msgid()
Pierre-Yves Chibon 0a9634
        self.diffopts = environment.diffopts
Pierre-Yves Chibon 0a9634
        self.logopts = environment.logopts
Pierre-Yves Chibon 0a9634
        self.commitlogopts = environment.commitlogopts
Pierre-Yves Chibon 0a9634
        self.showlog = environment.refchange_showlog
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def _compute_values(self):
Pierre-Yves Chibon 0a9634
        values = Change._compute_values(self)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        values['change_type'] = self.change_type
Pierre-Yves Chibon 0a9634
        values['refname_type'] = self.refname_type
Pierre-Yves Chibon 0a9634
        values['refname'] = self.refname
Pierre-Yves Chibon 0a9634
        values['short_refname'] = self.short_refname
Pierre-Yves Chibon 0a9634
        values['msgid'] = self.msgid
Pierre-Yves Chibon 0a9634
        values['recipients'] = self.recipients
Pierre-Yves Chibon 0a9634
        values['oldrev'] = str(self.old)
Pierre-Yves Chibon 0a9634
        values['oldrev_short'] = self.old.short
Pierre-Yves Chibon 0a9634
        values['newrev'] = str(self.new)
Pierre-Yves Chibon 0a9634
        values['newrev_short'] = self.new.short
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if self.old:
Pierre-Yves Chibon 0a9634
            values['oldrev_type'] = self.old.type
Pierre-Yves Chibon 0a9634
        if self.new:
Pierre-Yves Chibon 0a9634
            values['newrev_type'] = self.new.type
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        reply_to = self.environment.get_reply_to_refchange(self)
Pierre-Yves Chibon 0a9634
        if reply_to:
Pierre-Yves Chibon 0a9634
            values['reply_to'] = reply_to
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return values
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_subject(self):
Pierre-Yves Chibon 0a9634
        template = {
Pierre-Yves Chibon 0b6d99
            'create': REF_CREATED_SUBJECT_TEMPLATE,
Pierre-Yves Chibon 0b6d99
            'update': REF_UPDATED_SUBJECT_TEMPLATE,
Pierre-Yves Chibon 0b6d99
            'delete': REF_DELETED_SUBJECT_TEMPLATE,
Pierre-Yves Chibon 0a9634
            }[self.change_type]
Pierre-Yves Chibon 0a9634
        return self.expand(template)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_header(self, **extra_values):
Pierre-Yves Chibon 0a9634
        if 'subject' not in extra_values:
Pierre-Yves Chibon 0a9634
            extra_values['subject'] = self.get_subject()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.expand_header_lines(
Pierre-Yves Chibon 0b6d99
                REFCHANGE_HEADER_TEMPLATE, **extra_values):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_intro(self):
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(REFCHANGE_INTRO_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_body(self, push):
Pierre-Yves Chibon 0a9634
        """Call the appropriate body-generation routine.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Call one of generate_create_summary() /
Pierre-Yves Chibon 0a9634
        generate_update_summary() / generate_delete_summary()."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        change_summary = {
Pierre-Yves Chibon 0b6d99
            'create': self.generate_create_summary,
Pierre-Yves Chibon 0b6d99
            'delete': self.generate_delete_summary,
Pierre-Yves Chibon 0b6d99
            'update': self.generate_update_summary,
Pierre-Yves Chibon 0a9634
            }[self.change_type](push)
Pierre-Yves Chibon 0a9634
        for line in change_summary:
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.generate_revision_change_summary(push):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_email_footer(self):
Pierre-Yves Chibon 0a9634
        return self.expand_lines(FOOTER_TEMPLATE)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_revision_change_log(self, new_commits_list):
Pierre-Yves Chibon 0a9634
        if self.showlog:
Pierre-Yves Chibon 0a9634
            yield '\n'
Pierre-Yves Chibon 0a9634
            yield 'Detailed log of new commits:\n\n'
Pierre-Yves Chibon 0a9634
            for line in read_git_lines(
Pierre-Yves Chibon 0a9634
                    ['log', '--no-walk']
Pierre-Yves Chibon 0a9634
                    + self.logopts
Pierre-Yves Chibon 0a9634
                    + new_commits_list
Pierre-Yves Chibon 0a9634
                    + ['--'],
Pierre-Yves Chibon 0b6d99
                    keepends=True,):
Pierre-Yves Chibon 0a9634
                yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_revision_change_summary(self, push):
Pierre-Yves Chibon 0b6d99
        """Generate a summary of the revisions added/removed by this
Pierre-Yves Chibon 0b6d99
        change."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if self.new.commit_sha1 and not self.old.commit_sha1:
Pierre-Yves Chibon 0a9634
            # A new reference was created.  List the new revisions
Pierre-Yves Chibon 0a9634
            # brought by the new reference (i.e., those revisions that
Pierre-Yves Chibon 0a9634
            # were not in the repository before this reference
Pierre-Yves Chibon 0a9634
            # change).
Pierre-Yves Chibon 0a9634
            sha1s = list(push.get_new_commits(self))
Pierre-Yves Chibon 0a9634
            sha1s.reverse()
Pierre-Yves Chibon 0a9634
            tot = len(sha1s)
Pierre-Yves Chibon 0a9634
            new_revisions = [
Pierre-Yves Chibon 0a9634
                Revision(self, GitObject(sha1), num=i+1, tot=tot)
Pierre-Yves Chibon 0a9634
                for (i, sha1) in enumerate(sha1s)
Pierre-Yves Chibon 0a9634
                ]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            if new_revisions:
Pierre-Yves Chibon 0b6d99
                yield self.expand(
Pierre-Yves Chibon 0b6d99
                    'This %(refname_type)s includes the following new '
Pierre-Yves Chibon 0b6d99
                    'commits:\n')
Pierre-Yves Chibon 0a9634
                yield '\n'
Pierre-Yves Chibon 0a9634
                for r in new_revisions:
Pierre-Yves Chibon 0a9634
                    (sha1, subject) = r.rev.get_summary()
Pierre-Yves Chibon 0a9634
                    yield r.expand(
Pierre-Yves Chibon 0a9634
                        BRIEF_SUMMARY_TEMPLATE, action='new', text=subject,
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
                yield '\n'
Pierre-Yves Chibon 0a9634
                for line in self.expand_lines(NEW_REVISIONS_TEMPLATE, tot=tot):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0b6d99
                for line in self.generate_revision_change_log(
Pierre-Yves Chibon 0b6d99
                        [r.rev.sha1 for r in new_revisions]):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                for line in self.expand_lines(NO_NEW_REVISIONS_TEMPLATE):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        elif self.new.commit_sha1 and self.old.commit_sha1:
Pierre-Yves Chibon 0a9634
            # A reference was changed to point at a different commit.
Pierre-Yves Chibon 0a9634
            # List the revisions that were removed and/or added *from
Pierre-Yves Chibon 0a9634
            # that reference* by this reference change, along with a
Pierre-Yves Chibon 0a9634
            # diff between the trees for its old and new values.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            # List of the revisions that were added to the branch by
Pierre-Yves Chibon 0a9634
            # this update.  Note this list can include revisions that
Pierre-Yves Chibon 0a9634
            # have already had notification emails; we want such
Pierre-Yves Chibon 0a9634
            # revisions in the summary even though we will not send
Pierre-Yves Chibon 0a9634
            # new notification emails for them.
Pierre-Yves Chibon 0a9634
            adds = list(generate_summaries(
Pierre-Yves Chibon 0b6d99
                '--topo-order', '--reverse', '%s..%s'
Pierre-Yves Chibon 0b6d99
                % (self.old.commit_sha1, self.new.commit_sha1,)
Pierre-Yves Chibon 0b6d99
                ))
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            # List of the revisions that were removed from the branch
Pierre-Yves Chibon 0a9634
            # by this update.  This will be empty except for
Pierre-Yves Chibon 0a9634
            # non-fast-forward updates.
Pierre-Yves Chibon 0a9634
            discards = list(generate_summaries(
Pierre-Yves Chibon 0b6d99
                '%s..%s' % (self.new.commit_sha1, self.old.commit_sha1,)
Pierre-Yves Chibon 0b6d99
                ))
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            if adds:
Pierre-Yves Chibon 0a9634
                new_commits_list = push.get_new_commits(self)
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                new_commits_list = []
Pierre-Yves Chibon 0a9634
            new_commits = CommitSet(new_commits_list)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            if discards:
Pierre-Yves Chibon 0b6d99
                discarded_commits = CommitSet(
Pierre-Yves Chibon 0b6d99
                    push.get_discarded_commits(self))
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                discarded_commits = CommitSet([])
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            if discards and adds:
Pierre-Yves Chibon 0a9634
                for (sha1, subject) in discards:
Pierre-Yves Chibon 0a9634
                    if sha1 in discarded_commits:
Pierre-Yves Chibon 0a9634
                        action = 'discards'
Pierre-Yves Chibon 0a9634
                    else:
Pierre-Yves Chibon 0a9634
                        action = 'omits'
Pierre-Yves Chibon 0a9634
                    yield self.expand(
Pierre-Yves Chibon 0a9634
                        BRIEF_SUMMARY_TEMPLATE, action=action,
Pierre-Yves Chibon 0a9634
                        rev_short=sha1, text=subject,
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
                for (sha1, subject) in adds:
Pierre-Yves Chibon 0a9634
                    if sha1 in new_commits:
Pierre-Yves Chibon 0a9634
                        action = 'new'
Pierre-Yves Chibon 0a9634
                    else:
Pierre-Yves Chibon 0a9634
                        action = 'adds'
Pierre-Yves Chibon 0a9634
                    yield self.expand(
Pierre-Yves Chibon 0a9634
                        BRIEF_SUMMARY_TEMPLATE, action=action,
Pierre-Yves Chibon 0a9634
                        rev_short=sha1, text=subject,
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
                yield '\n'
Pierre-Yves Chibon 0a9634
                for line in self.expand_lines(NON_FF_TEMPLATE):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            elif discards:
Pierre-Yves Chibon 0a9634
                for (sha1, subject) in discards:
Pierre-Yves Chibon 0a9634
                    if sha1 in discarded_commits:
Pierre-Yves Chibon 0a9634
                        action = 'discards'
Pierre-Yves Chibon 0a9634
                    else:
Pierre-Yves Chibon 0a9634
                        action = 'omits'
Pierre-Yves Chibon 0a9634
                    yield self.expand(
Pierre-Yves Chibon 0a9634
                        BRIEF_SUMMARY_TEMPLATE, action=action,
Pierre-Yves Chibon 0a9634
                        rev_short=sha1, text=subject,
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
                yield '\n'
Pierre-Yves Chibon 0a9634
                for line in self.expand_lines(REWIND_ONLY_TEMPLATE):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            elif adds:
Pierre-Yves Chibon 0a9634
                (sha1, subject) = self.old.get_summary()
Pierre-Yves Chibon 0a9634
                yield self.expand(
Pierre-Yves Chibon 0a9634
                    BRIEF_SUMMARY_TEMPLATE, action='from',
Pierre-Yves Chibon 0a9634
                    rev_short=sha1, text=subject,
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
                for (sha1, subject) in adds:
Pierre-Yves Chibon 0a9634
                    if sha1 in new_commits:
Pierre-Yves Chibon 0a9634
                        action = 'new'
Pierre-Yves Chibon 0a9634
                    else:
Pierre-Yves Chibon 0a9634
                        action = 'adds'
Pierre-Yves Chibon 0a9634
                    yield self.expand(
Pierre-Yves Chibon 0a9634
                        BRIEF_SUMMARY_TEMPLATE, action=action,
Pierre-Yves Chibon 0a9634
                        rev_short=sha1, text=subject,
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            yield '\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            if new_commits:
Pierre-Yves Chibon 0b6d99
                for line in self.expand_lines(
Pierre-Yves Chibon 0b6d99
                        NEW_REVISIONS_TEMPLATE, tot=len(new_commits)):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0b6d99
                for line in self.generate_revision_change_log(
Pierre-Yves Chibon 0b6d99
                        new_commits_list):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                for line in self.expand_lines(NO_NEW_REVISIONS_TEMPLATE):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            # The diffstat is shown from the old revision to the new
Pierre-Yves Chibon 0a9634
            # revision.  This is to show the truth of what happened in
Pierre-Yves Chibon 0a9634
            # this change.  There's no point showing the stat from the
Pierre-Yves Chibon 0a9634
            # base to the new revision because the base is effectively a
Pierre-Yves Chibon 0a9634
            # random revision at this point - the user will be interested
Pierre-Yves Chibon 0a9634
            # in what this revision changed - including the undoing of
Pierre-Yves Chibon 0a9634
            # previous revisions in the case of non-fast-forward updates.
Pierre-Yves Chibon 0a9634
            yield '\n'
Pierre-Yves Chibon 0a9634
            yield 'Summary of changes:\n'
Pierre-Yves Chibon 0a9634
            for line in read_git_lines(
Pierre-Yves Chibon 0b6d99
                    ['diff-tree']
Pierre-Yves Chibon 0b6d99
                    + self.diffopts
Pierre-Yves Chibon 0b6d99
                    + ['%s..%s' % (
Pierre-Yves Chibon 0b6d99
                        self.old.commit_sha1, self.new.commit_sha1,)],
Pierre-Yves Chibon 0b6d99
                    keepends=True,):
Pierre-Yves Chibon 0a9634
                yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        elif self.old.commit_sha1 and not self.new.commit_sha1:
Pierre-Yves Chibon 0a9634
            # A reference was deleted.  List the revisions that were
Pierre-Yves Chibon 0a9634
            # removed from the repository by this reference change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            sha1s = list(push.get_discarded_commits(self))
Pierre-Yves Chibon 0a9634
            tot = len(sha1s)
Pierre-Yves Chibon 0a9634
            discarded_revisions = [
Pierre-Yves Chibon 0a9634
                Revision(self, GitObject(sha1), num=i+1, tot=tot)
Pierre-Yves Chibon 0a9634
                for (i, sha1) in enumerate(sha1s)
Pierre-Yves Chibon 0a9634
                ]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            if discarded_revisions:
Pierre-Yves Chibon 0a9634
                for line in self.expand_lines(DISCARDED_REVISIONS_TEMPLATE):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
                yield '\n'
Pierre-Yves Chibon 0a9634
                for r in discarded_revisions:
Pierre-Yves Chibon 0a9634
                    (sha1, subject) = r.rev.get_summary()
Pierre-Yves Chibon 0a9634
                    yield r.expand(
Pierre-Yves Chibon 0b6d99
                        BRIEF_SUMMARY_TEMPLATE, action='discards',
Pierre-Yves Chibon 0b6d99
                        text=subject,
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0b6d99
                for line in self.expand_lines(
Pierre-Yves Chibon 0b6d99
                        NO_DISCARDED_REVISIONS_TEMPLATE):
Pierre-Yves Chibon 0a9634
                    yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        elif not self.old.commit_sha1 and not self.new.commit_sha1:
Pierre-Yves Chibon 0a9634
            for line in self.expand_lines(NON_COMMIT_UPDATE_TEMPLATE):
Pierre-Yves Chibon 0a9634
                yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_create_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called for the creation of a reference."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # This is a new reference and so oldrev is not valid
Pierre-Yves Chibon 0a9634
        (sha1, subject) = self.new.get_summary()
Pierre-Yves Chibon 0a9634
        yield self.expand(
Pierre-Yves Chibon 0a9634
            BRIEF_SUMMARY_TEMPLATE, action='at',
Pierre-Yves Chibon 0a9634
            rev_short=sha1, text=subject,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        yield '\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_update_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called for the change of a pre-existing branch."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return iter([])
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_delete_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called for the deletion of any type of reference."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        (sha1, subject) = self.old.get_summary()
Pierre-Yves Chibon 0a9634
        yield self.expand(
Pierre-Yves Chibon 0a9634
            BRIEF_SUMMARY_TEMPLATE, action='was',
Pierre-Yves Chibon 0a9634
            rev_short=sha1, text=subject,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        yield '\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class BranchChange(ReferenceChange):
Pierre-Yves Chibon 0a9634
    refname_type = 'branch'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, environment, refname, short_refname, old, new, rev):
Pierre-Yves Chibon 0a9634
        ReferenceChange.__init__(
Pierre-Yves Chibon 0a9634
            self, environment,
Pierre-Yves Chibon 0a9634
            refname=refname, short_refname=short_refname,
Pierre-Yves Chibon 0a9634
            old=old, new=new, rev=rev,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        self.recipients = environment.get_refchange_recipients(self)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class AnnotatedTagChange(ReferenceChange):
Pierre-Yves Chibon 0a9634
    refname_type = 'annotated tag'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, environment, refname, short_refname, old, new, rev):
Pierre-Yves Chibon 0a9634
        ReferenceChange.__init__(
Pierre-Yves Chibon 0a9634
            self, environment,
Pierre-Yves Chibon 0a9634
            refname=refname, short_refname=short_refname,
Pierre-Yves Chibon 0a9634
            old=old, new=new, rev=rev,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        self.recipients = environment.get_announce_recipients(self)
Pierre-Yves Chibon 0a9634
        self.show_shortlog = environment.announce_show_shortlog
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    ANNOTATED_TAG_FORMAT = (
Pierre-Yves Chibon 0a9634
        '%(*objectname)\n'
Pierre-Yves Chibon 0a9634
        '%(*objecttype)\n'
Pierre-Yves Chibon 0a9634
        '%(taggername)\n'
Pierre-Yves Chibon 0a9634
        '%(taggerdate)'
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def describe_tag(self, push):
Pierre-Yves Chibon 0a9634
        """Describe the new value of an annotated tag."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # Use git for-each-ref to pull out the individual fields from
Pierre-Yves Chibon 0a9634
        # the tag
Pierre-Yves Chibon 0a9634
        [tagobject, tagtype, tagger, tagged] = read_git_lines(
Pierre-Yves Chibon 0b6d99
            ['for-each-ref', '--format=%s' % (
Pierre-Yves Chibon 0b6d99
                self.ANNOTATED_TAG_FORMAT,), self.refname],
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        yield self.expand(
Pierre-Yves Chibon 0a9634
            BRIEF_SUMMARY_TEMPLATE, action='tagging',
Pierre-Yves Chibon 0a9634
            rev_short=tagobject, text='(%s)' % (tagtype,),
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        if tagtype == 'commit':
Pierre-Yves Chibon 0a9634
            # If the tagged object is a commit, then we assume this is a
Pierre-Yves Chibon 0a9634
            # release, and so we calculate which tag this tag is
Pierre-Yves Chibon 0a9634
            # replacing
Pierre-Yves Chibon 0a9634
            try:
Pierre-Yves Chibon 0b6d99
                prevtag = read_git_output(
Pierre-Yves Chibon 0b6d99
                    ['describe', '--abbrev=0', '%s^' % (self.new,)])
Pierre-Yves Chibon 0a9634
            except CommandError:
Pierre-Yves Chibon 0a9634
                prevtag = None
Pierre-Yves Chibon 0a9634
            if prevtag:
Pierre-Yves Chibon 0a9634
                yield '  replaces  %s\n' % (prevtag,)
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            prevtag = None
Pierre-Yves Chibon 0b6d99
            yield '    length  %s bytes\n' % (read_git_output(
Pierre-Yves Chibon 0b6d99
                ['cat-file', '-s', tagobject]),)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        yield ' tagged by  %s\n' % (tagger,)
Pierre-Yves Chibon 0a9634
        yield '        on  %s\n' % (tagged,)
Pierre-Yves Chibon 0a9634
        yield '\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # Show the content of the tag message; this might contain a
Pierre-Yves Chibon 0a9634
        # change log or release notes so is worth displaying.
Pierre-Yves Chibon 0a9634
        yield LOGBEGIN
Pierre-Yves Chibon 0b6d99
        contents = list(read_git_lines(
Pierre-Yves Chibon 0b6d99
            ['cat-file', 'tag', self.new.sha1], keepends=True))
Pierre-Yves Chibon 0a9634
        contents = contents[contents.index('\n') + 1:]
Pierre-Yves Chibon 0a9634
        if contents and contents[-1][-1:] != '\n':
Pierre-Yves Chibon 0a9634
            contents.append('\n')
Pierre-Yves Chibon 0a9634
        for line in contents:
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if self.show_shortlog and tagtype == 'commit':
Pierre-Yves Chibon 0a9634
            # Only commit tags make sense to have rev-list operations
Pierre-Yves Chibon 0a9634
            # performed on them
Pierre-Yves Chibon 0a9634
            yield '\n'
Pierre-Yves Chibon 0a9634
            if prevtag:
Pierre-Yves Chibon 0a9634
                # Show changes since the previous release
Pierre-Yves Chibon 0a9634
                revlist = read_git_output(
Pierre-Yves Chibon 0b6d99
                    ['rev-list', '--pretty=short',
Pierre-Yves Chibon 0b6d99
                     '%s..%s' % (prevtag, self.new,)],
Pierre-Yves Chibon 0a9634
                    keepends=True,
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                # No previous tag, show all the changes since time
Pierre-Yves Chibon 0a9634
                # began
Pierre-Yves Chibon 0a9634
                revlist = read_git_output(
Pierre-Yves Chibon 0a9634
                    ['rev-list', '--pretty=short', '%s' % (self.new,)],
Pierre-Yves Chibon 0a9634
                    keepends=True,
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0b6d99
            for line in read_git_lines(
Pierre-Yves Chibon 0b6d99
                    ['shortlog'], input=revlist, keepends=True):
Pierre-Yves Chibon 0a9634
                yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        yield LOGEND
Pierre-Yves Chibon 0a9634
        yield '\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_create_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called for the creation of an annotated tag."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(TAG_CREATED_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.describe_tag(push):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_update_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called for the update of an annotated tag.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        This is probably a rare event and may not even be allowed."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(TAG_UPDATED_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.describe_tag(push):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_delete_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called when a non-annotated reference is updated."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(TAG_DELETED_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        yield self.expand('   tag was  %(oldrev_short)s\n')
Pierre-Yves Chibon 0a9634
        yield '\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class NonAnnotatedTagChange(ReferenceChange):
Pierre-Yves Chibon 0a9634
    refname_type = 'tag'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, environment, refname, short_refname, old, new, rev):
Pierre-Yves Chibon 0a9634
        ReferenceChange.__init__(
Pierre-Yves Chibon 0a9634
            self, environment,
Pierre-Yves Chibon 0a9634
            refname=refname, short_refname=short_refname,
Pierre-Yves Chibon 0a9634
            old=old, new=new, rev=rev,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        self.recipients = environment.get_refchange_recipients(self)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_create_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called for the creation of an annotated tag."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(TAG_CREATED_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_update_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called when a non-annotated reference is updated."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(TAG_UPDATED_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def generate_delete_summary(self, push):
Pierre-Yves Chibon 0a9634
        """Called when a non-annotated reference is updated."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in self.expand_lines(TAG_DELETED_TEMPLATE):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for line in ReferenceChange.generate_delete_summary(self, push):
Pierre-Yves Chibon 0a9634
            yield line
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class OtherReferenceChange(ReferenceChange):
Pierre-Yves Chibon 0a9634
    refname_type = 'reference'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, environment, refname, short_refname, old, new, rev):
Pierre-Yves Chibon 0a9634
        # We use the full refname as short_refname, because otherwise
Pierre-Yves Chibon 0a9634
        # the full name of the reference would not be obvious from the
Pierre-Yves Chibon 0a9634
        # text of the email.
Pierre-Yves Chibon 0a9634
        ReferenceChange.__init__(
Pierre-Yves Chibon 0a9634
            self, environment,
Pierre-Yves Chibon 0a9634
            refname=refname, short_refname=refname,
Pierre-Yves Chibon 0a9634
            old=old, new=new, rev=rev,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        self.recipients = environment.get_refchange_recipients(self)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class Mailer(object):
Pierre-Yves Chibon 0a9634
    """An object that can send emails."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def send(self, lines, to_addrs):
Pierre-Yves Chibon 0a9634
        """Send an email consisting of lines.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        lines must be an iterable over the lines constituting the
Pierre-Yves Chibon 0a9634
        header and body of the email.  to_addrs is a list of recipient
Pierre-Yves Chibon 0a9634
        addresses (can be needed even if lines already contains a
Pierre-Yves Chibon 0a9634
        "To:" field).  It can be either a string (comma-separated list
Pierre-Yves Chibon 0a9634
        of email addresses) or a Python list of individual email
Pierre-Yves Chibon 0a9634
        addresses.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        """
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class SendMailer(Mailer):
Pierre-Yves Chibon 0a9634
    """Send emails using 'sendmail -oi -t'."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    SENDMAIL_CANDIDATES = [
Pierre-Yves Chibon 0a9634
        '/usr/sbin/sendmail',
Pierre-Yves Chibon 0a9634
        '/usr/lib/sendmail',
Pierre-Yves Chibon 0a9634
        ]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    @staticmethod
Pierre-Yves Chibon 0a9634
    def find_sendmail():
Pierre-Yves Chibon 0a9634
        for path in SendMailer.SENDMAIL_CANDIDATES:
Pierre-Yves Chibon 0a9634
            if os.access(path, os.X_OK):
Pierre-Yves Chibon 0a9634
                return path
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            raise ConfigurationException(
Pierre-Yves Chibon 0a9634
                'No sendmail executable found.  '
Pierre-Yves Chibon 0a9634
                'Try setting multimailhook.sendmailCommand.'
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, command=None, envelopesender=None):
Pierre-Yves Chibon 0a9634
        """Construct a SendMailer instance.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        command should be the command and arguments used to invoke
Pierre-Yves Chibon 0a9634
        sendmail, as a list of strings.  If an envelopesender is
Pierre-Yves Chibon 0a9634
        provided, it will also be passed to the command, via '-f
Pierre-Yves Chibon 0a9634
        envelopesender'."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if command:
Pierre-Yves Chibon 0a9634
            self.command = command[:]
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            self.command = [self.find_sendmail(), '-oi', '-t']
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if envelopesender:
Pierre-Yves Chibon 0a9634
            self.command.extend(['-f', envelopesender])
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def send(self, lines, to_addrs):
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            p = subprocess.Popen(self.command, stdin=subprocess.PIPE)
Pierre-Yves Chibon 0a9634
        except OSError, e:
Pierre-Yves Chibon 0a9634
            sys.stderr.write(
Pierre-Yves Chibon 0a9634
                '*** Cannot execute command: %s\n' % ' '.join(self.command)
Pierre-Yves Chibon 0a9634
                + '*** %s\n' % str(e)
Pierre-Yves Chibon 0a9634
                + '*** Try setting multimailhook.mailer to "smtp"\n'
Pierre-Yves Chibon 0a9634
                '*** to send emails without using the sendmail command.\n'
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
            sys.exit(1)
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            p.stdin.writelines(lines)
Pierre-Yves Chibon 0a9634
        except:
Pierre-Yves Chibon 0a9634
            sys.stderr.write(
Pierre-Yves Chibon 0a9634
                '*** Error while generating commit email\n'
Pierre-Yves Chibon 0a9634
                '***  - mail sending aborted.\n'
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
            p.terminate()
Pierre-Yves Chibon 0a9634
            raise
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            p.stdin.close()
Pierre-Yves Chibon 0a9634
            retcode = p.wait()
Pierre-Yves Chibon 0a9634
            if retcode:
Pierre-Yves Chibon 0a9634
                raise CommandError(self.command, retcode)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class SMTPMailer(Mailer):
Pierre-Yves Chibon 0a9634
    """Send emails using Python's smtplib."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, envelopesender, smtpserver):
Pierre-Yves Chibon 0a9634
        if not envelopesender:
Pierre-Yves Chibon 0a9634
            sys.stderr.write(
Pierre-Yves Chibon 0b6d99
                'fatal: git_multimail: cannot use SMTPMailer without a '
Pierre-Yves Chibon 0b6d99
                'sender address.\n'
Pierre-Yves Chibon 0b6d99
                'please set either multimailhook.envelopeSender or '
Pierre-Yves Chibon 0b6d99
                'user.email\n'
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
            sys.exit(1)
Pierre-Yves Chibon 0a9634
        self.envelopesender = envelopesender
Pierre-Yves Chibon 0a9634
        self.smtpserver = smtpserver
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            self.smtp = smtplib.SMTP(self.smtpserver)
Pierre-Yves Chibon 0a9634
        except Exception, e:
Pierre-Yves Chibon 0b6d99
            sys.stderr.write(
Pierre-Yves Chibon 0b6d99
                '*** Error establishing SMTP connection to %s***\n' %
Pierre-Yves Chibon 0b6d99
                self.smtpserver)
Pierre-Yves Chibon 0a9634
            sys.stderr.write('*** %s\n' % str(e))
Pierre-Yves Chibon 0a9634
            sys.exit(1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __del__(self):
Pierre-Yves Chibon 0a9634
        self.smtp.quit()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def send(self, lines, to_addrs):
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0a9634
            msg = ''.join(lines)
Pierre-Yves Chibon 0a9634
            # turn comma-separated list into Python list if needed.
Pierre-Yves Chibon 0a9634
            if isinstance(to_addrs, basestring):
Pierre-Yves Chibon 0b6d99
                to_addrs = [
Pierre-Yves Chibon 0b6d99
                    email for (name, email) in getaddresses([to_addrs])]
Pierre-Yves Chibon 0a9634
            self.smtp.sendmail(self.envelopesender, to_addrs, msg)
Pierre-Yves Chibon 0a9634
        except Exception, e:
Pierre-Yves Chibon 0a9634
            sys.stderr.write('*** Error sending email***\n')
Pierre-Yves Chibon 0a9634
            sys.stderr.write('*** %s\n' % str(e))
Pierre-Yves Chibon 0a9634
            self.smtp.quit()
Pierre-Yves Chibon 0a9634
            sys.exit(1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class OutputMailer(Mailer):
Pierre-Yves Chibon 0b6d99
    """Write emails to an output stream, bracketed by lines of '='
Pierre-Yves Chibon 0b6d99
    characters.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    This is intended for debugging purposes."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    SEPARATOR = '=' * 75 + '\n'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, f):
Pierre-Yves Chibon 0a9634
        self.f = f
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def send(self, lines, to_addrs):
Pierre-Yves Chibon 0a9634
        self.f.write(self.SEPARATOR)
Pierre-Yves Chibon 0a9634
        self.f.writelines(lines)
Pierre-Yves Chibon 0a9634
        self.f.write(self.SEPARATOR)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def get_git_dir():
Pierre-Yves Chibon 0a9634
    """Determine GIT_DIR.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    Determine GIT_DIR either from the GIT_DIR environment variable or
Pierre-Yves Chibon 0a9634
    from the working directory, using Git's usual rules."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    try:
Pierre-Yves Chibon 0a9634
        return read_git_output(['rev-parse', '--git-dir'])
Pierre-Yves Chibon 0a9634
    except CommandError:
Pierre-Yves Chibon 0a9634
        sys.stderr.write('fatal: git_multimail: not in a git directory\n')
Pierre-Yves Chibon 0a9634
        sys.exit(1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class Environment(object):
Pierre-Yves Chibon 0a9634
    """Describes the environment in which the push is occurring.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    An Environment object encapsulates information about the local
Pierre-Yves Chibon 0a9634
    environment.  For example, it knows how to determine:
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    * the name of the repository to which the push occurred
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    * what user did the push
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    * what users want to be informed about various types of changes.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    An Environment object is expected to have the following methods:
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_repo_shortname()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return a short name for the repository, for display
Pierre-Yves Chibon 0a9634
            purposes.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_repo_path()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return the absolute path to the Git repository.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_emailprefix()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return a string that will be prefixed to every email's
Pierre-Yves Chibon 0a9634
            subject.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_pusher()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return the username of the person who pushed the changes.
Pierre-Yves Chibon 0a9634
            This value is used in the email body to indicate who
Pierre-Yves Chibon 0a9634
            pushed the change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_pusher_email() (may return None)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return the email address of the person who pushed the
Pierre-Yves Chibon 0a9634
            changes.  The value should be a single RFC 2822 email
Pierre-Yves Chibon 0a9634
            address as a string; e.g., "Joe User <user@example.com>"</user@example.com>
Pierre-Yves Chibon 0a9634
            if available, otherwise "user@example.com".  If set, the
Pierre-Yves Chibon 0a9634
            value is used as the Reply-To address for refchange
Pierre-Yves Chibon 0a9634
            emails.  If it is impossible to determine the pusher's
Pierre-Yves Chibon 0a9634
            email, this attribute should be set to None (in which case
Pierre-Yves Chibon 0a9634
            no Reply-To header will be output).
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_sender()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return the address to be used as the 'From' email address
Pierre-Yves Chibon 0a9634
            in the email envelope.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_fromaddr()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return the 'From' email address used in the email 'From:'
Pierre-Yves Chibon 0a9634
            headers.  (May be a full RFC 2822 email address like 'Joe
Pierre-Yves Chibon 0a9634
            User <user@example.com>'.)</user@example.com>
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_administrator()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return the name and/or email of the repository
Pierre-Yves Chibon 0a9634
            administrator.  This value is used in the footer as the
Pierre-Yves Chibon 0a9634
            person to whom requests to be removed from the
Pierre-Yves Chibon 0a9634
            notification list should be sent.  Ideally, it should
Pierre-Yves Chibon 0a9634
            include a valid email address.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        get_reply_to_refchange()
Pierre-Yves Chibon 0a9634
        get_reply_to_commit()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Return the address to use in the email "Reply-To" header,
Pierre-Yves Chibon 0a9634
            as a string.  These can be an RFC 2822 email address, or
Pierre-Yves Chibon 0a9634
            None to omit the "Reply-To" header.
Pierre-Yves Chibon 0a9634
            get_reply_to_refchange() is used for refchange emails;
Pierre-Yves Chibon 0a9634
            get_reply_to_commit() is used for individual commit
Pierre-Yves Chibon 0a9634
            emails.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    They should also define the following attributes:
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        announce_show_shortlog (bool)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            True iff announce emails should include a shortlog.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        refchange_showlog (bool)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            True iff refchanges emails should include a detailed log.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        diffopts (list of strings)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            The options that should be passed to 'git diff' for the
Pierre-Yves Chibon 0a9634
            summary email.  The value should be a list of strings
Pierre-Yves Chibon 0a9634
            representing words to be passed to the command.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        logopts (list of strings)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            Analogous to diffopts, but contains options passed to
Pierre-Yves Chibon 0a9634
            'git log' when generating the detailed log for a set of
Pierre-Yves Chibon 0a9634
            commits (see refchange_showlog)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        commitlogopts (list of strings)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            The options that should be passed to 'git log' for each
Pierre-Yves Chibon 0a9634
            commit mail.  The value should be a list of strings
Pierre-Yves Chibon 0a9634
            representing words to be passed to the command.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    """
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    REPO_NAME_RE = re.compile(r'^(?P<name>.+?)(?:\.git)$')</name>
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, osenv=None):
Pierre-Yves Chibon 0a9634
        self.osenv = osenv or os.environ
Pierre-Yves Chibon 0a9634
        self.announce_show_shortlog = False
Pierre-Yves Chibon 0a9634
        self.maxcommitemails = 500
Pierre-Yves Chibon 0a9634
        self.diffopts = ['--stat', '--summary', '--find-copies-harder']
Pierre-Yves Chibon 0a9634
        self.logopts = []
Pierre-Yves Chibon 0a9634
        self.refchange_showlog = False
Pierre-Yves Chibon 0a9634
        self.commitlogopts = ['-C', '--stat', '-p', '--cc']
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        self.COMPUTED_KEYS = [
Pierre-Yves Chibon 0a9634
            'administrator',
Pierre-Yves Chibon 0a9634
            'charset',
Pierre-Yves Chibon 0a9634
            'emailprefix',
Pierre-Yves Chibon 0a9634
            'fromaddr',
Pierre-Yves Chibon 0a9634
            'pusher',
Pierre-Yves Chibon 0a9634
            'pusher_email',
Pierre-Yves Chibon 0a9634
            'repo_path',
Pierre-Yves Chibon 0a9634
            'repo_shortname',
Pierre-Yves Chibon 0a9634
            'sender',
Pierre-Yves Chibon 0a9634
            ]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        self._values = None
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_repo_shortname(self):
Pierre-Yves Chibon 0b6d99
        """Use the last part of the repo path, with ".git" stripped off if
Pierre-Yves Chibon 0b6d99
        present."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        basename = os.path.basename(os.path.abspath(self.get_repo_path()))
Pierre-Yves Chibon 0a9634
        m = self.REPO_NAME_RE.match(basename)
Pierre-Yves Chibon 0a9634
        if m:
Pierre-Yves Chibon 0a9634
            return m.group('name')
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            return basename
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_pusher(self):
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_pusher_email(self):
Pierre-Yves Chibon 0a9634
        return None
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_administrator(self):
Pierre-Yves Chibon 0a9634
        return 'the administrator of this repository'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_emailprefix(self):
Pierre-Yves Chibon 0a9634
        return ''
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_repo_path(self):
Pierre-Yves Chibon 0a9634
        if read_git_output(['rev-parse', '--is-bare-repository']) == 'true':
Pierre-Yves Chibon 0a9634
            path = get_git_dir()
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            path = read_git_output(['rev-parse', '--show-toplevel'])
Pierre-Yves Chibon 0a9634
        return os.path.abspath(path)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_charset(self):
Pierre-Yves Chibon 0a9634
        return CHARSET
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_values(self):
Pierre-Yves Chibon 0a9634
        """Return a dictionary {keyword : expansion} for this Environment.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        This method is called by Change._compute_values().  The keys
Pierre-Yves Chibon 0a9634
        in the returned dictionary are available to be used in any of
Pierre-Yves Chibon 0a9634
        the templates.  The dictionary is created by calling
Pierre-Yves Chibon 0a9634
        self.get_NAME() for each of the attributes named in
Pierre-Yves Chibon 0a9634
        COMPUTED_KEYS and recording those that do not return None.
Pierre-Yves Chibon 0a9634
        The return value is always a new dictionary."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if self._values is None:
Pierre-Yves Chibon 0a9634
            values = {}
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            for key in self.COMPUTED_KEYS:
Pierre-Yves Chibon 0a9634
                value = getattr(self, 'get_%s' % (key,))()
Pierre-Yves Chibon 0a9634
                if value is not None:
Pierre-Yves Chibon 0a9634
                    values[key] = value
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            self._values = values
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return self._values.copy()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_refchange_recipients(self, refchange):
Pierre-Yves Chibon 0a9634
        """Return the recipients for notifications about refchange.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return the list of email addresses to which notifications
Pierre-Yves Chibon 0a9634
        about the specified ReferenceChange should be sent."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_announce_recipients(self, annotated_tag_change):
Pierre-Yves Chibon 0b6d99
        """Return the recipients for notifications about
Pierre-Yves Chibon 0b6d99
        annotated_tag_change.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return the list of email addresses to which notifications
Pierre-Yves Chibon 0a9634
        about the specified AnnotatedTagChange should be sent."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_reply_to_refchange(self, refchange):
Pierre-Yves Chibon 0a9634
        return self.get_pusher_email()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_revision_recipients(self, revision):
Pierre-Yves Chibon 0a9634
        """Return the recipients for messages about revision.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return the list of email addresses to which notifications
Pierre-Yves Chibon 0a9634
        about the specified Revision should be sent.  This method
Pierre-Yves Chibon 0a9634
        could be overridden, for example, to take into account the
Pierre-Yves Chibon 0a9634
        contents of the revision when deciding whom to notify about
Pierre-Yves Chibon 0a9634
        it.  For example, there could be a scheme for users to express
Pierre-Yves Chibon 0a9634
        interest in particular files or subdirectories, and only
Pierre-Yves Chibon 0a9634
        receive notification emails for revisions that affecting those
Pierre-Yves Chibon 0a9634
        files."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        raise NotImplementedError()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_reply_to_commit(self, revision):
Pierre-Yves Chibon 0a9634
        return revision.author
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def filter_body(self, lines):
Pierre-Yves Chibon 0a9634
        """Filter the lines intended for an email body.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        lines is an iterable over the lines that would go into the
Pierre-Yves Chibon 0a9634
        email body.  Filter it (e.g., limit the number of lines, the
Pierre-Yves Chibon 0a9634
        line length, character set, etc.), returning another iterable.
Pierre-Yves Chibon 0a9634
        See FilterLinesEnvironmentMixin and MaxlinesEnvironmentMixin
Pierre-Yves Chibon 0a9634
        for classes implementing this functionality."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return lines
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ConfigEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    """A mixin that sets self.config to its constructor's config argument.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    This class's constructor consumes the "config" argument.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    Mixins that need to inspect the config should inherit from this
Pierre-Yves Chibon 0a9634
    class (1) to make sure that "config" is still in the constructor
Pierre-Yves Chibon 0a9634
    arguments with its own constructor runs and/or (2) to be sure that
Pierre-Yves Chibon 0a9634
    self.config is set after construction."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, config, **kw):
Pierre-Yves Chibon 0a9634
        super(ConfigEnvironmentMixin, self).__init__(**kw)
Pierre-Yves Chibon 0a9634
        self.config = config
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ConfigOptionsEnvironmentMixin(ConfigEnvironmentMixin):
Pierre-Yves Chibon 0b6d99
    """An Environment that reads most of its information from "git config".
Pierre-Yves Chibon 0b6d99
    """
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, config, **kw):
Pierre-Yves Chibon 0a9634
        super(ConfigOptionsEnvironmentMixin, self).__init__(
Pierre-Yves Chibon 0a9634
            config=config, **kw
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        self.announce_show_shortlog = config.get_bool(
Pierre-Yves Chibon 0a9634
            'announceshortlog', default=self.announce_show_shortlog
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        self.refchange_showlog = config.get_bool(
Pierre-Yves Chibon 0a9634
            'refchangeshowlog', default=self.refchange_showlog
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        maxcommitemails = config.get('maxcommitemails')
Pierre-Yves Chibon 0a9634
        if maxcommitemails is not None:
Pierre-Yves Chibon 0a9634
            try:
Pierre-Yves Chibon 0a9634
                self.maxcommitemails = int(maxcommitemails)
Pierre-Yves Chibon 0a9634
            except ValueError:
Pierre-Yves Chibon 0a9634
                sys.stderr.write(
Pierre-Yves Chibon 0b6d99
                    '*** Malformed value for multimailhook.maxCommitEmails: '
Pierre-Yves Chibon 0b6d99
                    '%s\n' % maxcommitemails
Pierre-Yves Chibon 0a9634
                    + '*** Expected a number.  Ignoring.\n'
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        diffopts = config.get('diffopts')
Pierre-Yves Chibon 0a9634
        if diffopts is not None:
Pierre-Yves Chibon 0a9634
            self.diffopts = shlex.split(diffopts)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        logopts = config.get('logopts')
Pierre-Yves Chibon 0a9634
        if logopts is not None:
Pierre-Yves Chibon 0a9634
            self.logopts = shlex.split(logopts)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        commitlogopts = config.get('commitlogopts')
Pierre-Yves Chibon 0a9634
        if commitlogopts is not None:
Pierre-Yves Chibon 0a9634
            self.commitlogopts = shlex.split(commitlogopts)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        reply_to = config.get('replyTo')
Pierre-Yves Chibon 0b6d99
        self.__reply_to_refchange = config.get(
Pierre-Yves Chibon 0b6d99
            'replyToRefchange', default=reply_to)
Pierre-Yves Chibon 0a9634
        if (
Pierre-Yves Chibon 0a9634
            self.__reply_to_refchange is not None
Pierre-Yves Chibon 0b6d99
                and self.__reply_to_refchange.lower() == 'author'):
Pierre-Yves Chibon 0a9634
            raise ConfigurationException(
Pierre-Yves Chibon 0a9634
                '"author" is not an allowed setting for replyToRefchange'
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0b6d99
        self.__reply_to_commit = config.get(
Pierre-Yves Chibon 0b6d99
            'replyToCommit', default=reply_to)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_administrator(self):
Pierre-Yves Chibon 0a9634
        return (
Pierre-Yves Chibon 0a9634
            self.config.get('administrator')
Pierre-Yves Chibon 0a9634
            or self.get_sender()
Pierre-Yves Chibon 0b6d99
            or super(
Pierre-Yves Chibon 0b6d99
                ConfigOptionsEnvironmentMixin, self).get_administrator()
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_repo_shortname(self):
Pierre-Yves Chibon 0a9634
        return (
Pierre-Yves Chibon 0a9634
            self.config.get('reponame')
Pierre-Yves Chibon 0b6d99
            or super(
Pierre-Yves Chibon 0b6d99
                ConfigOptionsEnvironmentMixin, self).get_repo_shortname()
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_emailprefix(self):
Pierre-Yves Chibon 0a9634
        emailprefix = self.config.get('emailprefix')
Pierre-Yves Chibon 0a9634
        if emailprefix and emailprefix.strip():
Pierre-Yves Chibon 0a9634
            return emailprefix.strip() + ' '
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            return '[%s] ' % (self.get_repo_shortname(),)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_sender(self):
Pierre-Yves Chibon 0a9634
        return self.config.get('envelopesender')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_fromaddr(self):
Pierre-Yves Chibon 0a9634
        fromaddr = self.config.get('from')
Pierre-Yves Chibon 0a9634
        if fromaddr:
Pierre-Yves Chibon 0a9634
            return fromaddr
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            config = Config('user')
Pierre-Yves Chibon 0a9634
            fromname = config.get('name', default='')
Pierre-Yves Chibon 0a9634
            fromemail = config.get('email', default='')
Pierre-Yves Chibon 0a9634
            if fromemail:
Pierre-Yves Chibon 0a9634
                return formataddr([fromname, fromemail])
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0a9634
                return self.get_sender()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_reply_to_refchange(self, refchange):
Pierre-Yves Chibon 0a9634
        if self.__reply_to_refchange is None:
Pierre-Yves Chibon 0b6d99
            return super(
Pierre-Yves Chibon 0b6d99
                ConfigOptionsEnvironmentMixin, self
Pierre-Yves Chibon 0b6d99
            ).get_reply_to_refchange(refchange)
Pierre-Yves Chibon 0a9634
        elif self.__reply_to_refchange.lower() == 'pusher':
Pierre-Yves Chibon 0a9634
            return self.get_pusher_email()
Pierre-Yves Chibon 0a9634
        elif self.__reply_to_refchange.lower() == 'none':
Pierre-Yves Chibon 0a9634
            return None
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            return self.__reply_to_refchange
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_reply_to_commit(self, revision):
Pierre-Yves Chibon 0a9634
        if self.__reply_to_commit is None:
Pierre-Yves Chibon 0b6d99
            return super(
Pierre-Yves Chibon 0b6d99
                ConfigOptionsEnvironmentMixin, self
Pierre-Yves Chibon 0b6d99
            ).get_reply_to_commit(revision)
Pierre-Yves Chibon 0a9634
        elif self.__reply_to_commit.lower() == 'author':
Pierre-Yves Chibon 0a9634
            return revision.get_author()
Pierre-Yves Chibon 0a9634
        elif self.__reply_to_commit.lower() == 'pusher':
Pierre-Yves Chibon 0a9634
            return self.get_pusher_email()
Pierre-Yves Chibon 0a9634
        elif self.__reply_to_commit.lower() == 'none':
Pierre-Yves Chibon 0a9634
            return None
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            return self.__reply_to_commit
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class FilterLinesEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    """Handle encoding and maximum line length of body lines.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        emailmaxlinelength (int or None)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            The maximum length of any single line in the email body.
Pierre-Yves Chibon 0a9634
            Longer lines are truncated at that length with ' [...]'
Pierre-Yves Chibon 0a9634
            appended.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        strict_utf8 (bool)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            If this field is set to True, then the email body text is
Pierre-Yves Chibon 0a9634
            expected to be UTF-8.  Any invalid characters are
Pierre-Yves Chibon 0a9634
            converted to U+FFFD, the Unicode replacement character
Pierre-Yves Chibon 0a9634
            (encoded as UTF-8, of course).
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    """
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, strict_utf8=True, emailmaxlinelength=500, **kw):
Pierre-Yves Chibon 0a9634
        super(FilterLinesEnvironmentMixin, self).__init__(**kw)
Pierre-Yves Chibon 0a9634
        self.__strict_utf8 = strict_utf8
Pierre-Yves Chibon 0a9634
        self.__emailmaxlinelength = emailmaxlinelength
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def filter_body(self, lines):
Pierre-Yves Chibon 0a9634
        lines = super(FilterLinesEnvironmentMixin, self).filter_body(lines)
Pierre-Yves Chibon 0a9634
        if self.__strict_utf8:
Pierre-Yves Chibon 0a9634
            lines = (line.decode(ENCODING, 'replace') for line in lines)
Pierre-Yves Chibon 0a9634
            # Limit the line length in Unicode-space to avoid
Pierre-Yves Chibon 0a9634
            # splitting characters:
Pierre-Yves Chibon 0a9634
            if self.__emailmaxlinelength:
Pierre-Yves Chibon 0a9634
                lines = limit_linelength(lines, self.__emailmaxlinelength)
Pierre-Yves Chibon 0a9634
            lines = (line.encode(ENCODING, 'replace') for line in lines)
Pierre-Yves Chibon 0a9634
        elif self.__emailmaxlinelength:
Pierre-Yves Chibon 0a9634
            lines = limit_linelength(lines, self.__emailmaxlinelength)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return lines
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ConfigFilterLinesEnvironmentMixin(
Pierre-Yves Chibon 0b6d99
        ConfigEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        FilterLinesEnvironmentMixin,):
Pierre-Yves Chibon 0a9634
    """Handle encoding and maximum line length based on config."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, config, **kw):
Pierre-Yves Chibon 0a9634
        strict_utf8 = config.get_bool('emailstrictutf8', default=None)
Pierre-Yves Chibon 0a9634
        if strict_utf8 is not None:
Pierre-Yves Chibon 0a9634
            kw['strict_utf8'] = strict_utf8
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        emailmaxlinelength = config.get('emailmaxlinelength')
Pierre-Yves Chibon 0a9634
        if emailmaxlinelength is not None:
Pierre-Yves Chibon 0a9634
            kw['emailmaxlinelength'] = int(emailmaxlinelength)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        super(ConfigFilterLinesEnvironmentMixin, self).__init__(
Pierre-Yves Chibon 0a9634
            config=config, **kw
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class MaxlinesEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    """Limit the email body to a specified number of lines."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, emailmaxlines, **kw):
Pierre-Yves Chibon 0a9634
        super(MaxlinesEnvironmentMixin, self).__init__(**kw)
Pierre-Yves Chibon 0a9634
        self.__emailmaxlines = emailmaxlines
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def filter_body(self, lines):
Pierre-Yves Chibon 0a9634
        lines = super(MaxlinesEnvironmentMixin, self).filter_body(lines)
Pierre-Yves Chibon 0a9634
        if self.__emailmaxlines:
Pierre-Yves Chibon 0a9634
            lines = limit_lines(lines, self.__emailmaxlines)
Pierre-Yves Chibon 0a9634
        return lines
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ConfigMaxlinesEnvironmentMixin(
Pierre-Yves Chibon 0b6d99
        ConfigEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        MaxlinesEnvironmentMixin,):
Pierre-Yves Chibon 0a9634
    """Limit the email body to the number of lines specified in config."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, config, **kw):
Pierre-Yves Chibon 0a9634
        emailmaxlines = int(config.get('emailmaxlines', default='0'))
Pierre-Yves Chibon 0a9634
        super(ConfigMaxlinesEnvironmentMixin, self).__init__(
Pierre-Yves Chibon 0a9634
            config=config,
Pierre-Yves Chibon 0a9634
            emailmaxlines=emailmaxlines,
Pierre-Yves Chibon 0a9634
            **kw
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class FQDNEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    """A mixin that sets the host's FQDN to its constructor argument."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, fqdn, **kw):
Pierre-Yves Chibon 0a9634
        super(FQDNEnvironmentMixin, self).__init__(**kw)
Pierre-Yves Chibon 0a9634
        self.COMPUTED_KEYS += ['fqdn']
Pierre-Yves Chibon 0a9634
        self.__fqdn = fqdn
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_fqdn(self):
Pierre-Yves Chibon 0a9634
        """Return the fully-qualified domain name for this host.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return None if it is unavailable or unwanted."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return self.__fqdn
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ConfigFQDNEnvironmentMixin(
Pierre-Yves Chibon 0b6d99
        ConfigEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        FQDNEnvironmentMixin,):
Pierre-Yves Chibon 0a9634
    """Read the FQDN from the config."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, config, **kw):
Pierre-Yves Chibon 0a9634
        fqdn = config.get('fqdn')
Pierre-Yves Chibon 0a9634
        super(ConfigFQDNEnvironmentMixin, self).__init__(
Pierre-Yves Chibon 0a9634
            config=config,
Pierre-Yves Chibon 0a9634
            fqdn=fqdn,
Pierre-Yves Chibon 0a9634
            **kw
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ComputeFQDNEnvironmentMixin(FQDNEnvironmentMixin):
Pierre-Yves Chibon 0a9634
    """Get the FQDN by calling socket.getfqdn()."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, **kw):
Pierre-Yves Chibon 0a9634
        super(ComputeFQDNEnvironmentMixin, self).__init__(
Pierre-Yves Chibon 0a9634
            fqdn=socket.getfqdn(),
Pierre-Yves Chibon 0a9634
            **kw
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class PusherDomainEnvironmentMixin(ConfigEnvironmentMixin):
Pierre-Yves Chibon 0a9634
    """Deduce pusher_email from pusher by appending an emaildomain."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, **kw):
Pierre-Yves Chibon 0a9634
        super(PusherDomainEnvironmentMixin, self).__init__(**kw)
Pierre-Yves Chibon 0a9634
        self.__emaildomain = self.config.get('emaildomain')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_pusher_email(self):
Pierre-Yves Chibon 0a9634
        if self.__emaildomain:
Pierre-Yves Chibon 0a9634
            # Derive the pusher's full email address in the default way:
Pierre-Yves Chibon 0a9634
            return '%s@%s' % (self.get_pusher(), self.__emaildomain)
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0b6d99
            return super(
Pierre-Yves Chibon 0b6d99
                PusherDomainEnvironmentMixin, self).get_pusher_email()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class StaticRecipientsEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    """Set recipients statically based on constructor parameters."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(
Pierre-Yves Chibon 0b6d99
            self, refchange_recipients, announce_recipients,
Pierre-Yves Chibon 0b6d99
            revision_recipients, **kw):
Pierre-Yves Chibon 0a9634
        super(StaticRecipientsEnvironmentMixin, self).__init__(**kw)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # The recipients for various types of notification emails, as
Pierre-Yves Chibon 0a9634
        # RFC 2822 email addresses separated by commas (or the empty
Pierre-Yves Chibon 0a9634
        # string if no recipients are configured).  Although there is
Pierre-Yves Chibon 0a9634
        # a mechanism to choose the recipient lists based on on the
Pierre-Yves Chibon 0a9634
        # actual *contents* of the change being reported, we only
Pierre-Yves Chibon 0a9634
        # choose based on the *type* of the change.  Therefore we can
Pierre-Yves Chibon 0a9634
        # compute them once and for all:
Pierre-Yves Chibon 0a9634
        if not (refchange_recipients
Pierre-Yves Chibon 0a9634
                or announce_recipients
Pierre-Yves Chibon 0a9634
                or revision_recipients):
Pierre-Yves Chibon 0a9634
            raise ConfigurationException('No email recipients configured!')
Pierre-Yves Chibon 0a9634
        self.__refchange_recipients = refchange_recipients
Pierre-Yves Chibon 0a9634
        self.__announce_recipients = announce_recipients
Pierre-Yves Chibon 0a9634
        self.__revision_recipients = revision_recipients
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_refchange_recipients(self, refchange):
Pierre-Yves Chibon 0a9634
        return self.__refchange_recipients
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_announce_recipients(self, annotated_tag_change):
Pierre-Yves Chibon 0a9634
        return self.__announce_recipients
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_revision_recipients(self, revision):
Pierre-Yves Chibon 0a9634
        return self.__revision_recipients
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ConfigRecipientsEnvironmentMixin(
Pierre-Yves Chibon 0b6d99
        ConfigEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        StaticRecipientsEnvironmentMixin):
Pierre-Yves Chibon 0a9634
    """Determine recipients statically based on config."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, config, **kw):
Pierre-Yves Chibon 0a9634
        super(ConfigRecipientsEnvironmentMixin, self).__init__(
Pierre-Yves Chibon 0a9634
            config=config,
Pierre-Yves Chibon 0a9634
            refchange_recipients=self._get_recipients(
Pierre-Yves Chibon 0a9634
                config, 'refchangelist', 'mailinglist',
Pierre-Yves Chibon 0a9634
                ),
Pierre-Yves Chibon 0a9634
            announce_recipients=self._get_recipients(
Pierre-Yves Chibon 0a9634
                config, 'announcelist', 'refchangelist', 'mailinglist',
Pierre-Yves Chibon 0a9634
                ),
Pierre-Yves Chibon 0a9634
            revision_recipients=self._get_recipients(
Pierre-Yves Chibon 0a9634
                config, 'commitlist', 'mailinglist',
Pierre-Yves Chibon 0a9634
                ),
Pierre-Yves Chibon 0a9634
            **kw
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def _get_recipients(self, config, *names):
Pierre-Yves Chibon 0a9634
        """Return the recipients for a particular type of message.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return the list of email addresses to which a particular type
Pierre-Yves Chibon 0a9634
        of notification email should be sent, by looking at the config
Pierre-Yves Chibon 0a9634
        value for "multimailhook.$name" for each of names.  Use the
Pierre-Yves Chibon 0a9634
        value from the first name that is configured.  The return
Pierre-Yves Chibon 0a9634
        value is a (possibly empty) string containing RFC 2822 email
Pierre-Yves Chibon 0a9634
        addresses separated by commas.  If no configuration could be
Pierre-Yves Chibon 0a9634
        found, raise a ConfigurationException."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        for name in names:
Pierre-Yves Chibon 0a9634
            retval = config.get_recipients(name)
Pierre-Yves Chibon 0a9634
            if retval is not None:
Pierre-Yves Chibon 0a9634
                return retval
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            return ''
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class ProjectdescEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    """Make a "projectdesc" value available for templates.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    By default, it is set to the first line of $GIT_DIR/description
Pierre-Yves Chibon 0a9634
    (if that file is present and appears to be set meaningfully)."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, **kw):
Pierre-Yves Chibon 0a9634
        super(ProjectdescEnvironmentMixin, self).__init__(**kw)
Pierre-Yves Chibon 0a9634
        self.COMPUTED_KEYS += ['projectdesc']
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_projectdesc(self):
Pierre-Yves Chibon 0a9634
        """Return a one-line descripition of the project."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git_dir = get_git_dir()
Pierre-Yves Chibon 0a9634
        try:
Pierre-Yves Chibon 0b6d99
            projectdesc = open(
Pierre-Yves Chibon 0b6d99
                os.path.join(git_dir, 'description')).readline().strip()
Pierre-Yves Chibon 0b6d99
            if projectdesc and not projectdesc.startswith(
Pierre-Yves Chibon 0b6d99
                    'Unnamed repository'):
Pierre-Yves Chibon 0a9634
                return projectdesc
Pierre-Yves Chibon 0a9634
        except IOError:
Pierre-Yves Chibon 0a9634
            pass
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return 'UNNAMED PROJECT'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class GenericEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    def get_pusher(self):
Pierre-Yves Chibon 0a9634
        return self.osenv.get('USER', 'unknown user')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class GenericEnvironment(
Pierre-Yves Chibon 0b6d99
        ProjectdescEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigMaxlinesEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ComputeFQDNEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigFilterLinesEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigRecipientsEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        PusherDomainEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigOptionsEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        GenericEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        Environment,
Pierre-Yves Chibon 0b6d99
        ):
Pierre-Yves Chibon 0a9634
    pass
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class GitoliteEnvironmentMixin(Environment):
Pierre-Yves Chibon 0a9634
    def get_repo_shortname(self):
Pierre-Yves Chibon 0a9634
        # The gitolite environment variable $GL_REPO is a pretty good
Pierre-Yves Chibon 0a9634
        # repo_shortname (though it's probably not as good as a value
Pierre-Yves Chibon 0a9634
        # the user might have explicitly put in his config).
Pierre-Yves Chibon 0a9634
        return (
Pierre-Yves Chibon 0a9634
            self.osenv.get('GL_REPO', None)
Pierre-Yves Chibon 0a9634
            or super(GitoliteEnvironmentMixin, self).get_repo_shortname()
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_pusher(self):
Pierre-Yves Chibon 0a9634
        return self.osenv.get('GL_USER', 'unknown user')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class IncrementalDateTime(object):
Pierre-Yves Chibon 0a9634
    """Simple wrapper to give incremental date/times.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    Each call will result in a date/time a second later than the
Pierre-Yves Chibon 0a9634
    previous call.  This can be used to falsify email headers, to
Pierre-Yves Chibon 0a9634
    increase the likelihood that email clients sort the emails
Pierre-Yves Chibon 0a9634
    correctly."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self):
Pierre-Yves Chibon 0a9634
        self.time = time.time()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def next(self):
Pierre-Yves Chibon 0a9634
        formatted = formatdate(self.time, True)
Pierre-Yves Chibon 0a9634
        self.time += 1
Pierre-Yves Chibon 0a9634
        return formatted
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class GitoliteEnvironment(
Pierre-Yves Chibon 0b6d99
        ProjectdescEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigMaxlinesEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ComputeFQDNEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigFilterLinesEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigRecipientsEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        PusherDomainEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        ConfigOptionsEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        GitoliteEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
        Environment,
Pierre-Yves Chibon 0b6d99
        ):
Pierre-Yves Chibon 0a9634
    pass
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
class Push(object):
Pierre-Yves Chibon 0a9634
    """Represent an entire push (i.e., a group of ReferenceChanges).
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    It is easy to figure out what commits were added to a *branch* by
Pierre-Yves Chibon 0a9634
    a Reference change:
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git rev-list change.old..change.new
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    or removed from a *branch*:
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git rev-list change.new..change.old
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    But it is not quite so trivial to determine which entirely new
Pierre-Yves Chibon 0a9634
    commits were added to the *repository* by a push and which old
Pierre-Yves Chibon 0a9634
    commits were discarded by a push.  A big part of the job of this
Pierre-Yves Chibon 0a9634
    class is to figure out these things, and to make sure that new
Pierre-Yves Chibon 0a9634
    commits are only detailed once even if they were added to multiple
Pierre-Yves Chibon 0a9634
    references.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    The first step is to determine the "other" references--those
Pierre-Yves Chibon 0a9634
    unaffected by the current push.  They are computed by
Pierre-Yves Chibon 0a9634
    Push._compute_other_ref_sha1s() by listing all references then
Pierre-Yves Chibon 0a9634
    removing any affected by this push.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    The commits contained in the repository before this push were
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git rev-list other1 other2 other3 ... change1.old change2.old ...
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    Where "changeN.old" is the old value of one of the references
Pierre-Yves Chibon 0a9634
    affected by this push.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    The commits contained in the repository after this push are
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git rev-list other1 other2 other3 ... change1.new change2.new ...
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    The commits added by this push are the difference between these
Pierre-Yves Chibon 0a9634
    two sets, which can be written
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git rev-list \
Pierre-Yves Chibon 0a9634
            ^other1 ^other2 ... \
Pierre-Yves Chibon 0a9634
            ^change1.old ^change2.old ... \
Pierre-Yves Chibon 0a9634
            change1.new change2.new ...
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    The commits removed by this push can be computed by
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git rev-list \
Pierre-Yves Chibon 0a9634
            ^other1 ^other2 ... \
Pierre-Yves Chibon 0a9634
            ^change1.new ^change2.new ... \
Pierre-Yves Chibon 0a9634
            change1.old change2.old ...
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    The last point is that it is possible that other pushes are
Pierre-Yves Chibon 0a9634
    occurring simultaneously to this one, so reference values can
Pierre-Yves Chibon 0a9634
    change at any time.  It is impossible to eliminate all race
Pierre-Yves Chibon 0a9634
    conditions, but we reduce the window of time during which problems
Pierre-Yves Chibon 0a9634
    can occur by translating reference names to SHA1s as soon as
Pierre-Yves Chibon 0a9634
    possible and working with SHA1s thereafter (because SHA1s are
Pierre-Yves Chibon 0a9634
    immutable)."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    # A map {(changeclass, changetype) : integer} specifying the order
Pierre-Yves Chibon 0a9634
    # that reference changes will be processed if multiple reference
Pierre-Yves Chibon 0a9634
    # changes are included in a single push.  The order is significant
Pierre-Yves Chibon 0a9634
    # mostly because new commit notifications are threaded together
Pierre-Yves Chibon 0a9634
    # with the first reference change that includes the commit.  The
Pierre-Yves Chibon 0a9634
    # following order thus causes commits to be grouped with branch
Pierre-Yves Chibon 0a9634
    # changes (as opposed to tag changes) if possible.
Pierre-Yves Chibon 0a9634
    SORT_ORDER = dict(
Pierre-Yves Chibon 0a9634
        (value, i) for (i, value) in enumerate([
Pierre-Yves Chibon 0a9634
            (BranchChange, 'update'),
Pierre-Yves Chibon 0a9634
            (BranchChange, 'create'),
Pierre-Yves Chibon 0a9634
            (AnnotatedTagChange, 'update'),
Pierre-Yves Chibon 0a9634
            (AnnotatedTagChange, 'create'),
Pierre-Yves Chibon 0a9634
            (NonAnnotatedTagChange, 'update'),
Pierre-Yves Chibon 0a9634
            (NonAnnotatedTagChange, 'create'),
Pierre-Yves Chibon 0a9634
            (BranchChange, 'delete'),
Pierre-Yves Chibon 0a9634
            (AnnotatedTagChange, 'delete'),
Pierre-Yves Chibon 0a9634
            (NonAnnotatedTagChange, 'delete'),
Pierre-Yves Chibon 0a9634
            (OtherReferenceChange, 'update'),
Pierre-Yves Chibon 0a9634
            (OtherReferenceChange, 'create'),
Pierre-Yves Chibon 0a9634
            (OtherReferenceChange, 'delete'),
Pierre-Yves Chibon 0a9634
            ])
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def __init__(self, changes):
Pierre-Yves Chibon 0a9634
        self.changes = sorted(changes, key=self._sort_key)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # The SHA-1s of commits referred to by references unaffected
Pierre-Yves Chibon 0a9634
        # by this push:
Pierre-Yves Chibon 0a9634
        other_ref_sha1s = self._compute_other_ref_sha1s()
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        self._old_rev_exclusion_spec = self._compute_rev_exclusion_spec(
Pierre-Yves Chibon 0a9634
            other_ref_sha1s.union(
Pierre-Yves Chibon 0a9634
                change.old.sha1
Pierre-Yves Chibon 0a9634
                for change in self.changes
Pierre-Yves Chibon 0a9634
                if change.old.type in ['commit', 'tag']
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        self._new_rev_exclusion_spec = self._compute_rev_exclusion_spec(
Pierre-Yves Chibon 0a9634
            other_ref_sha1s.union(
Pierre-Yves Chibon 0a9634
                change.new.sha1
Pierre-Yves Chibon 0a9634
                for change in self.changes
Pierre-Yves Chibon 0a9634
                if change.new.type in ['commit', 'tag']
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    @classmethod
Pierre-Yves Chibon 0a9634
    def _sort_key(klass, change):
Pierre-Yves Chibon 0b6d99
        return (
Pierre-Yves Chibon 0b6d99
            klass.SORT_ORDER[change.__class__, change.change_type],
Pierre-Yves Chibon 0b6d99
            change.refname,)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def _compute_other_ref_sha1s(self):
Pierre-Yves Chibon 0b6d99
        """Return the GitObjects referred to by references unaffected by
Pierre-Yves Chibon 0b6d99
        this push."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # The refnames being changed by this push:
Pierre-Yves Chibon 0a9634
        updated_refs = set(
Pierre-Yves Chibon 0a9634
            change.refname
Pierre-Yves Chibon 0a9634
            for change in self.changes
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # The SHA-1s of commits referred to by all references in this
Pierre-Yves Chibon 0a9634
        # repository *except* updated_refs:
Pierre-Yves Chibon 0a9634
        sha1s = set()
Pierre-Yves Chibon 0a9634
        fmt = (
Pierre-Yves Chibon 0a9634
            '%(objectname) %(objecttype) %(refname)\n'
Pierre-Yves Chibon 0a9634
            '%(*objectname) %(*objecttype) %(refname)'
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        for line in read_git_lines(['for-each-ref', '--format=%s' % (fmt,)]):
Pierre-Yves Chibon 0a9634
            (sha1, type, name) = line.split(' ', 2)
Pierre-Yves Chibon 0a9634
            if sha1 and type == 'commit' and name not in updated_refs:
Pierre-Yves Chibon 0a9634
                sha1s.add(sha1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return sha1s
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def _compute_rev_exclusion_spec(self, sha1s):
Pierre-Yves Chibon 0a9634
        """Return an exclusion specification for 'git rev-list'.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        git_objects is an iterable over GitObject instances.  Return a
Pierre-Yves Chibon 0a9634
        string that can be passed to the standard input of 'git
Pierre-Yves Chibon 0a9634
        rev-list --stdin' to exclude all of the commits referred to by
Pierre-Yves Chibon 0a9634
        git_objects."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        return ''.join(
Pierre-Yves Chibon 0a9634
            ['^%s\n' % (sha1,) for sha1 in sorted(sha1s)]
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_new_commits(self, reference_change=None):
Pierre-Yves Chibon 0a9634
        """Return a list of commits added by this push.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return a list of the object names of commits that were added
Pierre-Yves Chibon 0a9634
        by the part of this push represented by reference_change.  If
Pierre-Yves Chibon 0a9634
        reference_change is None, then return a list of *all* commits
Pierre-Yves Chibon 0a9634
        added by this push."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if not reference_change:
Pierre-Yves Chibon 0a9634
            new_revs = sorted(
Pierre-Yves Chibon 0a9634
                change.new.sha1
Pierre-Yves Chibon 0a9634
                for change in self.changes
Pierre-Yves Chibon 0a9634
                if change.new
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
        elif not reference_change.new.commit_sha1:
Pierre-Yves Chibon 0a9634
            return []
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            new_revs = [reference_change.new.commit_sha1]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        cmd = ['rev-list', '--stdin'] + new_revs
Pierre-Yves Chibon 0a9634
        return read_git_lines(cmd, input=self._old_rev_exclusion_spec)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def get_discarded_commits(self, reference_change):
Pierre-Yves Chibon 0a9634
        """Return a list of commits discarded by this push.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Return a list of the object names of commits that were
Pierre-Yves Chibon 0a9634
        entirely discarded from the repository by the part of this
Pierre-Yves Chibon 0a9634
        push represented by reference_change."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if not reference_change.old.commit_sha1:
Pierre-Yves Chibon 0a9634
            return []
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            old_revs = [reference_change.old.commit_sha1]
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        cmd = ['rev-list', '--stdin'] + old_revs
Pierre-Yves Chibon 0a9634
        return read_git_lines(cmd, input=self._new_rev_exclusion_spec)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    def send_emails(self, mailer, body_filter=None):
Pierre-Yves Chibon 0a9634
        """Use send all of the notification emails needed for this push.
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        Use send all of the notification emails (including reference
Pierre-Yves Chibon 0a9634
        change emails and commit emails) needed for this push.  Send
Pierre-Yves Chibon 0a9634
        the emails using mailer.  If body_filter is not None, then use
Pierre-Yves Chibon 0a9634
        it to filter the lines that are intended for the email
Pierre-Yves Chibon 0a9634
        body."""
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # The sha1s of commits that were introduced by this push.
Pierre-Yves Chibon 0a9634
        # They will be removed from this set as they are processed, to
Pierre-Yves Chibon 0a9634
        # guarantee that one (and only one) email is generated for
Pierre-Yves Chibon 0a9634
        # each new commit.
Pierre-Yves Chibon 0a9634
        unhandled_sha1s = set(self.get_new_commits())
Pierre-Yves Chibon 0a9634
        send_date = IncrementalDateTime()
Pierre-Yves Chibon 0a9634
        for change in self.changes:
Pierre-Yves Chibon 0a9634
            # Check if we've got anyone to send to
Pierre-Yves Chibon 0a9634
            if not change.recipients:
Pierre-Yves Chibon 0a9634
                sys.stderr.write(
Pierre-Yves Chibon 0a9634
                    '*** no recipients configured so no email will be sent\n'
Pierre-Yves Chibon 0a9634
                    '*** for %r update %s->%s\n'
Pierre-Yves Chibon 0a9634
                    % (change.refname, change.old.sha1, change.new.sha1,)
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
            else:
Pierre-Yves Chibon 0b6d99
                sys.stderr.write(
Pierre-Yves Chibon 0b6d99
                    'Sending notification emails to: %s\n' % (
Pierre-Yves Chibon 0b6d99
                        change.recipients,))
Pierre-Yves Chibon 0b6d99
                extra_values = {'send_date': send_date.next()}
Pierre-Yves Chibon 0a9634
                mailer.send(
Pierre-Yves Chibon 0a9634
                    change.generate_email(self, body_filter, extra_values),
Pierre-Yves Chibon 0a9634
                    change.recipients,
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            sha1s = []
Pierre-Yves Chibon 0a9634
            for sha1 in reversed(list(self.get_new_commits(change))):
Pierre-Yves Chibon 0a9634
                if sha1 in unhandled_sha1s:
Pierre-Yves Chibon 0a9634
                    sha1s.append(sha1)
Pierre-Yves Chibon 0a9634
                    unhandled_sha1s.remove(sha1)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            max_emails = change.environment.maxcommitemails
Pierre-Yves Chibon 0a9634
            if max_emails and len(sha1s) > max_emails:
Pierre-Yves Chibon 0a9634
                sys.stderr.write(
Pierre-Yves Chibon 0b6d99
                    '*** Too many new commits (%d), not sending commit '
Pierre-Yves Chibon 0b6d99
                    'emails.\n' % len(sha1s)
Pierre-Yves Chibon 0b6d99
                    + '*** Try setting multimailhook.maxCommitEmails to a '
Pierre-Yves Chibon 0b6d99
                    'greater value\n'
Pierre-Yves Chibon 0b6d99
                    '*** Currently, multimailhook.maxCommitEmails=%d\n' %
Pierre-Yves Chibon 0b6d99
                    max_emails
Pierre-Yves Chibon 0a9634
                    )
Pierre-Yves Chibon 0a9634
                return
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
            for (num, sha1) in enumerate(sha1s):
Pierre-Yves Chibon 0b6d99
                rev = Revision(
Pierre-Yves Chibon 0b6d99
                    change, GitObject(sha1), num=num+1, tot=len(sha1s))
Pierre-Yves Chibon 0a9634
                if rev.recipients:
Pierre-Yves Chibon 0b6d99
                    extra_values = {'send_date': send_date.next()}
Pierre-Yves Chibon 0a9634
                    mailer.send(
Pierre-Yves Chibon 0a9634
                        rev.generate_email(self, body_filter, extra_values),
Pierre-Yves Chibon 0a9634
                        rev.recipients,
Pierre-Yves Chibon 0a9634
                        )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # Consistency check:
Pierre-Yves Chibon 0a9634
        if unhandled_sha1s:
Pierre-Yves Chibon 0a9634
            sys.stderr.write(
Pierre-Yves Chibon 0a9634
                'ERROR: No emails were sent for the following new commits:\n'
Pierre-Yves Chibon 0a9634
                '    %s\n'
Pierre-Yves Chibon 0a9634
                % ('\n    '.join(sorted(unhandled_sha1s)),)
Pierre-Yves Chibon 0a9634
                )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def run_as_post_receive_hook(environment, mailer):
Pierre-Yves Chibon 0a9634
    changes = []
Pierre-Yves Chibon 0a9634
    for line in sys.stdin:
Pierre-Yves Chibon 0a9634
        (oldrev, newrev, refname) = line.strip().split(' ', 2)
Pierre-Yves Chibon 0a9634
        changes.append(
Pierre-Yves Chibon 0a9634
            ReferenceChange.create(environment, oldrev, newrev, refname)
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
    push = Push(changes)
Pierre-Yves Chibon 0a9634
    push.send_emails(mailer, body_filter=environment.filter_body)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def run_as_update_hook(environment, mailer, refname, oldrev, newrev):
Pierre-Yves Chibon 0a9634
    changes = [
Pierre-Yves Chibon 0a9634
        ReferenceChange.create(
Pierre-Yves Chibon 0a9634
            environment,
Pierre-Yves Chibon 0a9634
            read_git_output(['rev-parse', '--verify', oldrev]),
Pierre-Yves Chibon 0a9634
            read_git_output(['rev-parse', '--verify', newrev]),
Pierre-Yves Chibon 0a9634
            refname,
Pierre-Yves Chibon 0a9634
            ),
Pierre-Yves Chibon 0a9634
        ]
Pierre-Yves Chibon 0a9634
    push = Push(changes)
Pierre-Yves Chibon 0a9634
    push.send_emails(mailer, body_filter=environment.filter_body)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def choose_mailer(config, environment):
Pierre-Yves Chibon 0a9634
    mailer = config.get('mailer', default='sendmail')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    if mailer == 'smtp':
Pierre-Yves Chibon 0a9634
        smtpserver = config.get('smtpserver', default='localhost')
Pierre-Yves Chibon 0a9634
        mailer = SMTPMailer(
Pierre-Yves Chibon 0b6d99
            envelopesender=(
Pierre-Yves Chibon 0b6d99
                environment.get_sender() or environment.get_fromaddr()
Pierre-Yves Chibon 0b6d99
            ),
Pierre-Yves Chibon 0a9634
            smtpserver=smtpserver,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
    elif mailer == 'sendmail':
Pierre-Yves Chibon 0a9634
        command = config.get('sendmailcommand')
Pierre-Yves Chibon 0a9634
        if command:
Pierre-Yves Chibon 0a9634
            command = shlex.split(command)
Pierre-Yves Chibon 0b6d99
        mailer = SendMailer(
Pierre-Yves Chibon 0b6d99
            command=command, envelopesender=environment.get_sender())
Pierre-Yves Chibon 0a9634
    else:
Pierre-Yves Chibon 0a9634
        sys.stderr.write(
Pierre-Yves Chibon 0b6d99
            'fatal: multimailhook.mailer is set to an incorrect value: '
Pierre-Yves Chibon 0b6d99
            '"%s"\n' % mailer
Pierre-Yves Chibon 0a9634
            + 'please use one of "smtp" or "sendmail".\n'
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
        sys.exit(1)
Pierre-Yves Chibon 0a9634
    return mailer
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
KNOWN_ENVIRONMENTS = {
Pierre-Yves Chibon 0b6d99
    'generic': GenericEnvironmentMixin,
Pierre-Yves Chibon 0b6d99
    'gitolite': GitoliteEnvironmentMixin,
Pierre-Yves Chibon 0a9634
    }
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def choose_environment(config, osenv=None, env=None, recipients=None):
Pierre-Yves Chibon 0a9634
    if not osenv:
Pierre-Yves Chibon 0a9634
        osenv = os.environ
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    environment_mixins = [
Pierre-Yves Chibon 0a9634
        ProjectdescEnvironmentMixin,
Pierre-Yves Chibon 0a9634
        ConfigMaxlinesEnvironmentMixin,
Pierre-Yves Chibon 0a9634
        ComputeFQDNEnvironmentMixin,
Pierre-Yves Chibon 0a9634
        ConfigFilterLinesEnvironmentMixin,
Pierre-Yves Chibon 0a9634
        PusherDomainEnvironmentMixin,
Pierre-Yves Chibon 0a9634
        ConfigOptionsEnvironmentMixin,
Pierre-Yves Chibon 0a9634
        ]
Pierre-Yves Chibon 0a9634
    environment_kw = {
Pierre-Yves Chibon 0b6d99
        'osenv': osenv,
Pierre-Yves Chibon 0b6d99
        'config': config,
Pierre-Yves Chibon 0a9634
        }
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    if not env:
Pierre-Yves Chibon 0a9634
        env = config.get('environment')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    if not env:
Pierre-Yves Chibon 0a9634
        if 'GL_USER' in osenv and 'GL_REPO' in osenv:
Pierre-Yves Chibon 0a9634
            env = 'gitolite'
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            env = 'generic'
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    environment_mixins.append(KNOWN_ENVIRONMENTS[env])
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    if recipients:
Pierre-Yves Chibon 0a9634
        environment_mixins.insert(0, StaticRecipientsEnvironmentMixin)
Pierre-Yves Chibon 0a9634
        environment_kw['refchange_recipients'] = recipients
Pierre-Yves Chibon 0a9634
        environment_kw['announce_recipients'] = recipients
Pierre-Yves Chibon 0a9634
        environment_kw['revision_recipients'] = recipients
Pierre-Yves Chibon 0a9634
    else:
Pierre-Yves Chibon 0a9634
        environment_mixins.insert(0, ConfigRecipientsEnvironmentMixin)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    environment_klass = type(
Pierre-Yves Chibon 0a9634
        'EffectiveEnvironment',
Pierre-Yves Chibon 0a9634
        tuple(environment_mixins) + (Environment,),
Pierre-Yves Chibon 0a9634
        {},
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
    return environment_klass(**environment_kw)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
def main(args):
Pierre-Yves Chibon 0a9634
    parser = optparse.OptionParser(
Pierre-Yves Chibon 0a9634
        description=__doc__,
Pierre-Yves Chibon 0a9634
        usage='%prog [OPTIONS]\n   or: %prog [OPTIONS] REFNAME OLDREV NEWREV',
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    parser.add_option(
Pierre-Yves Chibon 0a9634
        '--environment', '--env', action='store', type='choice',
Pierre-Yves Chibon 0a9634
        choices=['generic', 'gitolite'], default=None,
Pierre-Yves Chibon 0a9634
        help=(
Pierre-Yves Chibon 0a9634
            'Choose type of environment is in use.  Default is taken from '
Pierre-Yves Chibon 0a9634
            'multimailhook.environment if set; otherwise "generic".'
Pierre-Yves Chibon 0a9634
            ),
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
    parser.add_option(
Pierre-Yves Chibon 0a9634
        '--stdout', action='store_true', default=False,
Pierre-Yves Chibon 0a9634
        help='Output emails to stdout rather than sending them.',
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
    parser.add_option(
Pierre-Yves Chibon 0a9634
        '--recipients', action='store', default=None,
Pierre-Yves Chibon 0a9634
        help='Set list of email recipients for all types of emails.',
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
    parser.add_option(
Pierre-Yves Chibon 0a9634
        '--show-env', action='store_true', default=False,
Pierre-Yves Chibon 0a9634
        help=(
Pierre-Yves Chibon 0a9634
            'Write to stderr the values determined for the environment '
Pierre-Yves Chibon 0a9634
            '(intended for debugging purposes).'
Pierre-Yves Chibon 0a9634
            ),
Pierre-Yves Chibon 0a9634
        )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    (options, args) = parser.parse_args(args)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    config = Config('multimailhook')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
    try:
Pierre-Yves Chibon 0a9634
        environment = choose_environment(
Pierre-Yves Chibon 0a9634
            config, osenv=os.environ,
Pierre-Yves Chibon 0a9634
            env=options.environment,
Pierre-Yves Chibon 0a9634
            recipients=options.recipients,
Pierre-Yves Chibon 0a9634
            )
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if options.show_env:
Pierre-Yves Chibon 0a9634
            sys.stderr.write('Environment values:\n')
Pierre-Yves Chibon 0b6d99
            for (k, v) in sorted(environment.get_values().items()):
Pierre-Yves Chibon 0b6d99
                sys.stderr.write('    %s : %r\n' % (k, v))
Pierre-Yves Chibon 0a9634
            sys.stderr.write('\n')
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        if options.stdout:
Pierre-Yves Chibon 0a9634
            mailer = OutputMailer(sys.stdout)
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            mailer = choose_mailer(config, environment)
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
        # Dual mode: if arguments were specified on the command line, run
Pierre-Yves Chibon 0a9634
        # like an update hook; otherwise, run as a post-receive hook.
Pierre-Yves Chibon 0a9634
        if args:
Pierre-Yves Chibon 0a9634
            if len(args) != 3:
Pierre-Yves Chibon 0a9634
                parser.error('Need zero or three non-option arguments')
Pierre-Yves Chibon 0a9634
            (refname, oldrev, newrev) = args
Pierre-Yves Chibon 0a9634
            run_as_update_hook(environment, mailer, refname, oldrev, newrev)
Pierre-Yves Chibon 0a9634
        else:
Pierre-Yves Chibon 0a9634
            run_as_post_receive_hook(environment, mailer)
Pierre-Yves Chibon 0a9634
    except ConfigurationException, e:
Pierre-Yves Chibon 0a9634
        sys.exit(str(e))
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
Pierre-Yves Chibon 0a9634
if __name__ == '__main__':
Pierre-Yves Chibon 0a9634
    main(sys.argv[1:])