#!/usr/bin/python

from arsenal.arsenal_lib import *
from lpltk import LaunchpadService

if len(sys.argv) < 1:
    sys.stderr.write("Usage: %s <source-package>\n" %(sys.argv[0]) )
    sys.exit(1)

total_count = 0
source_pkgs = sys.argv[1:]
lp          = LaunchpadService(config={'read_only':True})
d           = lp.launchpad.distributions["ubuntu"]

regex_hex   = re.compile('[0-9a-f]+[0-9][a-f]+[0-9a-f]+')

print "== Bugs with git commits =="

try:
    for source_pkg in source_pkgs:
        count = 0
        print "=== " + source_pkg + " ==="

        for bugtask in d.searchTasks(search_text=source_pkg):
            if bugtask.bug_target_display_name != source_pkg + " (Ubuntu)":
                continue

            bug = ArsenalBug(bugtask.bug, lp.launchpad)
            title = "%d %s %s" % (bug.id, bugtask.status, bug.title)

            #print " -- ", bug.id, " -- "

            # Search description for git commit strings
            # TODO:  Make sure it's either 8 chars or 40 chars
            commits = regex_hex.findall(bug.description)
            if len(commits) > 0:
                for s in commits:
                    if len(s) == 40:
                        if title:
                            print title
                            title = ""
                        print "  commit:  " + s

            for m in bug.bug.messages:
                if not m.content:
                    continue

                commits = regex_hex.findall(m.content)
                if len(commits) == 0:
                    continue
            
                for s in commits:
                    if len(s) == 40:
                        if title:
                            print title
                            title = ""
                        print "  commit:  " + s + " in comment"

except HTTPError, e:
    print "*** Encountered HTTP error ***"
    print e.content
    time.sleep(600)
    lp.reset()
    d = lp.launchpad.distributions["ubuntu"]


