main.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Copyright (c) 2011 The Chromium OS Authors.
  5. #
  6. """See README for more information"""
  7. from argparse import ArgumentParser
  8. import os
  9. import re
  10. import shutil
  11. import sys
  12. import traceback
  13. import unittest
  14. if __name__ == "__main__":
  15. # Allow 'from patman import xxx to work'
  16. our_path = os.path.dirname(os.path.realpath(__file__))
  17. sys.path.append(os.path.join(our_path, '..'))
  18. # Our modules
  19. from patman import command
  20. from patman import control
  21. from patman import gitutil
  22. from patman import project
  23. from patman import settings
  24. from patman import terminal
  25. from patman import test_util
  26. from patman import test_checkpatch
  27. epilog = '''Create patches from commits in a branch, check them and email them
  28. as specified by tags you place in the commits. Use -n to do a dry run first.'''
  29. parser = ArgumentParser(epilog=epilog)
  30. parser.add_argument('-b', '--branch', type=str,
  31. help="Branch to process (by default, the current branch)")
  32. parser.add_argument('-c', '--count', dest='count', type=int,
  33. default=-1, help='Automatically create patches from top n commits')
  34. parser.add_argument('-e', '--end', type=int, default=0,
  35. help='Commits to skip at end of patch list')
  36. parser.add_argument('-D', '--debug', action='store_true',
  37. help='Enabling debugging (provides a full traceback on error)')
  38. parser.add_argument('-p', '--project', default=project.DetectProject(),
  39. help="Project name; affects default option values and "
  40. "aliases [default: %(default)s]")
  41. parser.add_argument('-P', '--patchwork-url',
  42. default='https://patchwork.ozlabs.org',
  43. help='URL of patchwork server [default: %(default)s]')
  44. parser.add_argument('-s', '--start', dest='start', type=int,
  45. default=0, help='Commit to start creating patches from (0 = HEAD)')
  46. parser.add_argument('-v', '--verbose', action='store_true', dest='verbose',
  47. default=False, help='Verbose output of errors and warnings')
  48. parser.add_argument('-H', '--full-help', action='store_true', dest='full_help',
  49. default=False, help='Display the README file')
  50. subparsers = parser.add_subparsers(dest='cmd')
  51. send = subparsers.add_parser('send')
  52. send.add_argument('-i', '--ignore-errors', action='store_true',
  53. dest='ignore_errors', default=False,
  54. help='Send patches email even if patch errors are found')
  55. send.add_argument('-l', '--limit-cc', dest='limit', type=int, default=None,
  56. help='Limit the cc list to LIMIT entries [default: %(default)s]')
  57. send.add_argument('-m', '--no-maintainers', action='store_false',
  58. dest='add_maintainers', default=True,
  59. help="Don't cc the file maintainers automatically")
  60. send.add_argument('-n', '--dry-run', action='store_true', dest='dry_run',
  61. default=False, help="Do a dry run (create but don't email patches)")
  62. send.add_argument('-r', '--in-reply-to', type=str, action='store',
  63. help="Message ID that this series is in reply to")
  64. send.add_argument('-t', '--ignore-bad-tags', action='store_true',
  65. default=False,
  66. help='Ignore bad tags / aliases (default=warn)')
  67. send.add_argument('-T', '--thread', action='store_true', dest='thread',
  68. default=False, help='Create patches as a single thread')
  69. send.add_argument('--cc-cmd', dest='cc_cmd', type=str, action='store',
  70. default=None, help='Output cc list for patch file (used by git)')
  71. send.add_argument('--no-binary', action='store_true', dest='ignore_binary',
  72. default=False,
  73. help="Do not output contents of changes in binary files")
  74. send.add_argument('--no-check', action='store_false', dest='check_patch',
  75. default=True,
  76. help="Don't check for patch compliance")
  77. send.add_argument('--no-tags', action='store_false', dest='process_tags',
  78. default=True, help="Don't process subject tags as aliases")
  79. send.add_argument('--no-signoff', action='store_false', dest='add_signoff',
  80. default=True, help="Don't add Signed-off-by to patches")
  81. send.add_argument('--smtp-server', type=str,
  82. help="Specify the SMTP server to 'git send-email'")
  83. send.add_argument('patchfiles', nargs='*')
  84. test_parser = subparsers.add_parser('test', help='Run tests')
  85. test_parser.add_argument('testname', type=str, default=None, nargs='?',
  86. help="Specify the test to run")
  87. status = subparsers.add_parser('status',
  88. help='Check status of patches in patchwork')
  89. status.add_argument('-C', '--show-comments', action='store_true',
  90. help='Show comments from each patch')
  91. status.add_argument('-d', '--dest-branch', type=str,
  92. help='Name of branch to create with collected responses')
  93. status.add_argument('-f', '--force', action='store_true',
  94. help='Force overwriting an existing branch')
  95. # Parse options twice: first to get the project and second to handle
  96. # defaults properly (which depends on project)
  97. # Use parse_known_args() in case 'cmd' is omitted
  98. argv = sys.argv[1:]
  99. args, rest = parser.parse_known_args(argv)
  100. if hasattr(args, 'project'):
  101. settings.Setup(gitutil, parser, args.project, '')
  102. args, rest = parser.parse_known_args(argv)
  103. # If we have a command, it is safe to parse all arguments
  104. if args.cmd:
  105. args = parser.parse_args(argv)
  106. else:
  107. # No command, so insert it after the known arguments and before the ones
  108. # that presumably relate to the 'send' subcommand
  109. nargs = len(rest)
  110. argv = argv[:-nargs] + ['send'] + rest
  111. args = parser.parse_args(argv)
  112. if __name__ != "__main__":
  113. pass
  114. if not args.debug:
  115. sys.tracebacklimit = 0
  116. # Run our meagre tests
  117. if args.cmd == 'test':
  118. import doctest
  119. from patman import func_test
  120. sys.argv = [sys.argv[0]]
  121. result = unittest.TestResult()
  122. suite = unittest.TestSuite()
  123. loader = unittest.TestLoader()
  124. for module in (test_checkpatch.TestPatch, func_test.TestFunctional):
  125. if args.testname:
  126. try:
  127. suite.addTests(loader.loadTestsFromName(args.testname, module))
  128. except AttributeError:
  129. continue
  130. else:
  131. suite.addTests(loader.loadTestsFromTestCase(module))
  132. suite.run(result)
  133. for module in ['gitutil', 'settings', 'terminal']:
  134. suite = doctest.DocTestSuite(module)
  135. suite.run(result)
  136. sys.exit(test_util.ReportResult('patman', args.testname, result))
  137. # Process commits, produce patches files, check them, email them
  138. elif args.cmd == 'send':
  139. # Called from git with a patch filename as argument
  140. # Printout a list of additional CC recipients for this patch
  141. if args.cc_cmd:
  142. fd = open(args.cc_cmd, 'r')
  143. re_line = re.compile('(\S*) (.*)')
  144. for line in fd.readlines():
  145. match = re_line.match(line)
  146. if match and match.group(1) == args.patchfiles[0]:
  147. for cc in match.group(2).split('\0'):
  148. cc = cc.strip()
  149. if cc:
  150. print(cc)
  151. fd.close()
  152. elif args.full_help:
  153. pager = os.getenv('PAGER')
  154. if not pager:
  155. pager = shutil.which('less')
  156. if not pager:
  157. pager = 'more'
  158. fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
  159. 'README')
  160. command.Run(pager, fname)
  161. else:
  162. # If we are not processing tags, no need to warning about bad ones
  163. if not args.process_tags:
  164. args.ignore_bad_tags = True
  165. control.send(args)
  166. # Check status of patches in patchwork
  167. elif args.cmd == 'status':
  168. ret_code = 0
  169. try:
  170. control.patchwork_status(args.branch, args.count, args.start, args.end,
  171. args.dest_branch, args.force,
  172. args.show_comments, args.patchwork_url)
  173. except Exception as e:
  174. terminal.Print('patman: %s: %s' % (type(e).__name__, e),
  175. colour=terminal.Color.RED)
  176. if args.debug:
  177. print()
  178. traceback.print_exc()
  179. ret_code = 1
  180. sys.exit(ret_code)