changelog.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  2. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. #
  4. # This file is part of logilab-common.
  5. #
  6. # logilab-common is free software: you can redistribute it and/or modify it under
  7. # the terms of the GNU Lesser General Public License as published by the Free
  8. # Software Foundation, either version 2.1 of the License, or (at your option) any
  9. # later version.
  10. #
  11. # logilab-common is distributed in the hope that it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  14. # details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public License along
  17. # with logilab-common. If not, see <http://www.gnu.org/licenses/>.
  18. """Manipulation of upstream change log files.
  19. The upstream change log files format handled is simpler than the one
  20. often used such as those generated by the default Emacs changelog mode.
  21. Sample ChangeLog format::
  22. Change log for project Yoo
  23. ==========================
  24. --
  25. * add a new functionality
  26. 2002-02-01 -- 0.1.1
  27. * fix bug #435454
  28. * fix bug #434356
  29. 2002-01-01 -- 0.1
  30. * initial release
  31. There is 3 entries in this change log, one for each released version and one
  32. for the next version (i.e. the current entry).
  33. Each entry contains a set of messages corresponding to changes done in this
  34. release.
  35. All the non empty lines before the first entry are considered as the change
  36. log title.
  37. """
  38. __docformat__ = "restructuredtext en"
  39. import sys
  40. from stat import S_IWRITE
  41. BULLET = '*'
  42. SUBBULLET = '-'
  43. INDENT = ' ' * 4
  44. class NoEntry(Exception):
  45. """raised when we are unable to find an entry"""
  46. class EntryNotFound(Exception):
  47. """raised when we are unable to find a given entry"""
  48. class Version(tuple):
  49. """simple class to handle soft version number has a tuple while
  50. correctly printing it as X.Y.Z
  51. """
  52. def __new__(cls, versionstr):
  53. if isinstance(versionstr, basestring):
  54. versionstr = versionstr.strip(' :') # XXX (syt) duh?
  55. parsed = cls.parse(versionstr)
  56. else:
  57. parsed = versionstr
  58. return tuple.__new__(cls, parsed)
  59. @classmethod
  60. def parse(cls, versionstr):
  61. versionstr = versionstr.strip(' :')
  62. try:
  63. return [int(i) for i in versionstr.split('.')]
  64. except ValueError, ex:
  65. raise ValueError("invalid literal for version '%s' (%s)"%(versionstr, ex))
  66. def __str__(self):
  67. return '.'.join([str(i) for i in self])
  68. # upstream change log #########################################################
  69. class ChangeLogEntry(object):
  70. """a change log entry, i.e. a set of messages associated to a version and
  71. its release date
  72. """
  73. version_class = Version
  74. def __init__(self, date=None, version=None, **kwargs):
  75. self.__dict__.update(kwargs)
  76. if version:
  77. self.version = self.version_class(version)
  78. else:
  79. self.version = None
  80. self.date = date
  81. self.messages = []
  82. def add_message(self, msg):
  83. """add a new message"""
  84. self.messages.append(([msg], []))
  85. def complete_latest_message(self, msg_suite):
  86. """complete the latest added message
  87. """
  88. if not self.messages:
  89. raise ValueError('unable to complete last message as there is no previous message)')
  90. if self.messages[-1][1]: # sub messages
  91. self.messages[-1][1][-1].append(msg_suite)
  92. else: # message
  93. self.messages[-1][0].append(msg_suite)
  94. def add_sub_message(self, sub_msg, key=None):
  95. if not self.messages:
  96. raise ValueError('unable to complete last message as there is no previous message)')
  97. if key is None:
  98. self.messages[-1][1].append([sub_msg])
  99. else:
  100. raise NotImplementedError("sub message to specific key are not implemented yet")
  101. def write(self, stream=sys.stdout):
  102. """write the entry to file """
  103. stream.write('%s -- %s\n' % (self.date or '', self.version or ''))
  104. for msg, sub_msgs in self.messages:
  105. stream.write('%s%s %s\n' % (INDENT, BULLET, msg[0]))
  106. stream.write(''.join(msg[1:]))
  107. if sub_msgs:
  108. stream.write('\n')
  109. for sub_msg in sub_msgs:
  110. stream.write('%s%s %s\n' % (INDENT * 2, SUBBULLET, sub_msg[0]))
  111. stream.write(''.join(sub_msg[1:]))
  112. stream.write('\n')
  113. stream.write('\n\n')
  114. class ChangeLog(object):
  115. """object representation of a whole ChangeLog file"""
  116. entry_class = ChangeLogEntry
  117. def __init__(self, changelog_file, title=''):
  118. self.file = changelog_file
  119. self.title = title
  120. self.additional_content = ''
  121. self.entries = []
  122. self.load()
  123. def __repr__(self):
  124. return '<ChangeLog %s at %s (%s entries)>' % (self.file, id(self),
  125. len(self.entries))
  126. def add_entry(self, entry):
  127. """add a new entry to the change log"""
  128. self.entries.append(entry)
  129. def get_entry(self, version='', create=None):
  130. """ return a given changelog entry
  131. if version is omitted, return the current entry
  132. """
  133. if not self.entries:
  134. if version or not create:
  135. raise NoEntry()
  136. self.entries.append(self.entry_class())
  137. if not version:
  138. if self.entries[0].version and create is not None:
  139. self.entries.insert(0, self.entry_class())
  140. return self.entries[0]
  141. version = self.version_class(version)
  142. for entry in self.entries:
  143. if entry.version == version:
  144. return entry
  145. raise EntryNotFound()
  146. def add(self, msg, create=None):
  147. """add a new message to the latest opened entry"""
  148. entry = self.get_entry(create=create)
  149. entry.add_message(msg)
  150. def load(self):
  151. """ read a logilab's ChangeLog from file """
  152. try:
  153. stream = open(self.file)
  154. except IOError:
  155. return
  156. last = None
  157. expect_sub = False
  158. for line in stream.readlines():
  159. sline = line.strip()
  160. words = sline.split()
  161. # if new entry
  162. if len(words) == 1 and words[0] == '--':
  163. expect_sub = False
  164. last = self.entry_class()
  165. self.add_entry(last)
  166. # if old entry
  167. elif len(words) == 3 and words[1] == '--':
  168. expect_sub = False
  169. last = self.entry_class(words[0], words[2])
  170. self.add_entry(last)
  171. # if title
  172. elif sline and last is None:
  173. self.title = '%s%s' % (self.title, line)
  174. # if new entry
  175. elif sline and sline[0] == BULLET:
  176. expect_sub = False
  177. last.add_message(sline[1:].strip())
  178. # if new sub_entry
  179. elif expect_sub and sline and sline[0] == SUBBULLET:
  180. last.add_sub_message(sline[1:].strip())
  181. # if new line for current entry
  182. elif sline and last.messages:
  183. last.complete_latest_message(line)
  184. else:
  185. expect_sub = True
  186. self.additional_content += line
  187. stream.close()
  188. def format_title(self):
  189. return '%s\n\n' % self.title.strip()
  190. def save(self):
  191. """write back change log"""
  192. # filetutils isn't importable in appengine, so import locally
  193. from logilab.common.fileutils import ensure_fs_mode
  194. ensure_fs_mode(self.file, S_IWRITE)
  195. self.write(open(self.file, 'w'))
  196. def write(self, stream=sys.stdout):
  197. """write changelog to stream"""
  198. stream.write(self.format_title())
  199. for entry in self.entries:
  200. entry.write(stream)