#!/usr/local/bin/python
"""
  ChangeLogP4.py <rev1> <rev2>

  Output a report on the differences between two revisions from a
  perforce depot.
"""

import sys, os, getopt, re, string

def usage(argv0):
  print "%s [--help] rev1 rev2" % argv0

MAX_CHANGES = 1000
P4DB_URL = "http://P4WEBSERVER/cgi-bin/p4db/chv.cgi"

def fetch_change_numbers (rev):
  fp = os.popen("p4 changes -i -m %d -s submitted @%s" %  (MAX_CHANGES, rev))
  change_re = re.compile("Change ([0-9]+) on")

  data = fp.readlines()
  changes = []
  for line in data:
    m = change_re.match (line)
    if m:
      changes.append(int(m.group(1)))
  fp.close()
  
  return changes

def fetch_change_information(changes):
  changes = map(lambda x: str(x), changes)
  cmd = "p4 describe -s %s" % string.join(changes, ' ')
  fp = os.popen (cmd)
  data = fp.read()
  lines = string.split(data, '\n')

  change_re = re.compile("Change ([0-9]+) by")
  output = []
  output_on = 0
  for line in lines:
    if output_on:
      if line == "Affected files ...":
        output_on = 0
      else:
        output.append(line)
    else:
      m = change_re.match(line)
      if m: 
        output_on = 1
        num = m.group(1)
        output.append("%s?CH=%s" % (P4DB_URL, num))
        output.append(line)

  return string.join(output, '\n')
    

def main(argv, environ):
  alist, args = getopt.getopt(argv[1:], "", ["help"])

  for (field, val) in alist:
    if field == "--help":
      usage (argv[0])
      return

  if len(args) < 2:
    return usage(argv[0])

  rev1 = args[0]
  rev2 = args[1]

  rev1_changes = fetch_change_numbers (rev1)
  rev2_changes = fetch_change_numbers (rev2)

  # Now, we need to find all the ones in rev2 which aren't in rev1
  old_d = {}
  for num in rev1_changes:
    old_d[num] = 1

  new_changes = []
  for num in rev2_changes:
    if not old_d.has_key(num):
      new_changes.append(num)

  new_changes.sort()
  new_changes.reverse()
  print "Changelog between %s and %s" % (rev1, rev2)
  print "There were %d changes between these releases" % len(new_changes)
  print "-" * 65
  print fetch_change_information(new_changes)

if __name__ == "__main__":
  main (sys.argv, os.environ)
   

