series.py 9.49 KB
Newer Older
1 2
# Copyright (c) 2011 The Chromium OS Authors.
#
3
# SPDX-License-Identifier:	GPL-2.0+
4 5
#

6 7
from __future__ import print_function

8
import itertools
9 10
import os

11
import get_maintainer
12 13 14 15
import gitutil
import terminal

# Series-xxx tags that we understand
16
valid_series = ['to', 'cc', 'version', 'changes', 'prefix', 'notes', 'name',
17
                'cover_cc', 'process_log']
18 19 20 21 22 23 24 25 26 27 28

class Series(dict):
    """Holds information about a patch series, including all tags.

    Vars:
        cc: List of aliases/emails to Cc all patches to
        commits: List of Commit objects, one for each patch
        cover: List of lines in the cover letter
        notes: List of lines in the notes
        changes: (dict) List of changes for each version, The key is
            the integer version number
29
        allow_overwrite: Allow tags to overwrite an existing tag
30 31 32 33
    """
    def __init__(self):
        self.cc = []
        self.to = []
34
        self.cover_cc = []
35 36 37 38
        self.commits = []
        self.cover = None
        self.notes = []
        self.changes = {}
39
        self.allow_overwrite = False
40

41 42 43 44 45
        # Written in MakeCcFile()
        #  key: name of patch file
        #  value: list of email addresses
        self._generated_cc = {}

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    # These make us more like a dictionary
    def __setattr__(self, name, value):
        self[name] = value

    def __getattr__(self, name):
        return self[name]

    def AddTag(self, commit, line, name, value):
        """Add a new Series-xxx tag along with its value.

        Args:
            line: Source line containing tag (useful for debug/error messages)
            name: Tag name (part after 'Series-')
            value: Tag value (part after 'Series-xxx: ')
        """
        # If we already have it, then add to our list
62
        name = name.replace('-', '_')
63
        if name in self and not self.allow_overwrite:
64 65 66 67 68 69 70 71 72 73
            values = value.split(',')
            values = [str.strip() for str in values]
            if type(self[name]) != type([]):
                raise ValueError("In %s: line '%s': Cannot add another value "
                        "'%s' to series '%s'" %
                            (commit.hash, line, values, self[name]))
            self[name] += values

        # Otherwise just set the value
        elif name in valid_series:
74 75 76 77
            if name=="notes":
                self[name] = [value]
            else:
                self[name] = value
78 79
        else:
            raise ValueError("In %s: line '%s': Unknown 'Series-%s': valid "
80
                        "options are %s" % (commit.hash, line, name,
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
                            ', '.join(valid_series)))

    def AddCommit(self, commit):
        """Add a commit into our list of commits

        We create a list of tags in the commit subject also.

        Args:
            commit: Commit object to add
        """
        commit.CheckTags()
        self.commits.append(commit)

    def ShowActions(self, args, cmd, process_tags):
        """Show what actions we will/would perform

        Args:
            args: List of patch files we created
            cmd: The git command we would have run
            process_tags: Process tags as if they were aliases
        """
102 103 104
        to_set = set(gitutil.BuildEmailList(self.to));
        cc_set = set(gitutil.BuildEmailList(self.cc));

105
        col = terminal.Color()
106 107 108
        print('Dry run, so not doing much. But I would do this:')
        print()
        print('Send a total of %d patch%s with %scover letter.' % (
109
                len(args), '' if len(args) == 1 else 'es',
110
                self.get('cover') and 'a ' or 'no '))
111 112 113 114

        # TODO: Colour the patches according to whether they passed checks
        for upto in range(len(args)):
            commit = self.commits[upto]
115
            print(col.Color(col.GREEN, '   %s' % args[upto]))
116
            cc_list = list(self._generated_cc[commit.patch])
117
            for email in set(cc_list) - to_set - cc_set:
118 119 120 121
                if email == None:
                    email = col.Color(col.YELLOW, "<alias '%s' not found>"
                            % tag)
                if email:
122
                    print('      Cc: ', email)
123
        print
124
        for item in to_set:
125
            print('To:\t ', item)
126
        for item in cc_set - to_set:
127 128 129
            print('Cc:\t ', item)
        print('Version: ', self.get('version'))
        print('Prefix:\t ', self.get('prefix'))
130
        if self.cover:
131
            print('Cover: %d lines' % len(self.cover))
132 133
            cover_cc = gitutil.BuildEmailList(self.get('cover_cc', ''))
            all_ccs = itertools.chain(cover_cc, *self._generated_cc.values())
134
            for email in set(all_ccs) - to_set - cc_set:
135
                    print('      Cc: ', email)
136
        if cmd:
137
            print('Git command: %s' % cmd)
138 139 140 141 142 143 144

    def MakeChangeLog(self, commit):
        """Create a list of changes for each version.

        Return:
            The change log as a list of strings, one per line

145
            Changes in v4:
146 147
            - Jog the dial back closer to the widget

148 149
            Changes in v3: None
            Changes in v2:
150 151 152 153 154 155
            - Fix the widget
            - Jog the dial

            etc.
        """
        final = []
156 157
        process_it = self.get('process_log', '').split(',')
        process_it = [item.strip() for item in process_it]
158
        need_blank = False
159
        for change in sorted(self.changes, reverse=True):
160 161 162 163
            out = []
            for this_commit, text in self.changes[change]:
                if commit and this_commit != commit:
                    continue
164 165
                if 'uniq' not in process_it or text not in out:
                    out.append(text)
166 167
            line = 'Changes in v%d:' % change
            have_changes = len(out) > 0
168 169
            if 'sort' in process_it:
                out = sorted(out)
170 171 172 173 174 175 176 177
            if have_changes:
                out.insert(0, line)
            else:
                out = [line + ' None']
            if need_blank:
                out.insert(0, '')
            final += out
            need_blank = have_changes
178 179 180 181 182 183 184 185 186 187 188 189
        if self.changes:
            final.append('')
        return final

    def DoChecks(self):
        """Check that each version has a change log

        Print an error if something is wrong.
        """
        col = terminal.Color()
        if self.get('version'):
            changes_copy = dict(self.changes)
190
            for version in range(1, int(self.version) + 1):
191 192 193
                if self.changes.get(version):
                    del changes_copy[version]
                else:
194 195
                    if version > 1:
                        str = 'Change log missing for v%d' % version
196
                        print(col.Color(col.RED, str))
197 198
            for version in changes_copy:
                str = 'Change log for unknown version v%d' % version
199
                print(col.Color(col.RED, str))
200 201
        elif self.changes:
            str = 'Change log exists, but no version is set'
202
            print(col.Color(col.RED, str))
203

204 205
    def MakeCcFile(self, process_tags, cover_fname, raise_on_error,
                   add_maintainers):
206 207
        """Make a cc file for us to use for per-commit Cc automation

208 209
        Also stores in self._generated_cc to make ShowActions() faster.

210 211
        Args:
            process_tags: Process tags as if they were aliases
212
            cover_fname: If non-None the name of the cover letter.
213 214
            raise_on_error: True to raise an error when an alias fails to match,
                False to just print a message.
215
            add_maintainers: Call the get_maintainers to CC maintainers
216 217 218 219 220 221
        Return:
            Filename of temp file created
        """
        # Look for commit tags (of the form 'xxx:' at the start of the subject)
        fname = '/tmp/patman.%d' % os.getpid()
        fd = open(fname, 'w')
222
        all_ccs = []
223 224 225
        for commit in self.commits:
            list = []
            if process_tags:
226 227 228 229
                list += gitutil.BuildEmailList(commit.tags,
                                               raise_on_error=raise_on_error)
            list += gitutil.BuildEmailList(commit.cc_list,
                                           raise_on_error=raise_on_error)
Paul Burton's avatar
Paul Burton committed
230
            if add_maintainers:
231
                list += get_maintainer.GetMaintainer(commit.patch)
232
            all_ccs += list
233
            print(commit.patch, ', '.join(set(list)), file=fd)
234
            self._generated_cc[commit.patch] = list
235

236
        if cover_fname:
237
            cover_cc = gitutil.BuildEmailList(self.get('cover_cc', ''))
238
            print(cover_fname, ', '.join(set(cover_cc + all_ccs)), file=fd)
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
        fd.close()
        return fname

    def AddChange(self, version, commit, info):
        """Add a new change line to a version.

        This will later appear in the change log.

        Args:
            version: version number to add change list to
            info: change line for this version
        """
        if not self.changes.get(version):
            self.changes[version] = []
        self.changes[version].append([commit, info])

    def GetPatchPrefix(self):
        """Get the patch version string

        Return:
            Patch string, like 'RFC PATCH v5' or just 'PATCH'
        """
262 263
        git_prefix = gitutil.GetDefaultSubjectPrefix()
        if git_prefix:
Paul Burton's avatar
Paul Burton committed
264
            git_prefix = '%s][' % git_prefix
265 266 267
        else:
            git_prefix = ''

268 269 270 271 272 273 274 275
        version = ''
        if self.get('version'):
            version = ' v%s' % self['version']

        # Get patch name prefix
        prefix = ''
        if self.get('prefix'):
            prefix = '%s ' % self['prefix']
276
        return '%s%sPATCH%s' % (git_prefix, prefix, version)