patchstream.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 a tag is detected, but we are already in a section,
  139. # this means 'END' is missing for that section, fix it up.
  140. if series_tag_match or commit_tag_match or \
  141. cover_match or cover_cc_match or signoff_match:
  142. if self.in_section:
  143. self.warn.append("Missing 'END' in section '%s'" % self.in_section)
  144. if self.in_section == 'cover':
  145. self.series.cover = self.section
  146. elif self.in_section == 'notes':
  147. if self.is_log:
  148. self.series.notes += self.section
  149. elif self.in_section == 'commit-notes':
  150. if self.is_log:
  151. self.commit.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. # If we are in a section, keep collecting lines until we see END
  158. if self.in_section:
  159. if line == 'END':
  160. if self.in_section == 'cover':
  161. self.series.cover = self.section
  162. elif self.in_section == 'notes':
  163. if self.is_log:
  164. self.series.notes += self.section
  165. elif self.in_section == 'commit-notes':
  166. if self.is_log:
  167. self.commit.notes += self.section
  168. else:
  169. self.warn.append("Unknown section '%s'" % self.in_section)
  170. self.in_section = None
  171. self.skip_blank = True
  172. self.section = []
  173. else:
  174. self.section.append(line)
  175. # Detect the commit subject
  176. elif not is_blank and self.state == STATE_PATCH_SUBJECT:
  177. self.commit.subject = line
  178. # Detect the tags we want to remove, and skip blank lines
  179. elif re_remove.match(line) and not commit_tag_match:
  180. self.skip_blank = True
  181. # TEST= should be the last thing in the commit, so remove
  182. # everything after it
  183. if line.startswith('TEST='):
  184. self.found_test = True
  185. elif self.skip_blank and is_blank:
  186. self.skip_blank = False
  187. # Detect the start of a cover letter section
  188. elif cover_match:
  189. self.in_section = 'cover'
  190. self.skip_blank = False
  191. elif cover_cc_match:
  192. value = cover_cc_match.group(1)
  193. self.AddToSeries(line, 'cover-cc', value)
  194. # If we are in a change list, key collected lines until a blank one
  195. elif self.in_change:
  196. if is_blank:
  197. # Blank line ends this change list
  198. self.in_change = 0
  199. elif line == '---':
  200. self.in_change = 0
  201. out = self.ProcessLine(line)
  202. else:
  203. if self.is_log:
  204. self.series.AddChange(self.in_change, self.commit, line)
  205. self.skip_blank = False
  206. # Detect Series-xxx tags
  207. elif series_tag_match:
  208. name = series_tag_match.group(1)
  209. value = series_tag_match.group(2)
  210. if name == 'changes':
  211. # value is the version number: e.g. 1, or 2
  212. try:
  213. value = int(value)
  214. except ValueError as str:
  215. raise ValueError("%s: Cannot decode version info '%s'" %
  216. (self.commit.hash, line))
  217. self.in_change = int(value)
  218. else:
  219. self.AddToSeries(line, name, value)
  220. self.skip_blank = True
  221. # Detect Commit-xxx tags
  222. elif commit_tag_match:
  223. name = commit_tag_match.group(1)
  224. value = commit_tag_match.group(2)
  225. if name == 'notes':
  226. self.AddToCommit(line, name, value)
  227. self.skip_blank = True
  228. # Detect the start of a new commit
  229. elif commit_match:
  230. self.CloseCommit()
  231. self.commit = commit.Commit(commit_match.group(1))
  232. # Detect tags in the commit message
  233. elif tag_match:
  234. # Remove Tested-by self, since few will take much notice
  235. if (tag_match.group(1) == 'Tested-by' and
  236. tag_match.group(2).find(os.getenv('USER') + '@') != -1):
  237. self.warn.append("Ignoring %s" % line)
  238. elif tag_match.group(1) == 'Patch-cc':
  239. self.commit.AddCc(tag_match.group(2).split(','))
  240. else:
  241. out = [line]
  242. # Suppress duplicate signoffs
  243. elif signoff_match:
  244. if (self.is_log or not self.commit or
  245. self.commit.CheckDuplicateSignoff(signoff_match.group(1))):
  246. out = [line]
  247. # Well that means this is an ordinary line
  248. else:
  249. pos = 1
  250. # Look for ugly ASCII characters
  251. for ch in line:
  252. # TODO: Would be nicer to report source filename and line
  253. if ord(ch) > 0x80:
  254. self.warn.append("Line %d/%d ('%s') has funny ascii char" %
  255. (self.linenum, pos, line))
  256. pos += 1
  257. # Look for space before tab
  258. m = re_space_before_tab.match(line)
  259. if m:
  260. self.warn.append('Line %d/%d has space before tab' %
  261. (self.linenum, m.start()))
  262. # OK, we have a valid non-blank line
  263. out = [line]
  264. self.linenum += 1
  265. self.skip_blank = False
  266. if self.state == STATE_DIFFS:
  267. pass
  268. # If this is the start of the diffs section, emit our tags and
  269. # change log
  270. elif line == '---':
  271. self.state = STATE_DIFFS
  272. # Output the tags (signeoff first), then change list
  273. out = []
  274. log = self.series.MakeChangeLog(self.commit)
  275. out += [line]
  276. if self.commit:
  277. out += self.commit.notes
  278. out += [''] + log
  279. elif self.found_test:
  280. if not re_allowed_after_test.match(line):
  281. self.lines_after_test += 1
  282. return out
  283. def Finalize(self):
  284. """Close out processing of this patch stream"""
  285. self.CloseCommit()
  286. if self.lines_after_test:
  287. self.warn.append('Found %d lines after TEST=' %
  288. self.lines_after_test)
  289. def ProcessStream(self, infd, outfd):
  290. """Copy a stream from infd to outfd, filtering out unwanting things.
  291. This is used to process patch files one at a time.
  292. Args:
  293. infd: Input stream file object
  294. outfd: Output stream file object
  295. """
  296. # Extract the filename from each diff, for nice warnings
  297. fname = None
  298. last_fname = None
  299. re_fname = re.compile('diff --git a/(.*) b/.*')
  300. while True:
  301. line = infd.readline()
  302. if not line:
  303. break
  304. out = self.ProcessLine(line)
  305. # Try to detect blank lines at EOF
  306. for line in out:
  307. match = re_fname.match(line)
  308. if match:
  309. last_fname = fname
  310. fname = match.group(1)
  311. if line == '+':
  312. self.blank_count += 1
  313. else:
  314. if self.blank_count and (line == '-- ' or match):
  315. self.warn.append("Found possible blank line(s) at "
  316. "end of file '%s'" % last_fname)
  317. outfd.write('+\n' * self.blank_count)
  318. outfd.write(line + '\n')
  319. self.blank_count = 0
  320. self.Finalize()
  321. def GetMetaDataForList(commit_range, git_dir=None, count=None,
  322. series = None, allow_overwrite=False):
  323. """Reads out patch series metadata from the commits
  324. This does a 'git log' on the relevant commits and pulls out the tags we
  325. are interested in.
  326. Args:
  327. commit_range: Range of commits to count (e.g. 'HEAD..base')
  328. git_dir: Path to git repositiory (None to use default)
  329. count: Number of commits to list, or None for no limit
  330. series: Series object to add information into. By default a new series
  331. is started.
  332. allow_overwrite: Allow tags to overwrite an existing tag
  333. Returns:
  334. A Series object containing information about the commits.
  335. """
  336. if not series:
  337. series = Series()
  338. series.allow_overwrite = allow_overwrite
  339. params = gitutil.LogCmd(commit_range, reverse=True, count=count,
  340. git_dir=git_dir)
  341. stdout = command.RunPipe([params], capture=True).stdout
  342. ps = PatchStream(series, is_log=True)
  343. for line in stdout.splitlines():
  344. ps.ProcessLine(line)
  345. ps.Finalize()
  346. return series
  347. def GetMetaData(start, count):
  348. """Reads out patch series metadata from the commits
  349. This does a 'git log' on the relevant commits and pulls out the tags we
  350. are interested in.
  351. Args:
  352. start: Commit to start from: 0=HEAD, 1=next one, etc.
  353. count: Number of commits to list
  354. """
  355. return GetMetaDataForList('HEAD~%d' % start, None, count)
  356. def FixPatch(backup_dir, fname, series, commit):
  357. """Fix up a patch file, by adding/removing as required.
  358. We remove our tags from the patch file, insert changes lists, etc.
  359. The patch file is processed in place, and overwritten.
  360. A backup file is put into backup_dir (if not None).
  361. Args:
  362. fname: Filename to patch file to process
  363. series: Series information about this patch set
  364. commit: Commit object for this patch file
  365. Return:
  366. A list of errors, or [] if all ok.
  367. """
  368. handle, tmpname = tempfile.mkstemp()
  369. outfd = os.fdopen(handle, 'w')
  370. infd = open(fname, 'r')
  371. ps = PatchStream(series)
  372. ps.commit = commit
  373. ps.ProcessStream(infd, outfd)
  374. infd.close()
  375. outfd.close()
  376. # Create a backup file if required
  377. if backup_dir:
  378. shutil.copy(fname, os.path.join(backup_dir, os.path.basename(fname)))
  379. shutil.move(tmpname, fname)
  380. return ps.warn
  381. def FixPatches(series, fnames):
  382. """Fix up a list of patches identified by filenames
  383. The patch files are processed in place, and overwritten.
  384. Args:
  385. series: The series object
  386. fnames: List of patch files to process
  387. """
  388. # Current workflow creates patches, so we shouldn't need a backup
  389. backup_dir = None #tempfile.mkdtemp('clean-patch')
  390. count = 0
  391. for fname in fnames:
  392. commit = series.commits[count]
  393. commit.patch = fname
  394. result = FixPatch(backup_dir, fname, series, commit)
  395. if result:
  396. print '%d warnings for %s:' % (len(result), fname)
  397. for warn in result:
  398. print '\t', warn
  399. print
  400. count += 1
  401. print 'Cleaned %d patches' % count
  402. return series
  403. def InsertCoverLetter(fname, series, count):
  404. """Inserts a cover letter with the required info into patch 0
  405. Args:
  406. fname: Input / output filename of the cover letter file
  407. series: Series object
  408. count: Number of patches in the series
  409. """
  410. fd = open(fname, 'r')
  411. lines = fd.readlines()
  412. fd.close()
  413. fd = open(fname, 'w')
  414. text = series.cover
  415. prefix = series.GetPatchPrefix()
  416. for line in lines:
  417. if line.startswith('Subject:'):
  418. # if more than 10 or 100 patches, it should say 00/xx, 000/xxx, etc
  419. zero_repeat = int(math.log10(count)) + 1
  420. zero = '0' * zero_repeat
  421. line = 'Subject: [%s %s/%d] %s\n' % (prefix, zero, count, text[0])
  422. # Insert our cover letter
  423. elif line.startswith('*** BLURB HERE ***'):
  424. # First the blurb test
  425. line = '\n'.join(text[1:]) + '\n'
  426. if series.get('notes'):
  427. line += '\n'.join(series.notes) + '\n'
  428. # Now the change list
  429. out = series.MakeChangeLog(None)
  430. line += '\n' + '\n'.join(out)
  431. fd.write(line)
  432. fd.close()