#!/usr/bin/env python
#
# git-changelog - Output a rpm changelog
#
# Copyright (C) 2009-2010  Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: David Cantrell <dcantrell@redhat.com>
# Author: Brian C. Lane <bcl@redhat.com>

import subprocess
import textwrap
from argparse import ArgumentParser


class ChangeLog:
    def __init__(self, name, version):
        self.name = name
        self.version = version

    def _getCommitDetail(self, commit, field):
        proc = subprocess.Popen(['git', 'log', '-1',
                                 "--pretty=format:%s" % field, commit],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE).communicate()

        ret = proc[0].strip('\n').split('\n')

        if field == '%aE' and len(ret) == 1 and ret[0].find('@') != -1:
            ret = ret[0].split('@')[0]
        elif len(ret) == 1:
            ret = ret[0]
        else:
            ret = filter(lambda x: x != '', ret)

        return ret

    def getLog(self):
        if not self.name:
            range = "%s.." % (self.version)
        else:
            range = "%s-%s.." % (self.name, self.version)
        proc = subprocess.Popen(['git', 'log', '--pretty=oneline',
                                 '--no-merges', range],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE).communicate()
        lines = filter(lambda x: x.find('l10n: ') != 41,
                       proc[0].strip('\n').split('\n'))

        log = []
        for line in lines:
            fields = line.split(' ')
            commit = fields[0]

            summary = self._getCommitDetail(commit, "%s")
            author = self._getCommitDetail(commit, "%aE")

            log.append(("%s (%s)" % (summary.strip(), author)))

        return log

    def formatLog(self):
        s = ""
        for msg in self.getLog():
            sublines = textwrap.wrap(msg, 77)
            s = s + "- %s\n" % sublines[0]

            if len(sublines) > 1:
                for subline in sublines[1:]:
                    s = s + "  %s\n" % subline

        return s


def main():
    parser = ArgumentParser()
    parser.add_argument("-n", "--name",
                        help="Name of package used in tags")
    parser.add_argument("-v", "--version",
                        help="Last version, changelog is commits after this tag")
    args = parser.parse_args()

    cl = ChangeLog(args.name, args.version)
    print cl.formatLog()

if __name__ == "__main__":
    main()