patchstream.py 18 KB

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