#!/usr/bin/env python
# ====================================================================
# Copyright (c) 2000-2007 CollabNet.  All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.  The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals.  For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================

"""
gnuify-changelog.py: a script to munge the output of 'svn log' into something
  approaching the style of a GNU ChangeLog.

See usage() for details, or run with --help option.
"""

import os
import re
import sys
import getopt
try:
  my_getopt = getopt.gnu_getopt
except AttributeError:
  my_getopt = getopt.getopt

def complain(msg, fatal=False):
  """
  Print MSG as a warning, or if FATAL is true, print it as an error
  and exit.
  """
  prefix = 'WARNING: '
  if fatal:
    prefix = 'ERROR: '
  sys.stderr.write(prefix + msg + '\n')
  if fatal:
    sys.exit(1)

class Contributor:
  # Map contributor names to contributor instances, so that there
  # exists exactly one instance associated with a given name.
  # Fold names with email addresses.  That is, if we see someone
  # listed first with just an email address, but later with a real
  # name and that same email address together, we create only one
  # instance, and store it under both the email and the real name.
  all_contributors = { }

  def __init__(self, username, real_name, email):
    """Instantiate a contributor.  Don't use this to generate a
    Contributor for an external caller, though, use .get() instead."""
    self.real_name = real_name
    self.username  = username
    self.email     = email

  def get(username, real_name, email):
    """
    If this contributor is already registered, just return it;
    otherwise, register it then return it.  Hint: use parse() to
    generate the arguments.
    """
    c = None
    for key in username, real_name, email:
      if key and Contributor.all_contributors.has_key(key):
        c = Contributor.all_contributors[key]
        break
    # If we didn't get a Contributor, create one now.
    if not c:
      c = Contributor(username, real_name, email)
    # If we know identifying information that the Contributor lacks,
    # then give it to the Contributor now.
    if username:
      if not c.username:
        c.username = username
      Contributor.all_contributors[username]  = c
    if real_name:
      if not c.real_name:
        c.real_name = real_name
      Contributor.all_contributors[real_name] = c
    if email:
      if not c.email:
        c.email = email
      Contributor.all_contributors[email]     = c
    # This Contributor has never been in better shape; return it.
    return c
  get = staticmethod(get)

  def parse(name):
    """
    Parse NAME, which can be

      - A committer username, or
      - A space-separated real name, or
      - A space-separated real name followed by an email address in
        angle brackets, or
      - Just an email address in angle brackets.

    Return a tuple of (committer_username, real_name, email_address)
    any of which can be None if not available in NAME.
    """
    username  = None
    real_name = None
    email     = None
    name_components = name.split()
    if len(name_components) == 1:
      name = name_components[0] # Effectively, name = name.strip()
      if name[0] == '<' and name[-1] == '>':
        email = name[1:-1]
      elif name.find('@') != -1:
        email = name
      else:
        username = name
    elif name_components[-1][0] == '<' and name_components[-1][-1] == '>':
      real_name = ' '.join(name_components[0:-1])
      email = name_components[-1][1:-1]
    else:
      real_name = ' '.join(name_components)
    return username, real_name, email
  parse = staticmethod(parse)

def process_committers(committers):
  """Read from open file handle COMMITTERS, which should be in
  the same format as the Subversion 'COMMITTERS' file.  Create
  Contributor objects based on the contents."""
  matcher = re.compile('(\S+)\s+([^\(\)]+)\s{0,1}')
  line = committers.readline()
  while line:
    # Every @-sign we see after this point indicates a committer line.
    if line.find('@') >= 0:
      line = line.strip()
      m = matcher.match(line)
      user = m.group(1)
      real_and_email = m.group(2).strip()
      ignored, real, email = Contributor.parse(real_and_email)
      c = Contributor.get(user, real, email)
    line = committers.readline()

def create_changelog(input):
  # Read the entries from stdin
  entries = input.readlines()

  parse_next_line = 0
  this_line_empty = 0
  last_line_empty = 0
  last_rev = ""

  # Pattern to identify the starting and ending of a svn log entry
  p = re.compile (r'(^-+$)',re.S)

  for x in entries:
    # Axe windows style line endings, since we should try to be consistent, and
    # the repos has both styles in its log entries
    x = re.sub (r'\r\n', r'\n', x)

    # Remove trailing new line since it is added by default
    x = re.sub (r'\n+$', r'', x)

    # Remove trailing whitespace
    x = re.sub (r'\s+$', r'\n', x)

    if x == '\n':
      this_line_empty = 1
    else:
      this_line_empty = 0

      # Avoid duplicate empty lines
      if this_line_empty and last_line_empty:
        continue

      m = p.match(x)
      # Don't fail on valid dash-only lines
      if m and len(x) >= 72:
        # We're at the start of a log entry, so we need to parse next line
        parse_next_line = 1

        # Check to see if the final line of the commit message was blank,
        # if not insert one
        if last_rev != "" and (not last_line_empty):
          print "\n"

      elif parse_next_line:
        # Transform from svn style to GNU style
        parse_next_line = 0
        s = x.split('|')
        date = s[2].split(' ')

        # Populate name and email
        c = Contributor.all_contributors
        if c.has_key(s[1].strip()):
          name = c[s[1].strip()].real_name
          email = c[s[1].strip()].email
          print "%s  %s  <%s>" % (date[1], name, email)
        else:
          print "%s  %s" % (date[1], s[1].strip())

      elif this_line_empty:
        print "\n"
      else:
        print "\t"+x
        last_line_empty = this_line_empty

  # As a HERE doc so it also sets the final changelog's coding
  print """
;; Local Variables:
;; coding: utf-8
;; End:
"""

def usage():
  print 'USAGE: svn log | %s -C COMMITTERS_FILE > ChangeLog' \
        % os.path.basename(sys.argv[0])
  print ''
  print 'A script to munge the output of \'svn log\' into something'
  print 'approaching the style of a GNU ChangeLog.'
  print ''
  print 'Options:'
  print ''
  print '  -h, -H, -?, --help   Print this usage message and exit'
  print '  -C FILE              Use FILE as the COMMITTERS file'
  print ''

def main():
  try:
    opts, args = my_getopt(sys.argv[1:], 'C:hH?', [ 'help' ])
  except getopt.GetoptError, e:
    complain(str(e) + '\n\n')
    usage()
    sys.exit(1)

  # Parse options.
  for opt, value in opts:
    if opt in ('--help', '-h', '-H', '-?'):
      usage()
      sys.exit(0)
    elif opt == '-C':
      process_committers(open(value))

  create_changelog(sys.stdin)

if __name__ == '__main__':
  main()


