patchstream.py 19 KB

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