series.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2011 The Chromium OS Authors.
  3. #
  4. from __future__ import print_function
  5. import collections
  6. import concurrent.futures
  7. import itertools
  8. import os
  9. import sys
  10. import time
  11. from patman import get_maintainer
  12. from patman import gitutil
  13. from patman import settings
  14. from u_boot_pylib import terminal
  15. from u_boot_pylib import tools
  16. # Series-xxx tags that we understand
  17. valid_series = ['to', 'cc', 'version', 'changes', 'prefix', 'notes', 'name',
  18. 'cover_cc', 'process_log', 'links', 'patchwork_url', 'postfix']
  19. class Series(dict):
  20. """Holds information about a patch series, including all tags.
  21. Vars:
  22. cc: List of aliases/emails to Cc all patches to
  23. commits: List of Commit objects, one for each patch
  24. cover: List of lines in the cover letter
  25. notes: List of lines in the notes
  26. changes: (dict) List of changes for each version, The key is
  27. the integer version number
  28. allow_overwrite: Allow tags to overwrite an existing tag
  29. """
  30. def __init__(self):
  31. self.cc = []
  32. self.to = []
  33. self.cover_cc = []
  34. self.commits = []
  35. self.cover = None
  36. self.notes = []
  37. self.changes = {}
  38. self.allow_overwrite = False
  39. # Written in MakeCcFile()
  40. # key: name of patch file
  41. # value: list of email addresses
  42. self._generated_cc = {}
  43. # These make us more like a dictionary
  44. def __setattr__(self, name, value):
  45. self[name] = value
  46. def __getattr__(self, name):
  47. return self[name]
  48. def AddTag(self, commit, line, name, value):
  49. """Add a new Series-xxx tag along with its value.
  50. Args:
  51. line: Source line containing tag (useful for debug/error messages)
  52. name: Tag name (part after 'Series-')
  53. value: Tag value (part after 'Series-xxx: ')
  54. Returns:
  55. String warning if something went wrong, else None
  56. """
  57. # If we already have it, then add to our list
  58. name = name.replace('-', '_')
  59. if name in self and not self.allow_overwrite:
  60. values = value.split(',')
  61. values = [str.strip() for str in values]
  62. if type(self[name]) != type([]):
  63. raise ValueError("In %s: line '%s': Cannot add another value "
  64. "'%s' to series '%s'" %
  65. (commit.hash, line, values, self[name]))
  66. self[name] += values
  67. # Otherwise just set the value
  68. elif name in valid_series:
  69. if name=="notes":
  70. self[name] = [value]
  71. else:
  72. self[name] = value
  73. else:
  74. return ("In %s: line '%s': Unknown 'Series-%s': valid "
  75. "options are %s" % (commit.hash, line, name,
  76. ', '.join(valid_series)))
  77. return None
  78. def AddCommit(self, commit):
  79. """Add a commit into our list of commits
  80. We create a list of tags in the commit subject also.
  81. Args:
  82. commit: Commit object to add
  83. """
  84. commit.check_tags()
  85. self.commits.append(commit)
  86. def ShowActions(self, args, cmd, process_tags):
  87. """Show what actions we will/would perform
  88. Args:
  89. args: List of patch files we created
  90. cmd: The git command we would have run
  91. process_tags: Process tags as if they were aliases
  92. """
  93. to_set = set(gitutil.build_email_list(self.to));
  94. cc_set = set(gitutil.build_email_list(self.cc));
  95. col = terminal.Color()
  96. print('Dry run, so not doing much. But I would do this:')
  97. print()
  98. print('Send a total of %d patch%s with %scover letter.' % (
  99. len(args), '' if len(args) == 1 else 'es',
  100. self.get('cover') and 'a ' or 'no '))
  101. # TODO: Colour the patches according to whether they passed checks
  102. for upto in range(len(args)):
  103. commit = self.commits[upto]
  104. print(col.build(col.GREEN, ' %s' % args[upto]))
  105. cc_list = list(self._generated_cc[commit.patch])
  106. for email in sorted(set(cc_list) - to_set - cc_set):
  107. if email == None:
  108. email = col.build(col.YELLOW, '<alias not found>')
  109. if email:
  110. print(' Cc: ', email)
  111. print
  112. for item in sorted(to_set):
  113. print('To:\t ', item)
  114. for item in sorted(cc_set - to_set):
  115. print('Cc:\t ', item)
  116. print('Version: ', self.get('version'))
  117. print('Prefix:\t ', self.get('prefix'))
  118. print('Postfix:\t ', self.get('postfix'))
  119. if self.cover:
  120. print('Cover: %d lines' % len(self.cover))
  121. cover_cc = gitutil.build_email_list(self.get('cover_cc', ''))
  122. all_ccs = itertools.chain(cover_cc, *self._generated_cc.values())
  123. for email in sorted(set(all_ccs) - to_set - cc_set):
  124. print(' Cc: ', email)
  125. if cmd:
  126. print('Git command: %s' % cmd)
  127. def MakeChangeLog(self, commit):
  128. """Create a list of changes for each version.
  129. Return:
  130. The change log as a list of strings, one per line
  131. Changes in v4:
  132. - Jog the dial back closer to the widget
  133. Changes in v2:
  134. - Fix the widget
  135. - Jog the dial
  136. If there are no new changes in a patch, a note will be added
  137. (no changes since v2)
  138. Changes in v2:
  139. - Fix the widget
  140. - Jog the dial
  141. """
  142. # Collect changes from the series and this commit
  143. changes = collections.defaultdict(list)
  144. for version, changelist in self.changes.items():
  145. changes[version] += changelist
  146. if commit:
  147. for version, changelist in commit.changes.items():
  148. changes[version] += [[commit, text] for text in changelist]
  149. versions = sorted(changes, reverse=True)
  150. newest_version = 1
  151. if 'version' in self:
  152. newest_version = max(newest_version, int(self.version))
  153. if versions:
  154. newest_version = max(newest_version, versions[0])
  155. final = []
  156. process_it = self.get('process_log', '').split(',')
  157. process_it = [item.strip() for item in process_it]
  158. need_blank = False
  159. for version in versions:
  160. out = []
  161. for this_commit, text in changes[version]:
  162. if commit and this_commit != commit:
  163. continue
  164. if 'uniq' not in process_it or text not in out:
  165. out.append(text)
  166. if 'sort' in process_it:
  167. out = sorted(out)
  168. have_changes = len(out) > 0
  169. line = 'Changes in v%d:' % version
  170. if have_changes:
  171. out.insert(0, line)
  172. if version < newest_version and len(final) == 0:
  173. out.insert(0, '')
  174. out.insert(0, '(no changes since v%d)' % version)
  175. newest_version = 0
  176. # Only add a new line if we output something
  177. if need_blank:
  178. out.insert(0, '')
  179. need_blank = False
  180. final += out
  181. need_blank = need_blank or have_changes
  182. if len(final) > 0:
  183. final.append('')
  184. elif newest_version != 1:
  185. final = ['(no changes since v1)', '']
  186. return final
  187. def DoChecks(self):
  188. """Check that each version has a change log
  189. Print an error if something is wrong.
  190. """
  191. col = terminal.Color()
  192. if self.get('version'):
  193. changes_copy = dict(self.changes)
  194. for version in range(1, int(self.version) + 1):
  195. if self.changes.get(version):
  196. del changes_copy[version]
  197. else:
  198. if version > 1:
  199. str = 'Change log missing for v%d' % version
  200. print(col.build(col.RED, str))
  201. for version in changes_copy:
  202. str = 'Change log for unknown version v%d' % version
  203. print(col.build(col.RED, str))
  204. elif self.changes:
  205. str = 'Change log exists, but no version is set'
  206. print(col.build(col.RED, str))
  207. def GetCcForCommit(self, commit, process_tags, warn_on_error,
  208. add_maintainers, limit, get_maintainer_script,
  209. all_skips):
  210. """Get the email CCs to use with a particular commit
  211. Uses subject tags and get_maintainers.pl script to find people to cc
  212. on a patch
  213. Args:
  214. commit (Commit): Commit to process
  215. process_tags (bool): Process tags as if they were aliases
  216. warn_on_error (bool): True to print a warning when an alias fails to
  217. match, False to ignore it.
  218. add_maintainers (bool or list of str): Either:
  219. True/False to call the get_maintainers to CC maintainers
  220. List of maintainers to include (for testing)
  221. limit (int): Limit the length of the Cc list (None if no limit)
  222. get_maintainer_script (str): The file name of the get_maintainer.pl
  223. script (or compatible).
  224. all_skips (set of str): Updated to include the set of bouncing email
  225. addresses that were dropped from the output. This is essentially
  226. a return value from this function.
  227. Returns:
  228. list of str: List of email addresses to cc
  229. """
  230. cc = []
  231. if process_tags:
  232. cc += gitutil.build_email_list(commit.tags,
  233. warn_on_error=warn_on_error)
  234. cc += gitutil.build_email_list(commit.cc_list,
  235. warn_on_error=warn_on_error)
  236. if type(add_maintainers) == type(cc):
  237. cc += add_maintainers
  238. elif add_maintainers:
  239. cc += get_maintainer.get_maintainer(get_maintainer_script,
  240. commit.patch)
  241. all_skips |= set(cc) & set(settings.bounces)
  242. cc = list(set(cc) - set(settings.bounces))
  243. if limit is not None:
  244. cc = cc[:limit]
  245. return cc
  246. def MakeCcFile(self, process_tags, cover_fname, warn_on_error,
  247. add_maintainers, limit, get_maintainer_script):
  248. """Make a cc file for us to use for per-commit Cc automation
  249. Also stores in self._generated_cc to make ShowActions() faster.
  250. Args:
  251. process_tags (bool): Process tags as if they were aliases
  252. cover_fname (str): If non-None the name of the cover letter.
  253. warn_on_error (bool): True to print a warning when an alias fails to
  254. match, False to ignore it.
  255. add_maintainers (bool or list of str): Either:
  256. True/False to call the get_maintainers to CC maintainers
  257. List of maintainers to include (for testing)
  258. limit (int): Limit the length of the Cc list (None if no limit)
  259. get_maintainer_script (str): The file name of the get_maintainer.pl
  260. script (or compatible).
  261. Return:
  262. Filename of temp file created
  263. """
  264. col = terminal.Color()
  265. # Look for commit tags (of the form 'xxx:' at the start of the subject)
  266. fname = '/tmp/patman.%d' % os.getpid()
  267. fd = open(fname, 'w', encoding='utf-8')
  268. all_ccs = []
  269. all_skips = set()
  270. with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
  271. for i, commit in enumerate(self.commits):
  272. commit.seq = i
  273. commit.future = executor.submit(
  274. self.GetCcForCommit, commit, process_tags, warn_on_error,
  275. add_maintainers, limit, get_maintainer_script, all_skips)
  276. # Show progress any commits that are taking forever
  277. lastlen = 0
  278. while True:
  279. left = [commit for commit in self.commits
  280. if not commit.future.done()]
  281. if not left:
  282. break
  283. names = ', '.join(f'{c.seq + 1}:{c.subject}'
  284. for c in left[:2])
  285. out = f'\r{len(left)} remaining: {names}'[:79]
  286. spaces = ' ' * (lastlen - len(out))
  287. if lastlen: # Don't print anything the first time
  288. print(out, spaces, end='')
  289. sys.stdout.flush()
  290. lastlen = len(out)
  291. time.sleep(.25)
  292. print(f'\rdone{" " * lastlen}\r', end='')
  293. print('Cc processing complete')
  294. for commit in self.commits:
  295. cc = commit.future.result()
  296. all_ccs += cc
  297. print(commit.patch, '\0'.join(sorted(set(cc))), file=fd)
  298. self._generated_cc[commit.patch] = cc
  299. for x in sorted(all_skips):
  300. print(col.build(col.YELLOW, f'Skipping "{x}"'))
  301. if cover_fname:
  302. cover_cc = gitutil.build_email_list(self.get('cover_cc', ''))
  303. cover_cc = list(set(cover_cc + all_ccs))
  304. if limit is not None:
  305. cover_cc = cover_cc[:limit]
  306. cc_list = '\0'.join([x for x in sorted(cover_cc)])
  307. print(cover_fname, cc_list, file=fd)
  308. fd.close()
  309. return fname
  310. def AddChange(self, version, commit, info):
  311. """Add a new change line to a version.
  312. This will later appear in the change log.
  313. Args:
  314. version: version number to add change list to
  315. info: change line for this version
  316. """
  317. if not self.changes.get(version):
  318. self.changes[version] = []
  319. self.changes[version].append([commit, info])
  320. def GetPatchPrefix(self):
  321. """Get the patch version string
  322. Return:
  323. Patch string, like 'RFC PATCH v5' or just 'PATCH'
  324. """
  325. git_prefix = gitutil.get_default_subject_prefix()
  326. if git_prefix:
  327. git_prefix = '%s][' % git_prefix
  328. else:
  329. git_prefix = ''
  330. version = ''
  331. if self.get('version'):
  332. version = ' v%s' % self['version']
  333. # Get patch name prefix
  334. prefix = ''
  335. if self.get('prefix'):
  336. prefix = '%s ' % self['prefix']
  337. postfix = ''
  338. if self.get('postfix'):
  339. postfix = ' %s' % self['postfix']
  340. return '%s%sPATCH%s%s' % (git_prefix, prefix, postfix, version)