format_changelog.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. #!/usr/bin/python
  2. # Copyright (c) 2014, The Tor Project, Inc.
  3. # See LICENSE for licensing information
  4. #
  5. # This script reformats a section of the changelog to wrap everything to
  6. # the right width and put blank lines in the right places. Eventually,
  7. # it might include a linter.
  8. #
  9. # To run it, pipe a section of the changelog (starting with "Changes
  10. # in Tor 0.x.y.z-alpha" through the script.)
  11. import os
  12. import re
  13. import sys
  14. # ==============================
  15. # Oh, look! It's a cruddy approximation to Knuth's elegant text wrapping
  16. # algorithm, with totally ad hoc parameters!
  17. #
  18. # We're trying to minimize:
  19. # The total of the cubes of ragged space on underflowed intermediate lines,
  20. # PLUS
  21. # 100 * the fourth power of overflowed characters
  22. # PLUS
  23. # .1 * a bit more than the cube of ragged space on the last line.
  24. #
  25. # We use an obvious dynamic programming algorithm to sorta approximate this.
  26. # It's not coded right or optimally, but it's fast enough for changelogs
  27. #
  28. # (Code found in an old directory of mine, lightly cleaned. -NM)
  29. NO_HYPHENATE=set("""
  30. pf-divert
  31. """.split())
  32. LASTLINE_UNDERFLOW_EXPONENT = 1
  33. LASTLINE_UNDERFLOW_PENALTY = 1
  34. UNDERFLOW_EXPONENT = 3
  35. UNDERFLOW_PENALTY = 1
  36. OVERFLOW_EXPONENT = 4
  37. OVERFLOW_PENALTY = 2000
  38. ORPHAN_PENALTY = 10000
  39. def generate_wrapping(words, divisions):
  40. lines = []
  41. last = 0
  42. for i in divisions:
  43. w = words[last:i]
  44. last = i
  45. line = " ".join(w).replace("\xff ","-").replace("\xff","-")
  46. lines.append(line)
  47. return lines
  48. def wrapping_quality(words, divisions, width1, width2):
  49. total = 0.0
  50. lines = generate_wrapping(words, divisions)
  51. for line in lines:
  52. length = len(line)
  53. if line is lines[0]:
  54. width = width1
  55. else:
  56. width = width2
  57. if length > width:
  58. total += OVERFLOW_PENALTY * (
  59. (length - width) ** OVERFLOW_EXPONENT )
  60. else:
  61. if line is lines[-1]:
  62. e,p = (LASTLINE_UNDERFLOW_EXPONENT, LASTLINE_UNDERFLOW_PENALTY)
  63. if " " not in line:
  64. total += ORPHAN_PENALTY
  65. else:
  66. e,p = (UNDERFLOW_EXPONENT, UNDERFLOW_PENALTY)
  67. total += p * ((width - length) ** e)
  68. return total
  69. def wrap_graf(words, prefix_len1=0, prefix_len2=0, width=72):
  70. wrapping_after = [ (0,), ]
  71. w1 = width - prefix_len1
  72. w2 = width - prefix_len2
  73. for i in range(1, len(words)+1):
  74. best_so_far = None
  75. best_score = 1e300
  76. for j in range(i):
  77. t = wrapping_after[j]
  78. t1 = t[:-1] + (i,)
  79. t2 = t + (i,)
  80. wq1 = wrapping_quality(words, t1, w1, w2)
  81. wq2 = wrapping_quality(words, t2, w1, w2)
  82. if wq1 < best_score:
  83. best_so_far = t1
  84. best_score = wq1
  85. if wq2 < best_score:
  86. best_so_far = t2
  87. best_score = wq2
  88. wrapping_after.append( best_so_far )
  89. lines = generate_wrapping(words, wrapping_after[-1])
  90. return lines
  91. def hyphenateable(word):
  92. if re.match(r'^[^\d\-].*-', word):
  93. stripped = re.sub(r'^\W+','',word)
  94. stripped = re.sub(r'\W+$','',word)
  95. return stripped not in NO_HYPHENATE
  96. else:
  97. return False
  98. def split_paragraph(s):
  99. "Split paragraph into words; tuned for Tor."
  100. r = []
  101. for word in s.split():
  102. if hyphenateable(word):
  103. while "-" in word:
  104. a,word = word.split("-",1)
  105. r.append(a+"\xff")
  106. r.append(word)
  107. return r
  108. def fill(text, width, initial_indent, subsequent_indent):
  109. words = split_paragraph(text)
  110. lines = wrap_graf(words, len(initial_indent), len(subsequent_indent),
  111. width)
  112. res = [ initial_indent, lines[0], "\n" ]
  113. for line in lines[1:]:
  114. res.append(subsequent_indent)
  115. res.append(line)
  116. res.append("\n")
  117. return "".join(res)
  118. # ==============================
  119. TP_MAINHEAD = 0
  120. TP_HEADTEXT = 1
  121. TP_BLANK = 2
  122. TP_SECHEAD = 3
  123. TP_ITEMFIRST = 4
  124. TP_ITEMBODY = 5
  125. TP_END = 6
  126. def head_parser(line):
  127. if re.match(r'^[A-Z]', line):
  128. return TP_MAINHEAD
  129. elif re.match(r'^ o ', line):
  130. return TP_SECHEAD
  131. elif re.match(r'^\s*$', line):
  132. return TP_BLANK
  133. else:
  134. return TP_HEADTEXT
  135. def body_parser(line):
  136. if re.match(r'^ o ', line):
  137. return TP_SECHEAD
  138. elif re.match(r'^ -',line):
  139. return TP_ITEMFIRST
  140. elif re.match(r'^ \S', line):
  141. return TP_ITEMBODY
  142. elif re.match(r'^\s*$', line):
  143. return TP_BLANK
  144. elif re.match(r'^Changes in', line):
  145. return TP_END
  146. else:
  147. print "Weird line %r"%line
  148. class ChangeLog(object):
  149. def __init__(self):
  150. self.mainhead = None
  151. self.headtext = []
  152. self.curgraf = None
  153. self.sections = []
  154. self.cursection = None
  155. self.lineno = 0
  156. def addLine(self, tp, line):
  157. self.lineno += 1
  158. if tp == TP_MAINHEAD:
  159. assert not self.mainhead
  160. self.mainhead = line
  161. elif tp == TP_HEADTEXT:
  162. if self.curgraf is None:
  163. self.curgraf = []
  164. self.headtext.append(self.curgraf)
  165. self.curgraf.append(line)
  166. elif tp == TP_BLANK:
  167. self.curgraf = None
  168. elif tp == TP_SECHEAD:
  169. self.cursection = [ self.lineno, line, [] ]
  170. self.sections.append(self.cursection)
  171. elif tp == TP_ITEMFIRST:
  172. item = ( self.lineno, [ [line] ])
  173. self.curgraf = item[1][0]
  174. self.cursection[2].append(item)
  175. elif tp == TP_ITEMBODY:
  176. if self.curgraf is None:
  177. self.curgraf = []
  178. self.cursection[2][1][-1].append(self.curgraf)
  179. self.curgraf.append(line)
  180. else:
  181. assert "This" is "unreachable"
  182. def lint_head(self, line, head):
  183. m = re.match(r'^ *o ([^\(]+)((?:\([^\)]+\))?):', head)
  184. if not m:
  185. print >>sys.stderr, "Weird header format on line %s"%line
  186. def lint_item(self, line, grafs, head_type):
  187. pass
  188. def lint(self):
  189. self.head_lines = {}
  190. for sec_line, sec_head, items in self.sections:
  191. head_type = self.lint_head(sec_line, sec_head)
  192. for item_line, grafs in items:
  193. self.lint_item(item_line, grafs, head_type)
  194. def dumpGraf(self,par,indent1,indent2=-1):
  195. if indent2 == -1:
  196. indent2 = indent1
  197. text = " ".join(re.sub(r'\s+', ' ', line.strip()) for line in par)
  198. sys.stdout.write(fill(text,
  199. width=72,
  200. initial_indent=" "*indent1,
  201. subsequent_indent=" "*indent2))
  202. def dump(self):
  203. print self.mainhead
  204. for par in self.headtext:
  205. self.dumpGraf(par, 2)
  206. print
  207. for _,head,items in self.sections:
  208. if not head.endswith(':'):
  209. print >>sys.stderr, "adding : to %r"%head
  210. head = head + ":"
  211. print head
  212. for _,grafs in items:
  213. self.dumpGraf(grafs[0],4,6)
  214. for par in grafs[1:]:
  215. print
  216. self.dumpGraf(par,6,6)
  217. print
  218. print
  219. CL = ChangeLog()
  220. parser = head_parser
  221. sys.stdin = open('ChangeLog', 'r')
  222. for line in sys.stdin:
  223. line = line.rstrip()
  224. tp = parser(line)
  225. if tp == TP_SECHEAD:
  226. parser = body_parser
  227. elif tp == TP_END:
  228. nextline = line
  229. break
  230. CL.addLine(tp,line)
  231. CL.lint()
  232. sys.stdout = open('ChangeLog.new', 'w')
  233. CL.dump()
  234. print nextline
  235. for line in sys.stdin:
  236. sys.stdout.write(line)
  237. os.rename('ChangeLog.new', 'ChangeLog')