patchstream.py 17 KB

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