patchstream.py 17 KB

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