patchstream.py 17 KB

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