main.py 7.7 KB

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