main.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 optparse import OptionParser
  8. import os
  9. import re
  10. import sys
  11. import unittest
  12. if __name__ == "__main__":
  13. # Allow 'from patman import xxx to work'
  14. our_path = os.path.dirname(os.path.realpath(__file__))
  15. sys.path.append(os.path.join(our_path, '..'))
  16. # Our modules
  17. from patman import checkpatch
  18. from patman import command
  19. from patman import gitutil
  20. from patman import patchstream
  21. from patman import project
  22. from patman import settings
  23. from patman import terminal
  24. from patman import test
  25. parser = OptionParser()
  26. parser.add_option('-H', '--full-help', action='store_true', dest='full_help',
  27. default=False, help='Display the README file')
  28. parser.add_option('-c', '--count', dest='count', type='int',
  29. default=-1, help='Automatically create patches from top n commits')
  30. parser.add_option('-i', '--ignore-errors', action='store_true',
  31. dest='ignore_errors', default=False,
  32. help='Send patches email even if patch errors are found')
  33. parser.add_option('-m', '--no-maintainers', action='store_false',
  34. dest='add_maintainers', default=True,
  35. help="Don't cc the file maintainers automatically")
  36. parser.add_option('-l', '--limit-cc', dest='limit', type='int',
  37. default=None, help='Limit the cc list to LIMIT entries [default: %default]')
  38. parser.add_option('-n', '--dry-run', action='store_true', dest='dry_run',
  39. default=False, help="Do a dry run (create but don't email patches)")
  40. parser.add_option('-p', '--project', default=project.DetectProject(),
  41. help="Project name; affects default option values and "
  42. "aliases [default: %default]")
  43. parser.add_option('-r', '--in-reply-to', type='string', action='store',
  44. help="Message ID that this series is in reply to")
  45. parser.add_option('-s', '--start', dest='start', type='int',
  46. default=0, help='Commit to start creating patches from (0 = HEAD)')
  47. parser.add_option('-t', '--ignore-bad-tags', action='store_true',
  48. default=False, help='Ignore bad tags / aliases')
  49. parser.add_option('--test', action='store_true', dest='test',
  50. default=False, help='run tests')
  51. parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
  52. default=False, help='Verbose output of errors and warnings')
  53. parser.add_option('--cc-cmd', dest='cc_cmd', type='string', action='store',
  54. default=None, help='Output cc list for patch file (used by git)')
  55. parser.add_option('--no-check', action='store_false', dest='check_patch',
  56. default=True,
  57. help="Don't check for patch compliance")
  58. parser.add_option('--no-tags', action='store_false', dest='process_tags',
  59. default=True, help="Don't process subject tags as aliaes")
  60. parser.add_option('--smtp-server', type='str',
  61. help="Specify the SMTP server to 'git send-email'")
  62. parser.add_option('-T', '--thread', action='store_true', dest='thread',
  63. default=False, help='Create patches as a single thread')
  64. parser.usage += """
  65. Create patches from commits in a branch, check them and email them as
  66. specified by tags you place in the commits. Use -n to do a dry run first."""
  67. # Parse options twice: first to get the project and second to handle
  68. # defaults properly (which depends on project).
  69. (options, args) = parser.parse_args()
  70. settings.Setup(parser, options.project, '')
  71. (options, args) = parser.parse_args()
  72. if __name__ != "__main__":
  73. pass
  74. # Run our meagre tests
  75. elif options.test:
  76. import doctest
  77. from patman import func_test
  78. sys.argv = [sys.argv[0]]
  79. result = unittest.TestResult()
  80. for module in (test.TestPatch, func_test.TestFunctional):
  81. suite = unittest.TestLoader().loadTestsFromTestCase(module)
  82. suite.run(result)
  83. for module in ['gitutil', 'settings', 'terminal']:
  84. suite = doctest.DocTestSuite(module)
  85. suite.run(result)
  86. # TODO: Surely we can just 'print' result?
  87. print(result)
  88. for test, err in result.errors:
  89. print(err)
  90. for test, err in result.failures:
  91. print(err)
  92. # Called from git with a patch filename as argument
  93. # Printout a list of additional CC recipients for this patch
  94. elif options.cc_cmd:
  95. fd = open(options.cc_cmd, 'r')
  96. re_line = re.compile('(\S*) (.*)')
  97. for line in fd.readlines():
  98. match = re_line.match(line)
  99. if match and match.group(1) == args[0]:
  100. for cc in match.group(2).split('\0'):
  101. cc = cc.strip()
  102. if cc:
  103. print(cc)
  104. fd.close()
  105. elif options.full_help:
  106. pager = os.getenv('PAGER')
  107. if not pager:
  108. pager = 'more'
  109. fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
  110. 'README')
  111. command.Run(pager, fname)
  112. # Process commits, produce patches files, check them, email them
  113. else:
  114. gitutil.Setup()
  115. if options.count == -1:
  116. # Work out how many patches to send if we can
  117. options.count = gitutil.CountCommitsToBranch() - options.start
  118. col = terminal.Color()
  119. if not options.count:
  120. str = 'No commits found to process - please use -c flag'
  121. sys.exit(col.Color(col.RED, str))
  122. # Read the metadata from the commits
  123. if options.count:
  124. series = patchstream.GetMetaData(options.start, options.count)
  125. cover_fname, args = gitutil.CreatePatches(options.start, options.count,
  126. series)
  127. # Fix up the patch files to our liking, and insert the cover letter
  128. patchstream.FixPatches(series, args)
  129. if cover_fname and series.get('cover'):
  130. patchstream.InsertCoverLetter(cover_fname, series, options.count)
  131. # Do a few checks on the series
  132. series.DoChecks()
  133. # Check the patches, and run them through 'git am' just to be sure
  134. if options.check_patch:
  135. ok = checkpatch.CheckPatches(options.verbose, args)
  136. else:
  137. ok = True
  138. cc_file = series.MakeCcFile(options.process_tags, cover_fname,
  139. not options.ignore_bad_tags,
  140. options.add_maintainers, options.limit)
  141. # Email the patches out (giving the user time to check / cancel)
  142. cmd = ''
  143. its_a_go = ok or options.ignore_errors
  144. if its_a_go:
  145. cmd = gitutil.EmailPatches(series, cover_fname, args,
  146. options.dry_run, not options.ignore_bad_tags, cc_file,
  147. in_reply_to=options.in_reply_to, thread=options.thread,
  148. smtp_server=options.smtp_server)
  149. else:
  150. print(col.Color(col.RED, "Not sending emails due to errors/warnings"))
  151. # For a dry run, just show our actions as a sanity check
  152. if options.dry_run:
  153. series.ShowActions(args, cmd, options.process_tags)
  154. if not its_a_go:
  155. print(col.Color(col.RED, "Email would not be sent"))
  156. os.remove(cc_file)