# Path: tools/release.py
# def shorten_changelog(changelog):
#     """Make the changelog into a single paragraph suitable for freshmeat."""
#     # Get the changelog, and strip off any trailing and leading whitespace.
#     # Look at some the freshmeat main page to get examples of how the layout
#     # should look (basically free flowing text).
#     lines = []
#     for line in changelog.splitlines():
#         line = line.strip()
#         while line.startswith('*'):
#             line = line[1:].strip()
#         if line:
#             lines.append(line)
#     return " ".join(lines)
# 
# def get_changelog(contents=_read_changelog()):
#     "Returns a list of (version, date, notes) tuple"
# 
#     result = []
#     version_regex = r'^([0-9.]*) \((.*)\)$'
#     while contents:
#         match = re.search(version_regex, contents, re.M)
#         if match is None:
#             break
# 
#         version = match.group(1)
#         date = match.group(2)
#         changelog_offset = match.end()
# 
#         match = re.search(version_regex, contents[changelog_offset:], re.M)
#         if match:
#             notes = contents[changelog_offset:changelog_offset + match.start()]
#             contents = contents[changelog_offset + match.start():]
#         else:
#             notes = contents[changelog_offset:]
#             contents = ""
# 
#         lines = notes.strip().splitlines()
#         if set(lines[0]) != set('-') or lines[1].strip():
#             sys.exit("The changelog section should be followed by a '---' line, got '%s'" % lines)
#         notes = '\n'.join(lines[2:])
#         result.append((version, date, notes))
#     if not result:
#         sys.exit('Failed to find version')
#     return result
# 
# def notify(version, changelog, freshmeat_auth=_get_freshmeat_auth_code,
#         connection=httplib.HTTPConnection, system=os.system, confirm=raw_input,
#         tag_list=_get_tags):
#     # This is a fresmeat limit
#     MAX_CHARS = 600
#     short_message = shorten_changelog(changelog)
#     while len(short_message) > 600:
#         print 'Changelog is too long (must be less then %i characters, is %i)' % (MAX_CHARS, len(short_message))
#         text = raw_input('Edit changelog for submission? [y]')
#         if text and text != 'y':
#             print 'Servers not notified of release.'
#             return
# 
#         short_message = _edit_message(short_message)
# 
#     # Notify freshmeat
#     if confirm('Should freshmeat be notified? [y]') in ['', 'y', 'Y']:
#         release = {
#                 'auth_code': freshmeat_auth(),
#                 'release':{
#                     'tag_list':tag_list(connection, freshmeat_auth),
#                     'version':str(version),
#                     'changelog':short_message
#                     },
#                 }
#         headers = {"Content-type": "application/json"}
#         conn = connection("freshmeat.net")
#         conn.request("POST", "/projects/bdec/releases.json", json.dumps(release), headers)
#         response = conn.getresponse()
#         data = response.read()
#         conn.close()
#         if response.status >= 400:
#             print response.status, response.reason
#             sys.exit('Failed to submit to freshmeat! (%s)' % data)
#         print "Created release; %s %s\n%s" % (response.status, response.reason, data)
# 
#     else:
#         print 'Not notifying freshmeat.'
# 
#     # Notify the python package index
#     if confirm('Should pypi be notified? [y]') in ['', 'y', 'Y']:
#         os.chdir(root_path)
#         command = "./setup.py register"
#         if system(command) != 0:
#             sys.exit('Failed to update python package index!')
#     else:
#         print 'Not notifying pypi.'
# 
#     if confirm('Send an email to the bdec mailing list? [y]') in ['', 'y', 'Y']:
#         send_email(version, changelog)


import os.path
import StringIO
import unittest
import bdec
from tools.release import shorten_changelog, get_changelog, notify
        text = """
Blah blah

Download
========

9.9.9 (blah blah)
-----------------

Blah blah:
* Did this.
* Did that.

Ding dong:
* Went there.
* Came back.

1.2.3 (be bop)
--------------

This is the current version
   """
        changelog = get_changelog(text)
        self.assertEqual(2, len(changelog))
        self.assertEqual('9.9.9', changelog[0][0])
        self.assertEqual('blah blah', changelog[0][1])
        self.assertEqual('Blah blah: Did this. Did that. Ding dong: Went there. Came back.', shorten_changelog(changelog[0][2]))

        self.assertEqual('1.2.3', changelog[1][0])
        self.assertEqual('be bop', changelog[1][1])

# Path: tools/release.py
# def shorten_changelog(changelog):
#     """Make the changelog into a single paragraph suitable for freshmeat."""
#     # Get the changelog, and strip off any trailing and leading whitespace.
#     # Look at some the freshmeat main page to get examples of how the layout
#     # should look (basically free flowing text).
#     lines = []
#     for line in changelog.splitlines():
#         line = line.strip()
#         while line.startswith('*'):
#             line = line[1:].strip()
#         if line:
#             lines.append(line)
#     return " ".join(lines)
# 
# def get_changelog(contents=_read_changelog()):
#     "Returns a list of (version, date, notes) tuple"
# 
#     result = []
#     version_regex = r'^([0-9.]*) \((.*)\)$'
#     while contents:
#         match = re.search(version_regex, contents, re.M)
#         if match is None:
#             break
# 
#         version = match.group(1)
#         date = match.group(2)
#         changelog_offset = match.end()
# 
#         match = re.search(version_regex, contents[changelog_offset:], re.M)
#         if match:
#             notes = contents[changelog_offset:changelog_offset + match.start()]
#             contents = contents[changelog_offset + match.start():]
#         else:
#             notes = contents[changelog_offset:]
#             contents = ""
# 
#         lines = notes.strip().splitlines()
#         if set(lines[0]) != set('-') or lines[1].strip():
#             sys.exit("The changelog section should be followed by a '---' line, got '%s'" % lines)
#         notes = '\n'.join(lines[2:])
#         result.append((version, date, notes))
#     if not result:
#         sys.exit('Failed to find version')
#     return result
# 
# def notify(version, changelog, freshmeat_auth=_get_freshmeat_auth_code,
#         connection=httplib.HTTPConnection, system=os.system, confirm=raw_input,
#         tag_list=_get_tags):
#     # This is a fresmeat limit
#     MAX_CHARS = 600
#     short_message = shorten_changelog(changelog)
#     while len(short_message) > 600:
#         print 'Changelog is too long (must be less then %i characters, is %i)' % (MAX_CHARS, len(short_message))
#         text = raw_input('Edit changelog for submission? [y]')
#         if text and text != 'y':
#             print 'Servers not notified of release.'
#             return
# 
#         short_message = _edit_message(short_message)
# 
#     # Notify freshmeat
#     if confirm('Should freshmeat be notified? [y]') in ['', 'y', 'Y']:
#         release = {
#                 'auth_code': freshmeat_auth(),
#                 'release':{
#                     'tag_list':tag_list(connection, freshmeat_auth),
#                     'version':str(version),
#                     'changelog':short_message
#                     },
#                 }
#         headers = {"Content-type": "application/json"}
#         conn = connection("freshmeat.net")
#         conn.request("POST", "/projects/bdec/releases.json", json.dumps(release), headers)
#         response = conn.getresponse()
#         data = response.read()
#         conn.close()
#         if response.status >= 400:
#             print response.status, response.reason
#             sys.exit('Failed to submit to freshmeat! (%s)' % data)
#         print "Created release; %s %s\n%s" % (response.status, response.reason, data)
# 
#     else:
#         print 'Not notifying freshmeat.'
# 
#     # Notify the python package index
#     if confirm('Should pypi be notified? [y]') in ['', 'y', 'Y']:
#         os.chdir(root_path)
#         command = "./setup.py register"
#         if system(command) != 0:
#             sys.exit('Failed to update python package index!')
#     else:
#         print 'Not notifying pypi.'
# 
#     if confirm('Send an email to the bdec mailing list? [y]') in ['', 'y', 'Y']:
#         send_email(version, changelog)


# Path: tools/test/testrelease.py
import os.path
import StringIO
import unittest
import bdec
from tools.release import shorten_changelog, get_changelog, notify

        text = """
Blah blah

Download
========

9.9.9 (blah blah)
-----------------

Blah blah:
* Did this.
* Did that.

Ding dong:
* Went there.
* Came back.

1.2.3 (be bop)
--------------

This is the current version
   """
        changelog = get_changelog(text)
        self.assertEqual(2, len(changelog))
        self.assertEqual('9.9.9', changelog[0][0])
        self.assertEqual('blah blah', changelog[0][1])
        self.assertEqual('Blah blah: Did this. Did that. Ding dong: Went there. Came back.', shorten_changelog(changelog[0][2]))

        self.assertEqual('1.2.3', changelog[1][0])
        self.assertEqual('be bop', changelog[1][1])

        self.assertEqual('This is the current version', shorten_changelog(changelog[1][2]))