format_changelog.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. import optparse
  15. # ==============================
  16. # Oh, look! It's a cruddy approximation to Knuth's elegant text wrapping
  17. # algorithm, with totally ad hoc parameters!
  18. #
  19. # We're trying to minimize:
  20. # The total of the cubes of ragged space on underflowed intermediate lines,
  21. # PLUS
  22. # 100 * the fourth power of overflowed characters
  23. # PLUS
  24. # .1 * a bit more than the cube of ragged space on the last line.
  25. # PLUS
  26. # OPENPAREN_PENALTY for each line that starts with (
  27. #
  28. # We use an obvious dynamic programming algorithm to sorta approximate this.
  29. # It's not coded right or optimally, but it's fast enough for changelogs
  30. #
  31. # (Code found in an old directory of mine, lightly cleaned. -NM)
  32. NO_HYPHENATE=set("""
  33. pf-divert
  34. """.split())
  35. LASTLINE_UNDERFLOW_EXPONENT = 1
  36. LASTLINE_UNDERFLOW_PENALTY = 1
  37. UNDERFLOW_EXPONENT = 3
  38. UNDERFLOW_PENALTY = 1
  39. OVERFLOW_EXPONENT = 4
  40. OVERFLOW_PENALTY = 2000
  41. ORPHAN_PENALTY = 10000
  42. OPENPAREN_PENALTY = 200
  43. def generate_wrapping(words, divisions):
  44. lines = []
  45. last = 0
  46. for i in divisions:
  47. w = words[last:i]
  48. last = i
  49. line = " ".join(w).replace("\xff ","-").replace("\xff","-")
  50. lines.append(line)
  51. return lines
  52. def wrapping_quality(words, divisions, width1, width2):
  53. total = 0.0
  54. lines = generate_wrapping(words, divisions)
  55. for line in lines:
  56. length = len(line)
  57. if line is lines[0]:
  58. width = width1
  59. else:
  60. width = width2
  61. if line[0:1] == '(':
  62. total += OPENPAREN_PENALTY
  63. if length > width:
  64. total += OVERFLOW_PENALTY * (
  65. (length - width) ** OVERFLOW_EXPONENT )
  66. else:
  67. if line is lines[-1]:
  68. e,p = (LASTLINE_UNDERFLOW_EXPONENT, LASTLINE_UNDERFLOW_PENALTY)
  69. if " " not in line:
  70. total += ORPHAN_PENALTY
  71. else:
  72. e,p = (UNDERFLOW_EXPONENT, UNDERFLOW_PENALTY)
  73. total += p * ((width - length) ** e)
  74. return total
  75. def wrap_graf(words, prefix_len1=0, prefix_len2=0, width=72):
  76. wrapping_after = [ (0,), ]
  77. w1 = width - prefix_len1
  78. w2 = width - prefix_len2
  79. for i in range(1, len(words)+1):
  80. best_so_far = None
  81. best_score = 1e300
  82. for j in range(i):
  83. t = wrapping_after[j]
  84. t1 = t[:-1] + (i,)
  85. t2 = t + (i,)
  86. wq1 = wrapping_quality(words, t1, w1, w2)
  87. wq2 = wrapping_quality(words, t2, w1, w2)
  88. if wq1 < best_score:
  89. best_so_far = t1
  90. best_score = wq1
  91. if wq2 < best_score:
  92. best_so_far = t2
  93. best_score = wq2
  94. wrapping_after.append( best_so_far )
  95. lines = generate_wrapping(words, wrapping_after[-1])
  96. return lines
  97. def hyphenateable(word):
  98. if re.match(r'^[^\d\-]\D*-', word):
  99. stripped = re.sub(r'^\W+','',word)
  100. stripped = re.sub(r'\W+$','',word)
  101. return stripped not in NO_HYPHENATE
  102. else:
  103. return False
  104. def split_paragraph(s):
  105. "Split paragraph into words; tuned for Tor."
  106. r = []
  107. for word in s.split():
  108. if hyphenateable(word):
  109. while "-" in word:
  110. a,word = word.split("-",1)
  111. r.append(a+"\xff")
  112. r.append(word)
  113. return r
  114. def fill(text, width, initial_indent, subsequent_indent):
  115. words = split_paragraph(text)
  116. lines = wrap_graf(words, len(initial_indent), len(subsequent_indent),
  117. width)
  118. res = [ initial_indent, lines[0], "\n" ]
  119. for line in lines[1:]:
  120. res.append(subsequent_indent)
  121. res.append(line)
  122. res.append("\n")
  123. return "".join(res)
  124. # ==============================
  125. TP_MAINHEAD = 0
  126. TP_HEADTEXT = 1
  127. TP_BLANK = 2
  128. TP_SECHEAD = 3
  129. TP_ITEMFIRST = 4
  130. TP_ITEMBODY = 5
  131. TP_END = 6
  132. TP_PREHEAD = 7
  133. def head_parser(line):
  134. if re.match(r'^Changes in', line):
  135. return TP_MAINHEAD
  136. elif re.match(r'^[A-Za-z]', line):
  137. return TP_PREHEAD
  138. elif re.match(r'^ o ', line):
  139. return TP_SECHEAD
  140. elif re.match(r'^\s*$', line):
  141. return TP_BLANK
  142. else:
  143. return TP_HEADTEXT
  144. def body_parser(line):
  145. if re.match(r'^ o ', line):
  146. return TP_SECHEAD
  147. elif re.match(r'^ -',line):
  148. return TP_ITEMFIRST
  149. elif re.match(r'^ \S', line):
  150. return TP_ITEMBODY
  151. elif re.match(r'^\s*$', line):
  152. return TP_BLANK
  153. elif re.match(r'^Changes in', line):
  154. return TP_END
  155. elif re.match(r'^\s+\S', line):
  156. return TP_HEADTEXT
  157. else:
  158. print "Weird line %r"%line
  159. def clean_head(head):
  160. return head
  161. def head_score(s):
  162. m = re.match(r'^ +o (.*)', s)
  163. if not m:
  164. print >>sys.stderr, "Can't score %r"%s
  165. return 99999
  166. lw = m.group(1).lower()
  167. if lw.startswith("security") and "feature" not in lw:
  168. score = -300
  169. elif lw.startswith("deprecated versions"):
  170. score = -200
  171. elif "build require" in lw:
  172. score = -100
  173. elif lw.startswith("major feature"):
  174. score = 00
  175. elif lw.startswith("major bug"):
  176. score = 50
  177. elif lw.startswith("major"):
  178. score = 70
  179. elif lw.startswith("minor feature"):
  180. score = 200
  181. elif lw.startswith("minor bug"):
  182. score = 250
  183. elif lw.startswith("minor"):
  184. score = 270
  185. else:
  186. score = 1000
  187. if 'secur' in lw:
  188. score -= 2
  189. if "(other)" in lw:
  190. score += 2
  191. if '(' not in lw:
  192. score -= 1
  193. return score
  194. class ChangeLog(object):
  195. def __init__(self, wrapText=True):
  196. self.prehead = []
  197. self.mainhead = None
  198. self.headtext = []
  199. self.curgraf = None
  200. self.sections = []
  201. self.cursection = None
  202. self.lineno = 0
  203. self.wrapText = wrapText
  204. def addLine(self, tp, line):
  205. self.lineno += 1
  206. if tp == TP_MAINHEAD:
  207. assert not self.mainhead
  208. self.mainhead = line
  209. elif tp == TP_PREHEAD:
  210. self.prehead.append(line)
  211. elif tp == TP_HEADTEXT:
  212. if self.curgraf is None:
  213. self.curgraf = []
  214. self.headtext.append(self.curgraf)
  215. self.curgraf.append(line)
  216. elif tp == TP_BLANK:
  217. self.curgraf = None
  218. elif tp == TP_SECHEAD:
  219. self.cursection = [ self.lineno, line, [] ]
  220. self.sections.append(self.cursection)
  221. elif tp == TP_ITEMFIRST:
  222. item = ( self.lineno, [ [line] ])
  223. self.curgraf = item[1][0]
  224. self.cursection[2].append(item)
  225. elif tp == TP_ITEMBODY:
  226. if self.curgraf is None:
  227. self.curgraf = []
  228. self.cursection[2][-1][1].append(self.curgraf)
  229. self.curgraf.append(line)
  230. else:
  231. assert "This" is "unreachable"
  232. def lint_head(self, line, head):
  233. m = re.match(r'^ *o ([^\(]+)((?:\([^\)]+\))?):', head)
  234. if not m:
  235. print >>sys.stderr, "Weird header format on line %s"%line
  236. def lint_item(self, line, grafs, head_type):
  237. pass
  238. def lint(self):
  239. self.head_lines = {}
  240. for sec_line, sec_head, items in self.sections:
  241. head_type = self.lint_head(sec_line, sec_head)
  242. for item_line, grafs in items:
  243. self.lint_item(item_line, grafs, head_type)
  244. def dumpGraf(self,par,indent1,indent2=-1):
  245. if not self.wrapText:
  246. for line in par:
  247. print line
  248. return
  249. if indent2 == -1:
  250. indent2 = indent1
  251. text = " ".join(re.sub(r'\s+', ' ', line.strip()) for line in par)
  252. sys.stdout.write(fill(text,
  253. width=72,
  254. initial_indent=" "*indent1,
  255. subsequent_indent=" "*indent2))
  256. def collateAndSortSections(self):
  257. heads = []
  258. sectionsByHead = { }
  259. for _, head, items in self.sections:
  260. head = clean_head(head)
  261. try:
  262. s = sectionsByHead[head]
  263. except KeyError:
  264. s = sectionsByHead[head] = []
  265. heads.append( (head_score(head), head, s) )
  266. s.extend(items)
  267. heads.sort()
  268. self.sections = [ (0, head, items) for _,head,items in heads ]
  269. def dump(self):
  270. if self.prehead:
  271. self.dumpGraf(self.prehead, 0)
  272. print
  273. print self.mainhead
  274. for par in self.headtext:
  275. self.dumpGraf(par, 2)
  276. print
  277. for _,head,items in self.sections:
  278. if not head.endswith(':'):
  279. print >>sys.stderr, "adding : to %r"%head
  280. head = head + ":"
  281. print head
  282. for _,grafs in items:
  283. self.dumpGraf(grafs[0],4,6)
  284. for par in grafs[1:]:
  285. print
  286. self.dumpGraf(par,6,6)
  287. print
  288. print
  289. op = optparse.OptionParser(usage="usage: %prog [options] [filename]")
  290. op.add_option('-W', '--no-wrap', action='store_false',
  291. dest='wrapText', default=True,
  292. help='Do not re-wrap paragraphs')
  293. op.add_option('-S', '--no-sort', action='store_false',
  294. dest='sort', default=True,
  295. help='Do not sort or collate sections')
  296. op.add_option('-o', '--output', dest='output',
  297. default=None, metavar='FILE', help="write output to FILE")
  298. options,args = op.parse_args()
  299. if len(args) > 1:
  300. op.error("Too many arguments")
  301. elif len(args) == 0:
  302. fname = 'ChangeLog'
  303. else:
  304. fname = args[0]
  305. if options.output == None:
  306. options.output = fname
  307. if fname != '-':
  308. sys.stdin = open(fname, 'r')
  309. nextline = None
  310. CL = ChangeLog(wrapText=options.wrapText)
  311. parser = head_parser
  312. for line in sys.stdin:
  313. line = line.rstrip()
  314. tp = parser(line)
  315. if tp == TP_SECHEAD:
  316. parser = body_parser
  317. elif tp == TP_END:
  318. nextline = line
  319. break
  320. CL.addLine(tp,line)
  321. CL.lint()
  322. if options.output != '-':
  323. fname_new = options.output+".new"
  324. fname_out = options.output
  325. sys.stdout = open(fname_new, 'w')
  326. else:
  327. fname_new = fname_out = None
  328. if options.sort:
  329. CL.collateAndSortSections()
  330. CL.dump()
  331. if nextline is not None:
  332. print nextline
  333. for line in sys.stdin:
  334. sys.stdout.write(line)
  335. if fname_new is not None:
  336. os.rename(fname_new, fname_out)