patman: Cache the CC list from MakeCcFile() for use in ShowActions()
[oweals/u-boot.git] / tools / patman / series.py
1 # Copyright (c) 2011 The Chromium OS Authors.
2 #
3 # See file CREDITS for list of people who contributed to this
4 # project.
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; either version 2 of
9 # the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
19 # MA 02111-1307 USA
20 #
21
22 import os
23
24 import gitutil
25 import terminal
26
27 # Series-xxx tags that we understand
28 valid_series = ['to', 'cc', 'version', 'changes', 'prefix', 'notes', 'name'];
29
30 class Series(dict):
31     """Holds information about a patch series, including all tags.
32
33     Vars:
34         cc: List of aliases/emails to Cc all patches to
35         commits: List of Commit objects, one for each patch
36         cover: List of lines in the cover letter
37         notes: List of lines in the notes
38         changes: (dict) List of changes for each version, The key is
39             the integer version number
40     """
41     def __init__(self):
42         self.cc = []
43         self.to = []
44         self.commits = []
45         self.cover = None
46         self.notes = []
47         self.changes = {}
48
49         # Written in MakeCcFile()
50         #  key: name of patch file
51         #  value: list of email addresses
52         self._generated_cc = {}
53
54     # These make us more like a dictionary
55     def __setattr__(self, name, value):
56         self[name] = value
57
58     def __getattr__(self, name):
59         return self[name]
60
61     def AddTag(self, commit, line, name, value):
62         """Add a new Series-xxx tag along with its value.
63
64         Args:
65             line: Source line containing tag (useful for debug/error messages)
66             name: Tag name (part after 'Series-')
67             value: Tag value (part after 'Series-xxx: ')
68         """
69         # If we already have it, then add to our list
70         if name in self:
71             values = value.split(',')
72             values = [str.strip() for str in values]
73             if type(self[name]) != type([]):
74                 raise ValueError("In %s: line '%s': Cannot add another value "
75                         "'%s' to series '%s'" %
76                             (commit.hash, line, values, self[name]))
77             self[name] += values
78
79         # Otherwise just set the value
80         elif name in valid_series:
81             self[name] = value
82         else:
83             raise ValueError("In %s: line '%s': Unknown 'Series-%s': valid "
84                         "options are %s" % (commit.hash, line, name,
85                             ', '.join(valid_series)))
86
87     def AddCommit(self, commit):
88         """Add a commit into our list of commits
89
90         We create a list of tags in the commit subject also.
91
92         Args:
93             commit: Commit object to add
94         """
95         commit.CheckTags()
96         self.commits.append(commit)
97
98     def ShowActions(self, args, cmd, process_tags):
99         """Show what actions we will/would perform
100
101         Args:
102             args: List of patch files we created
103             cmd: The git command we would have run
104             process_tags: Process tags as if they were aliases
105         """
106         col = terminal.Color()
107         print 'Dry run, so not doing much. But I would do this:'
108         print
109         print 'Send a total of %d patch%s with %scover letter.' % (
110                 len(args), '' if len(args) == 1 else 'es',
111                 self.get('cover') and 'a ' or 'no ')
112
113         # TODO: Colour the patches according to whether they passed checks
114         for upto in range(len(args)):
115             commit = self.commits[upto]
116             print col.Color(col.GREEN, '   %s' % args[upto])
117             cc_list = list(self._generated_cc[commit.patch])
118
119             # Skip items in To list
120             if 'to' in self:
121                 try:
122                     map(cc_list.remove, gitutil.BuildEmailList(self.to))
123                 except ValueError:
124                     pass
125
126             for email in cc_list:
127                 if email == None:
128                     email = col.Color(col.YELLOW, "<alias '%s' not found>"
129                             % tag)
130                 if email:
131                     print '      Cc: ',email
132         print
133         for item in gitutil.BuildEmailList(self.get('to', '<none>')):
134             print 'To:\t ', item
135         for item in gitutil.BuildEmailList(self.cc):
136             print 'Cc:\t ', item
137         print 'Version: ', self.get('version')
138         print 'Prefix:\t ', self.get('prefix')
139         if self.cover:
140             print 'Cover: %d lines' % len(self.cover)
141         if cmd:
142             print 'Git command: %s' % cmd
143
144     def MakeChangeLog(self, commit):
145         """Create a list of changes for each version.
146
147         Return:
148             The change log as a list of strings, one per line
149
150             Changes in v4:
151             - Jog the dial back closer to the widget
152
153             Changes in v3: None
154             Changes in v2:
155             - Fix the widget
156             - Jog the dial
157
158             etc.
159         """
160         final = []
161         need_blank = False
162         for change in sorted(self.changes, reverse=True):
163             out = []
164             for this_commit, text in self.changes[change]:
165                 if commit and this_commit != commit:
166                     continue
167                 out.append(text)
168             line = 'Changes in v%d:' % change
169             have_changes = len(out) > 0
170             if have_changes:
171                 out.insert(0, line)
172             else:
173                 out = [line + ' None']
174             if need_blank:
175                 out.insert(0, '')
176             final += out
177             need_blank = have_changes
178         if self.changes:
179             final.append('')
180         return final
181
182     def DoChecks(self):
183         """Check that each version has a change log
184
185         Print an error if something is wrong.
186         """
187         col = terminal.Color()
188         if self.get('version'):
189             changes_copy = dict(self.changes)
190             for version in range(1, int(self.version) + 1):
191                 if self.changes.get(version):
192                     del changes_copy[version]
193                 else:
194                     if version > 1:
195                         str = 'Change log missing for v%d' % version
196                         print col.Color(col.RED, str)
197             for version in changes_copy:
198                 str = 'Change log for unknown version v%d' % version
199                 print col.Color(col.RED, str)
200         elif self.changes:
201             str = 'Change log exists, but no version is set'
202             print col.Color(col.RED, str)
203
204     def MakeCcFile(self, process_tags):
205         """Make a cc file for us to use for per-commit Cc automation
206
207         Also stores in self._generated_cc to make ShowActions() faster.
208
209         Args:
210             process_tags: Process tags as if they were aliases
211         Return:
212             Filename of temp file created
213         """
214         # Look for commit tags (of the form 'xxx:' at the start of the subject)
215         fname = '/tmp/patman.%d' % os.getpid()
216         fd = open(fname, 'w')
217         for commit in self.commits:
218             list = []
219             if process_tags:
220                 list += gitutil.BuildEmailList(commit.tags)
221             list += gitutil.BuildEmailList(commit.cc_list)
222             print >>fd, commit.patch, ', '.join(list)
223             self._generated_cc[commit.patch] = list
224
225         fd.close()
226         return fname
227
228     def AddChange(self, version, commit, info):
229         """Add a new change line to a version.
230
231         This will later appear in the change log.
232
233         Args:
234             version: version number to add change list to
235             info: change line for this version
236         """
237         if not self.changes.get(version):
238             self.changes[version] = []
239         self.changes[version].append([commit, info])
240
241     def GetPatchPrefix(self):
242         """Get the patch version string
243
244         Return:
245             Patch string, like 'RFC PATCH v5' or just 'PATCH'
246         """
247         version = ''
248         if self.get('version'):
249             version = ' v%s' % self['version']
250
251         # Get patch name prefix
252         prefix = ''
253         if self.get('prefix'):
254             prefix = '%s ' % self['prefix']
255         return '%sPATCH%s' % (prefix, version)