patchstream.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. # Copyright (c) 2011 The Chromium OS Authors.
  2. #
  3. # See file CREDITS for list of people who contributed to this
  4. # project.
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License as
  8. # published by the Free Software Foundation; either version 2 of
  9. # the License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  19. # MA 02111-1307 USA
  20. #
  21. import os
  22. import re
  23. import shutil
  24. import tempfile
  25. import command
  26. import commit
  27. import gitutil
  28. from series import Series
  29. # Tags that we detect and remove
  30. re_remove = re.compile('^BUG=|^TEST=|^BRANCH=|^Change-Id:|^Review URL:'
  31. '|Reviewed-on:|Reviewed-by:|Commit-Ready:')
  32. # Lines which are allowed after a TEST= line
  33. re_allowed_after_test = re.compile('^Signed-off-by:')
  34. # Signoffs
  35. re_signoff = re.compile('^Signed-off-by:')
  36. # The start of the cover letter
  37. re_cover = re.compile('^Cover-letter:')
  38. # Patch series tag
  39. re_series = re.compile('^Series-(\w*): *(.*)')
  40. # Commit tags that we want to collect and keep
  41. re_tag = re.compile('^(Tested-by|Acked-by|Cc): (.*)')
  42. # The start of a new commit in the git log
  43. re_commit = re.compile('^commit (.*)')
  44. # We detect these since checkpatch doesn't always do it
  45. re_space_before_tab = re.compile('^[+].* \t')
  46. # States we can be in - can we use range() and still have comments?
  47. STATE_MSG_HEADER = 0 # Still in the message header
  48. STATE_PATCH_SUBJECT = 1 # In patch subject (first line of log for a commit)
  49. STATE_PATCH_HEADER = 2 # In patch header (after the subject)
  50. STATE_DIFFS = 3 # In the diff part (past --- line)
  51. class PatchStream:
  52. """Class for detecting/injecting tags in a patch or series of patches
  53. We support processing the output of 'git log' to read out the tags we
  54. are interested in. We can also process a patch file in order to remove
  55. unwanted tags or inject additional ones. These correspond to the two
  56. phases of processing.
  57. """
  58. def __init__(self, series, name=None, is_log=False):
  59. self.skip_blank = False # True to skip a single blank line
  60. self.found_test = False # Found a TEST= line
  61. self.lines_after_test = 0 # MNumber of lines found after TEST=
  62. self.warn = [] # List of warnings we have collected
  63. self.linenum = 1 # Output line number we are up to
  64. self.in_section = None # Name of start...END section we are in
  65. self.notes = [] # Series notes
  66. self.section = [] # The current section...END section
  67. self.series = series # Info about the patch series
  68. self.is_log = is_log # True if indent like git log
  69. self.in_change = 0 # Non-zero if we are in a change list
  70. self.blank_count = 0 # Number of blank lines stored up
  71. self.state = STATE_MSG_HEADER # What state are we in?
  72. self.tags = [] # Tags collected, like Tested-by...
  73. self.signoff = [] # Contents of signoff line
  74. self.commit = None # Current commit
  75. def AddToSeries(self, line, name, value):
  76. """Add a new Series-xxx tag.
  77. When a Series-xxx tag is detected, we come here to record it, if we
  78. are scanning a 'git log'.
  79. Args:
  80. line: Source line containing tag (useful for debug/error messages)
  81. name: Tag name (part after 'Series-')
  82. value: Tag value (part after 'Series-xxx: ')
  83. """
  84. if name == 'notes':
  85. self.in_section = name
  86. self.skip_blank = False
  87. if self.is_log:
  88. self.series.AddTag(self.commit, line, name, value)
  89. def CloseCommit(self):
  90. """Save the current commit into our commit list, and reset our state"""
  91. if self.commit and self.is_log:
  92. self.series.AddCommit(self.commit)
  93. self.commit = None
  94. def FormatTags(self, tags):
  95. out_list = []
  96. for tag in sorted(tags):
  97. if tag.startswith('Cc:'):
  98. tag_list = tag[4:].split(',')
  99. out_list += gitutil.BuildEmailList(tag_list, 'Cc:')
  100. else:
  101. out_list.append(tag)
  102. return out_list
  103. def ProcessLine(self, line):
  104. """Process a single line of a patch file or commit log
  105. This process a line and returns a list of lines to output. The list
  106. may be empty or may contain multiple output lines.
  107. This is where all the complicated logic is located. The class's
  108. state is used to move between different states and detect things
  109. properly.
  110. We can be in one of two modes:
  111. self.is_log == True: This is 'git log' mode, where most output is
  112. indented by 4 characters and we are scanning for tags
  113. self.is_log == False: This is 'patch' mode, where we already have
  114. all the tags, and are processing patches to remove junk we
  115. don't want, and add things we think are required.
  116. Args:
  117. line: text line to process
  118. Returns:
  119. list of output lines, or [] if nothing should be output
  120. """
  121. # Initially we have no output. Prepare the input line string
  122. out = []
  123. line = line.rstrip('\n')
  124. if self.is_log:
  125. if line[:4] == ' ':
  126. line = line[4:]
  127. # Handle state transition and skipping blank lines
  128. series_match = re_series.match(line)
  129. commit_match = re_commit.match(line) if self.is_log else None
  130. tag_match = None
  131. if self.state == STATE_PATCH_HEADER:
  132. tag_match = re_tag.match(line)
  133. is_blank = not line.strip()
  134. if is_blank:
  135. if (self.state == STATE_MSG_HEADER
  136. or self.state == STATE_PATCH_SUBJECT):
  137. self.state += 1
  138. # We don't have a subject in the text stream of patch files
  139. # It has its own line with a Subject: tag
  140. if not self.is_log and self.state == STATE_PATCH_SUBJECT:
  141. self.state += 1
  142. elif commit_match:
  143. self.state = STATE_MSG_HEADER
  144. # If we are in a section, keep collecting lines until we see END
  145. if self.in_section:
  146. if line == 'END':
  147. if self.in_section == 'cover':
  148. self.series.cover = self.section
  149. elif self.in_section == 'notes':
  150. if self.is_log:
  151. self.series.notes += self.section
  152. else:
  153. self.warn.append("Unknown section '%s'" % self.in_section)
  154. self.in_section = None
  155. self.skip_blank = True
  156. self.section = []
  157. else:
  158. self.section.append(line)
  159. # Detect the commit subject
  160. elif not is_blank and self.state == STATE_PATCH_SUBJECT:
  161. self.commit.subject = line
  162. # Detect the tags we want to remove, and skip blank lines
  163. elif re_remove.match(line):
  164. self.skip_blank = True
  165. # TEST= should be the last thing in the commit, so remove
  166. # everything after it
  167. if line.startswith('TEST='):
  168. self.found_test = True
  169. elif self.skip_blank and is_blank:
  170. self.skip_blank = False
  171. # Detect the start of a cover letter section
  172. elif re_cover.match(line):
  173. self.in_section = 'cover'
  174. self.skip_blank = False
  175. # If we are in a change list, key collected lines until a blank one
  176. elif self.in_change:
  177. if is_blank:
  178. # Blank line ends this change list
  179. self.in_change = 0
  180. elif line == '---' or re_signoff.match(line):
  181. self.in_change = 0
  182. out = self.ProcessLine(line)
  183. else:
  184. if self.is_log:
  185. self.series.AddChange(self.in_change, self.commit, line)
  186. self.skip_blank = False
  187. # Detect Series-xxx tags
  188. elif series_match:
  189. name = series_match.group(1)
  190. value = series_match.group(2)
  191. if name == 'changes':
  192. # value is the version number: e.g. 1, or 2
  193. try:
  194. value = int(value)
  195. except ValueError as str:
  196. raise ValueError("%s: Cannot decode version info '%s'" %
  197. (self.commit.hash, line))
  198. self.in_change = int(value)
  199. else:
  200. self.AddToSeries(line, name, value)
  201. self.skip_blank = True
  202. # Detect the start of a new commit
  203. elif commit_match:
  204. self.CloseCommit()
  205. self.commit = commit.Commit(commit_match.group(1)[:7])
  206. # Detect tags in the commit message
  207. elif tag_match:
  208. # Remove Tested-by self, since few will take much notice
  209. if (tag_match.group(1) == 'Tested-by' and
  210. tag_match.group(2).find(os.getenv('USER') + '@') != -1):
  211. self.warn.append("Ignoring %s" % line)
  212. elif tag_match.group(1) == 'Cc':
  213. self.commit.AddCc(tag_match.group(2).split(','))
  214. else:
  215. self.tags.append(line);
  216. # Well that means this is an ordinary line
  217. else:
  218. pos = 1
  219. # Look for ugly ASCII characters
  220. for ch in line:
  221. # TODO: Would be nicer to report source filename and line
  222. if ord(ch) > 0x80:
  223. self.warn.append("Line %d/%d ('%s') has funny ascii char" %
  224. (self.linenum, pos, line))
  225. pos += 1
  226. # Look for space before tab
  227. m = re_space_before_tab.match(line)
  228. if m:
  229. self.warn.append('Line %d/%d has space before tab' %
  230. (self.linenum, m.start()))
  231. # OK, we have a valid non-blank line
  232. out = [line]
  233. self.linenum += 1
  234. self.skip_blank = False
  235. if self.state == STATE_DIFFS:
  236. pass
  237. # If this is the start of the diffs section, emit our tags and
  238. # change log
  239. elif line == '---':
  240. self.state = STATE_DIFFS
  241. # Output the tags (signeoff first), then change list
  242. out = []
  243. log = self.series.MakeChangeLog(self.commit)
  244. out += self.FormatTags(self.tags)
  245. out += [line] + log
  246. elif self.found_test:
  247. if not re_allowed_after_test.match(line):
  248. self.lines_after_test += 1
  249. return out
  250. def Finalize(self):
  251. """Close out processing of this patch stream"""
  252. self.CloseCommit()
  253. if self.lines_after_test:
  254. self.warn.append('Found %d lines after TEST=' %
  255. self.lines_after_test)
  256. def ProcessStream(self, infd, outfd):
  257. """Copy a stream from infd to outfd, filtering out unwanting things.
  258. This is used to process patch files one at a time.
  259. Args:
  260. infd: Input stream file object
  261. outfd: Output stream file object
  262. """
  263. # Extract the filename from each diff, for nice warnings
  264. fname = None
  265. last_fname = None
  266. re_fname = re.compile('diff --git a/(.*) b/.*')
  267. while True:
  268. line = infd.readline()
  269. if not line:
  270. break
  271. out = self.ProcessLine(line)
  272. # Try to detect blank lines at EOF
  273. for line in out:
  274. match = re_fname.match(line)
  275. if match:
  276. last_fname = fname
  277. fname = match.group(1)
  278. if line == '+':
  279. self.blank_count += 1
  280. else:
  281. if self.blank_count and (line == '-- ' or match):
  282. self.warn.append("Found possible blank line(s) at "
  283. "end of file '%s'" % last_fname)
  284. outfd.write('+\n' * self.blank_count)
  285. outfd.write(line + '\n')
  286. self.blank_count = 0
  287. self.Finalize()
  288. def GetMetaData(start, count):
  289. """Reads out patch series metadata from the commits
  290. This does a 'git log' on the relevant commits and pulls out the tags we
  291. are interested in.
  292. Args:
  293. start: Commit to start from: 0=HEAD, 1=next one, etc.
  294. count: Number of commits to list
  295. """
  296. pipe = [['git', 'log', '--no-color', '--reverse', 'HEAD~%d' % start,
  297. '-n%d' % count]]
  298. stdout = command.RunPipe(pipe, capture=True).stdout
  299. series = Series()
  300. ps = PatchStream(series, is_log=True)
  301. for line in stdout.splitlines():
  302. ps.ProcessLine(line)
  303. ps.Finalize()
  304. return series
  305. def FixPatch(backup_dir, fname, series, commit):
  306. """Fix up a patch file, by adding/removing as required.
  307. We remove our tags from the patch file, insert changes lists, etc.
  308. The patch file is processed in place, and overwritten.
  309. A backup file is put into backup_dir (if not None).
  310. Args:
  311. fname: Filename to patch file to process
  312. series: Series information about this patch set
  313. commit: Commit object for this patch file
  314. Return:
  315. A list of errors, or [] if all ok.
  316. """
  317. handle, tmpname = tempfile.mkstemp()
  318. outfd = os.fdopen(handle, 'w')
  319. infd = open(fname, 'r')
  320. ps = PatchStream(series)
  321. ps.commit = commit
  322. ps.ProcessStream(infd, outfd)
  323. infd.close()
  324. outfd.close()
  325. # Create a backup file if required
  326. if backup_dir:
  327. shutil.copy(fname, os.path.join(backup_dir, os.path.basename(fname)))
  328. shutil.move(tmpname, fname)
  329. return ps.warn
  330. def FixPatches(series, fnames):
  331. """Fix up a list of patches identified by filenames
  332. The patch files are processed in place, and overwritten.
  333. Args:
  334. series: The series object
  335. fnames: List of patch files to process
  336. """
  337. # Current workflow creates patches, so we shouldn't need a backup
  338. backup_dir = None #tempfile.mkdtemp('clean-patch')
  339. count = 0
  340. for fname in fnames:
  341. commit = series.commits[count]
  342. commit.patch = fname
  343. result = FixPatch(backup_dir, fname, series, commit)
  344. if result:
  345. print '%d warnings for %s:' % (len(result), fname)
  346. for warn in result:
  347. print '\t', warn
  348. print
  349. count += 1
  350. print 'Cleaned %d patches' % count
  351. return series
  352. def InsertCoverLetter(fname, series, count):
  353. """Inserts a cover letter with the required info into patch 0
  354. Args:
  355. fname: Input / output filename of the cover letter file
  356. series: Series object
  357. count: Number of patches in the series
  358. """
  359. fd = open(fname, 'r')
  360. lines = fd.readlines()
  361. fd.close()
  362. fd = open(fname, 'w')
  363. text = series.cover
  364. prefix = series.GetPatchPrefix()
  365. for line in lines:
  366. if line.startswith('Subject:'):
  367. # TODO: if more than 10 patches this should save 00/xx, not 0/xx
  368. line = 'Subject: [%s 0/%d] %s\n' % (prefix, count, text[0])
  369. # Insert our cover letter
  370. elif line.startswith('*** BLURB HERE ***'):
  371. # First the blurb test
  372. line = '\n'.join(text[1:]) + '\n'
  373. if series.get('notes'):
  374. line += '\n'.join(series.notes) + '\n'
  375. # Now the change list
  376. out = series.MakeChangeLog(None)
  377. line += '\n' + '\n'.join(out)
  378. fd.write(line)
  379. fd.close()