patman.py 6.34 KB
Newer Older
1
#!/usr/bin/env python
2 3 4
#
# Copyright (c) 2011 The Chromium OS Authors.
#
5
# SPDX-License-Identifier:	GPL-2.0+
6 7 8 9 10 11 12 13 14 15 16
#

"""See README for more information"""

from optparse import OptionParser
import os
import re
import sys
import unittest

# Our modules
17 18 19 20 21 22 23 24 25 26 27 28
try:
    from patman import checkpatch, command, gitutil, patchstream, \
        project, settings, terminal, test
except ImportError:
    import checkpatch
    import command
    import gitutil
    import patchstream
    import project
    import settings
    import terminal
    import test
29 30 31 32 33 34 35 36 37 38


parser = OptionParser()
parser.add_option('-H', '--full-help', action='store_true', dest='full_help',
       default=False, help='Display the README file')
parser.add_option('-c', '--count', dest='count', type='int',
       default=-1, help='Automatically create patches from top n commits')
parser.add_option('-i', '--ignore-errors', action='store_true',
       dest='ignore_errors', default=False,
       help='Send patches email even if patch errors are found')
39 40 41
parser.add_option('-m', '--no-maintainers', action='store_false',
       dest='add_maintainers', default=True,
       help="Don't cc the file maintainers automatically")
42
parser.add_option('-n', '--dry-run', action='store_true', dest='dry_run',
43
       default=False, help="Do a dry run (create but don't email patches)")
44 45 46
parser.add_option('-p', '--project', default=project.DetectProject(),
                  help="Project name; affects default option values and "
                  "aliases [default: %default]")
47 48
parser.add_option('-r', '--in-reply-to', type='string', action='store',
                  help="Message ID that this series is in reply to")
49 50
parser.add_option('-s', '--start', dest='start', type='int',
       default=0, help='Commit to start creating patches from (0 = HEAD)')
51 52 53
parser.add_option('-t', '--ignore-bad-tags', action='store_true',
                  default=False, help='Ignore bad tags / aliases')
parser.add_option('--test', action='store_true', dest='test',
54 55 56 57 58
                  default=False, help='run tests')
parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
       default=False, help='Verbose output of errors and warnings')
parser.add_option('--cc-cmd', dest='cc_cmd', type='string', action='store',
       default=None, help='Output cc list for patch file (used by git)')
59 60 61
parser.add_option('--no-check', action='store_false', dest='check_patch',
                  default=True,
                  help="Don't check for patch compliance")
62 63
parser.add_option('--no-tags', action='store_false', dest='process_tags',
                  default=True, help="Don't process subject tags as aliaes")
64 65
parser.add_option('-T', '--thread', action='store_true', dest='thread',
                  default=False, help='Create patches as a single thread')
66

67
parser.usage += """
68 69

Create patches from commits in a branch, check them and email them as
70
specified by tags you place in the commits. Use -n to do a dry run first."""
71

72

73 74 75 76
# Parse options twice: first to get the project and second to handle
# defaults properly (which depends on project).
(options, args) = parser.parse_args()
settings.Setup(parser, options.project, '')
77 78
(options, args) = parser.parse_args()

79 80 81
if __name__ != "__main__":
    pass

82
# Run our meagre tests
83
elif options.test:
84 85 86 87 88 89 90
    import doctest

    sys.argv = [sys.argv[0]]
    suite = unittest.TestLoader().loadTestsFromTestCase(test.TestPatch)
    result = unittest.TestResult()
    suite.run(result)

91 92 93
    for module in ['gitutil', 'settings']:
        suite = doctest.DocTestSuite(module)
        suite.run(result)
94 95

    # TODO: Surely we can just 'print' result?
96
    print(result)
97
    for test, err in result.errors:
98
        print(err)
99
    for test, err in result.failures:
100
        print(err)
101 102 103 104 105 106 107 108 109 110 111 112

# Called from git with a patch filename as argument
# Printout a list of additional CC recipients for this patch
elif options.cc_cmd:
    fd = open(options.cc_cmd, 'r')
    re_line = re.compile('(\S*) (.*)')
    for line in fd.readlines():
        match = re_line.match(line)
        if match and match.group(1) == args[0]:
            for cc in match.group(2).split(', '):
                cc = cc.strip()
                if cc:
113
                    print(cc)
114 115 116 117 118 119
    fd.close()

elif options.full_help:
    pager = os.getenv('PAGER')
    if not pager:
        pager = 'more'
120 121
    fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
                         'README')
122 123 124 125 126 127 128 129 130 131 132 133 134
    command.Run(pager, fname)

# Process commits, produce patches files, check them, email them
else:
    gitutil.Setup()

    if options.count == -1:
        # Work out how many patches to send if we can
        options.count = gitutil.CountCommitsToBranch() - options.start

    col = terminal.Color()
    if not options.count:
        str = 'No commits found to process - please use -c flag'
135
        sys.exit(col.Color(col.RED, str))
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

    # Read the metadata from the commits
    if options.count:
        series = patchstream.GetMetaData(options.start, options.count)
        cover_fname, args = gitutil.CreatePatches(options.start, options.count,
                series)

    # Fix up the patch files to our liking, and insert the cover letter
    series = patchstream.FixPatches(series, args)
    if series and cover_fname and series.get('cover'):
        patchstream.InsertCoverLetter(cover_fname, series, options.count)

    # Do a few checks on the series
    series.DoChecks()

    # Check the patches, and run them through 'git am' just to be sure
152 153 154 155
    if options.check_patch:
        ok = checkpatch.CheckPatches(options.verbose, args)
    else:
        ok = True
156

157
    cc_file = series.MakeCcFile(options.process_tags, cover_fname,
158 159
                                not options.ignore_bad_tags,
                                options.add_maintainers)
160

161 162
    # Email the patches out (giving the user time to check / cancel)
    cmd = ''
163 164
    its_a_go = ok or options.ignore_errors
    if its_a_go:
165
        cmd = gitutil.EmailPatches(series, cover_fname, args,
166
                options.dry_run, not options.ignore_bad_tags, cc_file,
167
                in_reply_to=options.in_reply_to, thread=options.thread)
168
    else:
169
        print(col.Color(col.RED, "Not sending emails due to errors/warnings"))
170 171 172 173

    # For a dry run, just show our actions as a sanity check
    if options.dry_run:
        series.ShowActions(args, cmd, options.process_tags)
174
        if not its_a_go:
175
            print(col.Color(col.RED, "Email would not be sent"))
176 177

    os.remove(cc_file)