blob: 871c66aeb1d6b370577689456dc7d6e59bd90c2b [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass0d24de92012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass0d24de92012-01-14 15:12:45 +00004
Douglas Anderson833e4192019-09-27 09:23:56 -07005import datetime
Wu, Josh35ce2dc2015-04-03 10:51:17 +08006import math
Simon Glass0d24de92012-01-14 15:12:45 +00007import os
8import re
9import shutil
10import tempfile
11
Simon Glassbf776672020-04-17 18:09:04 -060012from patman import command
13from patman import commit
14from patman import gitutil
15from patman.series import Series
Simon Glass0d24de92012-01-14 15:12:45 +000016
17# Tags that we detect and remove
Douglas Anderson833e4192019-09-27 09:23:56 -070018re_remove = re.compile('^BUG=|^TEST=|^BRANCH=|^Review URL:'
Simon Glass3fefd5e2013-04-03 11:01:39 +000019 '|Reviewed-on:|Commit-\w*:')
Simon Glass0d24de92012-01-14 15:12:45 +000020
21# Lines which are allowed after a TEST= line
22re_allowed_after_test = re.compile('^Signed-off-by:')
23
Ilya Yanok05e5b732012-08-06 23:46:05 +000024# Signoffs
Simon Glass102061b2014-04-20 10:50:14 -060025re_signoff = re.compile('^Signed-off-by: *(.*)')
Ilya Yanok05e5b732012-08-06 23:46:05 +000026
Sean Anderson6949f702020-05-04 16:28:34 -040027# Cover letter tag
28re_cover = re.compile('^Cover-([a-z-]*): *(.*)')
Simon Glassfe2f8d92013-03-20 16:43:00 +000029
Simon Glass0d24de92012-01-14 15:12:45 +000030# Patch series tag
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +010031re_series_tag = re.compile('^Series-([a-z-]*): *(.*)')
32
Douglas Anderson833e4192019-09-27 09:23:56 -070033# Change-Id will be used to generate the Message-Id and then be stripped
34re_change_id = re.compile('^Change-Id: *(.*)')
35
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +010036# Commit series tag
37re_commit_tag = re.compile('^Commit-([a-z-]*): *(.*)')
Simon Glass0d24de92012-01-14 15:12:45 +000038
39# Commit tags that we want to collect and keep
Simon Glass659c89d2014-02-16 08:23:47 -070040re_tag = re.compile('^(Tested-by|Acked-by|Reviewed-by|Patch-cc): (.*)')
Simon Glass0d24de92012-01-14 15:12:45 +000041
42# The start of a new commit in the git log
Doug Anderson68618282013-03-01 11:11:07 +000043re_commit = re.compile('^commit ([0-9a-f]*)$')
Simon Glass0d24de92012-01-14 15:12:45 +000044
45# We detect these since checkpatch doesn't always do it
46re_space_before_tab = re.compile('^[+].* \t')
47
48# States we can be in - can we use range() and still have comments?
49STATE_MSG_HEADER = 0 # Still in the message header
50STATE_PATCH_SUBJECT = 1 # In patch subject (first line of log for a commit)
51STATE_PATCH_HEADER = 2 # In patch header (after the subject)
52STATE_DIFFS = 3 # In the diff part (past --- line)
53
54class PatchStream:
55 """Class for detecting/injecting tags in a patch or series of patches
56
57 We support processing the output of 'git log' to read out the tags we
58 are interested in. We can also process a patch file in order to remove
59 unwanted tags or inject additional ones. These correspond to the two
60 phases of processing.
61 """
62 def __init__(self, series, name=None, is_log=False):
63 self.skip_blank = False # True to skip a single blank line
64 self.found_test = False # Found a TEST= line
Sean Anderson6949f702020-05-04 16:28:34 -040065 self.lines_after_test = 0 # Number of lines found after TEST=
Simon Glass0d24de92012-01-14 15:12:45 +000066 self.warn = [] # List of warnings we have collected
67 self.linenum = 1 # Output line number we are up to
68 self.in_section = None # Name of start...END section we are in
69 self.notes = [] # Series notes
70 self.section = [] # The current section...END section
71 self.series = series # Info about the patch series
72 self.is_log = is_log # True if indent like git log
Sean Anderson6949f702020-05-04 16:28:34 -040073 self.in_change = None # Name of the change list we are in
74 self.change_version = 0 # Non-zero if we are in a change list
Simon Glass0d24de92012-01-14 15:12:45 +000075 self.blank_count = 0 # Number of blank lines stored up
76 self.state = STATE_MSG_HEADER # What state are we in?
Simon Glass0d24de92012-01-14 15:12:45 +000077 self.signoff = [] # Contents of signoff line
78 self.commit = None # Current commit
79
80 def AddToSeries(self, line, name, value):
81 """Add a new Series-xxx tag.
82
83 When a Series-xxx tag is detected, we come here to record it, if we
84 are scanning a 'git log'.
85
86 Args:
87 line: Source line containing tag (useful for debug/error messages)
88 name: Tag name (part after 'Series-')
89 value: Tag value (part after 'Series-xxx: ')
90 """
91 if name == 'notes':
92 self.in_section = name
93 self.skip_blank = False
94 if self.is_log:
95 self.series.AddTag(self.commit, line, name, value)
96
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +010097 def AddToCommit(self, line, name, value):
98 """Add a new Commit-xxx tag.
99
100 When a Commit-xxx tag is detected, we come here to record it.
101
102 Args:
103 line: Source line containing tag (useful for debug/error messages)
104 name: Tag name (part after 'Commit-')
105 value: Tag value (part after 'Commit-xxx: ')
106 """
107 if name == 'notes':
108 self.in_section = 'commit-' + name
109 self.skip_blank = False
110
Simon Glass0d24de92012-01-14 15:12:45 +0000111 def CloseCommit(self):
112 """Save the current commit into our commit list, and reset our state"""
113 if self.commit and self.is_log:
114 self.series.AddCommit(self.commit)
115 self.commit = None
Bin Meng0d577182016-06-26 23:24:30 -0700116 # If 'END' is missing in a 'Cover-letter' section, and that section
117 # happens to show up at the very end of the commit message, this is
118 # the chance for us to fix it up.
119 if self.in_section == 'cover' and self.is_log:
120 self.series.cover = self.section
121 self.in_section = None
122 self.skip_blank = True
123 self.section = []
Simon Glass0d24de92012-01-14 15:12:45 +0000124
Sean Anderson6949f702020-05-04 16:28:34 -0400125 def ParseVersion(self, value, line):
126 """Parse a version from a *-changes tag
127
128 Args:
129 value: Tag value (part after 'xxx-changes: '
130 line: Source line containing tag
131
132 Returns:
133 The version as an integer
134 """
135 try:
136 return int(value)
137 except ValueError as str:
138 raise ValueError("%s: Cannot decode version info '%s'" %
139 (self.commit.hash, line))
140
Simon Glass0d24de92012-01-14 15:12:45 +0000141 def ProcessLine(self, line):
142 """Process a single line of a patch file or commit log
143
144 This process a line and returns a list of lines to output. The list
145 may be empty or may contain multiple output lines.
146
147 This is where all the complicated logic is located. The class's
148 state is used to move between different states and detect things
149 properly.
150
151 We can be in one of two modes:
152 self.is_log == True: This is 'git log' mode, where most output is
153 indented by 4 characters and we are scanning for tags
154
155 self.is_log == False: This is 'patch' mode, where we already have
156 all the tags, and are processing patches to remove junk we
157 don't want, and add things we think are required.
158
159 Args:
160 line: text line to process
161
162 Returns:
163 list of output lines, or [] if nothing should be output
164 """
165 # Initially we have no output. Prepare the input line string
166 out = []
167 line = line.rstrip('\n')
Scott Wood4b89b812014-09-25 14:30:46 -0500168
169 commit_match = re_commit.match(line) if self.is_log else None
170
Simon Glass0d24de92012-01-14 15:12:45 +0000171 if self.is_log:
172 if line[:4] == ' ':
173 line = line[4:]
174
175 # Handle state transition and skipping blank lines
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +0100176 series_tag_match = re_series_tag.match(line)
Douglas Anderson833e4192019-09-27 09:23:56 -0700177 change_id_match = re_change_id.match(line)
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +0100178 commit_tag_match = re_commit_tag.match(line)
Bin Menge7df2182016-06-26 23:24:28 -0700179 cover_match = re_cover.match(line)
Simon Glass102061b2014-04-20 10:50:14 -0600180 signoff_match = re_signoff.match(line)
Simon Glass0d24de92012-01-14 15:12:45 +0000181 tag_match = None
182 if self.state == STATE_PATCH_HEADER:
183 tag_match = re_tag.match(line)
184 is_blank = not line.strip()
185 if is_blank:
186 if (self.state == STATE_MSG_HEADER
187 or self.state == STATE_PATCH_SUBJECT):
188 self.state += 1
189
190 # We don't have a subject in the text stream of patch files
191 # It has its own line with a Subject: tag
192 if not self.is_log and self.state == STATE_PATCH_SUBJECT:
193 self.state += 1
194 elif commit_match:
195 self.state = STATE_MSG_HEADER
196
Bin Meng94fbd3e2016-06-26 23:24:32 -0700197 # If a tag is detected, or a new commit starts
Douglas Anderson833e4192019-09-27 09:23:56 -0700198 if series_tag_match or commit_tag_match or change_id_match or \
Sean Anderson6949f702020-05-04 16:28:34 -0400199 cover_match or signoff_match or self.state == STATE_MSG_HEADER:
Bin Meng57b6b192016-06-26 23:24:31 -0700200 # but we are already in a section, this means 'END' is missing
201 # for that section, fix it up.
Bin Meng13b98d92016-06-26 23:24:29 -0700202 if self.in_section:
203 self.warn.append("Missing 'END' in section '%s'" % self.in_section)
204 if self.in_section == 'cover':
205 self.series.cover = self.section
206 elif self.in_section == 'notes':
207 if self.is_log:
208 self.series.notes += self.section
209 elif self.in_section == 'commit-notes':
210 if self.is_log:
211 self.commit.notes += self.section
212 else:
213 self.warn.append("Unknown section '%s'" % self.in_section)
214 self.in_section = None
215 self.skip_blank = True
216 self.section = []
Bin Meng57b6b192016-06-26 23:24:31 -0700217 # but we are already in a change list, that means a blank line
218 # is missing, fix it up.
219 if self.in_change:
Sean Anderson6949f702020-05-04 16:28:34 -0400220 self.warn.append("Missing 'blank line' in section '%s-changes'" % self.in_change)
221 self.in_change = None
222 self.change_version = 0
Bin Meng13b98d92016-06-26 23:24:29 -0700223
Simon Glass0d24de92012-01-14 15:12:45 +0000224 # If we are in a section, keep collecting lines until we see END
225 if self.in_section:
226 if line == 'END':
227 if self.in_section == 'cover':
228 self.series.cover = self.section
229 elif self.in_section == 'notes':
230 if self.is_log:
231 self.series.notes += self.section
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +0100232 elif self.in_section == 'commit-notes':
233 if self.is_log:
234 self.commit.notes += self.section
Simon Glass0d24de92012-01-14 15:12:45 +0000235 else:
236 self.warn.append("Unknown section '%s'" % self.in_section)
237 self.in_section = None
238 self.skip_blank = True
239 self.section = []
240 else:
241 self.section.append(line)
242
243 # Detect the commit subject
244 elif not is_blank and self.state == STATE_PATCH_SUBJECT:
245 self.commit.subject = line
246
247 # Detect the tags we want to remove, and skip blank lines
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +0100248 elif re_remove.match(line) and not commit_tag_match:
Simon Glass0d24de92012-01-14 15:12:45 +0000249 self.skip_blank = True
250
251 # TEST= should be the last thing in the commit, so remove
252 # everything after it
253 if line.startswith('TEST='):
254 self.found_test = True
255 elif self.skip_blank and is_blank:
256 self.skip_blank = False
257
Sean Anderson6949f702020-05-04 16:28:34 -0400258 # Detect Cover-xxx tags
Bin Menge7df2182016-06-26 23:24:28 -0700259 elif cover_match:
Sean Anderson6949f702020-05-04 16:28:34 -0400260 name = cover_match.group(1)
261 value = cover_match.group(2)
262 if name == 'letter':
263 self.in_section = 'cover'
264 self.skip_blank = False
265 elif name == 'letter-cc':
266 self.AddToSeries(line, 'cover-cc', value)
267 elif name == 'changes':
268 self.in_change = 'Cover'
269 self.change_version = self.ParseVersion(value, line)
Simon Glassfe2f8d92013-03-20 16:43:00 +0000270
Simon Glass0d24de92012-01-14 15:12:45 +0000271 # If we are in a change list, key collected lines until a blank one
272 elif self.in_change:
273 if is_blank:
274 # Blank line ends this change list
Sean Anderson6949f702020-05-04 16:28:34 -0400275 self.in_change = None
276 self.change_version = 0
Simon Glass102061b2014-04-20 10:50:14 -0600277 elif line == '---':
Sean Anderson6949f702020-05-04 16:28:34 -0400278 self.in_change = None
279 self.change_version = 0
Ilya Yanok05e5b732012-08-06 23:46:05 +0000280 out = self.ProcessLine(line)
Simon Glass0d24de92012-01-14 15:12:45 +0000281 else:
Ilya Yanoka8840cb2012-08-06 23:46:06 +0000282 if self.is_log:
Sean Anderson6949f702020-05-04 16:28:34 -0400283 if self.in_change == 'Series':
284 self.series.AddChange(self.change_version, self.commit, line)
285 elif self.in_change == 'Cover':
286 self.series.AddChange(self.change_version, None, line)
287 elif self.in_change == 'Commit':
288 self.commit.AddChange(self.change_version, line)
Simon Glass0d24de92012-01-14 15:12:45 +0000289 self.skip_blank = False
290
291 # Detect Series-xxx tags
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +0100292 elif series_tag_match:
293 name = series_tag_match.group(1)
294 value = series_tag_match.group(2)
Simon Glass0d24de92012-01-14 15:12:45 +0000295 if name == 'changes':
296 # value is the version number: e.g. 1, or 2
Sean Anderson6949f702020-05-04 16:28:34 -0400297 self.in_change = 'Series'
298 self.change_version = self.ParseVersion(value, line)
Simon Glass0d24de92012-01-14 15:12:45 +0000299 else:
300 self.AddToSeries(line, name, value)
301 self.skip_blank = True
302
Douglas Anderson833e4192019-09-27 09:23:56 -0700303 # Detect Change-Id tags
304 elif change_id_match:
305 value = change_id_match.group(1)
306 if self.is_log:
307 if self.commit.change_id:
308 raise ValueError("%s: Two Change-Ids: '%s' vs. '%s'" %
309 (self.commit.hash, self.commit.change_id, value))
310 self.commit.change_id = value
311 self.skip_blank = True
312
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +0100313 # Detect Commit-xxx tags
314 elif commit_tag_match:
315 name = commit_tag_match.group(1)
316 value = commit_tag_match.group(2)
317 if name == 'notes':
318 self.AddToCommit(line, name, value)
319 self.skip_blank = True
Sean Anderson6949f702020-05-04 16:28:34 -0400320 elif name == 'changes':
321 self.in_change = 'Commit'
322 self.change_version = self.ParseVersion(value, line)
Albert ARIBAUD5c8fdd92013-11-12 11:14:41 +0100323
Simon Glass0d24de92012-01-14 15:12:45 +0000324 # Detect the start of a new commit
325 elif commit_match:
326 self.CloseCommit()
Simon Glass0b5b4092014-10-15 02:27:00 -0600327 self.commit = commit.Commit(commit_match.group(1))
Simon Glass0d24de92012-01-14 15:12:45 +0000328
329 # Detect tags in the commit message
330 elif tag_match:
Simon Glass0d24de92012-01-14 15:12:45 +0000331 # Remove Tested-by self, since few will take much notice
Ilya Yanokc7379142012-08-06 23:46:08 +0000332 if (tag_match.group(1) == 'Tested-by' and
Simon Glass0d24de92012-01-14 15:12:45 +0000333 tag_match.group(2).find(os.getenv('USER') + '@') != -1):
334 self.warn.append("Ignoring %s" % line)
Simon Glass659c89d2014-02-16 08:23:47 -0700335 elif tag_match.group(1) == 'Patch-cc':
Simon Glass0d24de92012-01-14 15:12:45 +0000336 self.commit.AddCc(tag_match.group(2).split(','))
337 else:
Simon Glassd0c57192014-08-28 09:43:38 -0600338 out = [line]
Simon Glass0d24de92012-01-14 15:12:45 +0000339
Simon Glass102061b2014-04-20 10:50:14 -0600340 # Suppress duplicate signoffs
341 elif signoff_match:
Simon Glasse752edc2014-08-28 09:43:35 -0600342 if (self.is_log or not self.commit or
Simon Glass6be6b6b2014-05-13 12:14:02 -0600343 self.commit.CheckDuplicateSignoff(signoff_match.group(1))):
Simon Glass102061b2014-04-20 10:50:14 -0600344 out = [line]
345
Simon Glass0d24de92012-01-14 15:12:45 +0000346 # Well that means this is an ordinary line
347 else:
Simon Glass0d24de92012-01-14 15:12:45 +0000348 # Look for space before tab
349 m = re_space_before_tab.match(line)
350 if m:
351 self.warn.append('Line %d/%d has space before tab' %
352 (self.linenum, m.start()))
353
354 # OK, we have a valid non-blank line
355 out = [line]
356 self.linenum += 1
357 self.skip_blank = False
358 if self.state == STATE_DIFFS:
359 pass
360
361 # If this is the start of the diffs section, emit our tags and
362 # change log
363 elif line == '---':
364 self.state = STATE_DIFFS
365
Sean Anderson6949f702020-05-04 16:28:34 -0400366 # Output the tags (signoff first), then change list
Simon Glass0d24de92012-01-14 15:12:45 +0000367 out = []
Simon Glass0d24de92012-01-14 15:12:45 +0000368 log = self.series.MakeChangeLog(self.commit)
Simon Glasse752edc2014-08-28 09:43:35 -0600369 out += [line]
370 if self.commit:
371 out += self.commit.notes
372 out += [''] + log
Simon Glass0d24de92012-01-14 15:12:45 +0000373 elif self.found_test:
374 if not re_allowed_after_test.match(line):
375 self.lines_after_test += 1
376
377 return out
378
379 def Finalize(self):
380 """Close out processing of this patch stream"""
381 self.CloseCommit()
382 if self.lines_after_test:
383 self.warn.append('Found %d lines after TEST=' %
384 self.lines_after_test)
385
Douglas Anderson833e4192019-09-27 09:23:56 -0700386 def WriteMessageId(self, outfd):
387 """Write the Message-Id into the output.
388
389 This is based on the Change-Id in the original patch, the version,
390 and the prefix.
391
392 Args:
393 outfd: Output stream file object
394 """
395 if not self.commit.change_id:
396 return
397
398 # If the count is -1 we're testing, so use a fixed time
399 if self.commit.count == -1:
400 time_now = datetime.datetime(1999, 12, 31, 23, 59, 59)
401 else:
402 time_now = datetime.datetime.now()
403
404 # In theory there is email.utils.make_msgid() which would be nice
405 # to use, but it already produces something way too long and thus
406 # will produce ugly commit lines if someone throws this into
407 # a "Link:" tag in the final commit. So (sigh) roll our own.
408
409 # Start with the time; presumably we wouldn't send the same series
410 # with the same Change-Id at the exact same second.
411 parts = [time_now.strftime("%Y%m%d%H%M%S")]
412
413 # These seem like they would be nice to include.
414 if 'prefix' in self.series:
415 parts.append(self.series['prefix'])
416 if 'version' in self.series:
417 parts.append("v%s" % self.series['version'])
418
419 parts.append(str(self.commit.count + 1))
420
421 # The Change-Id must be last, right before the @
422 parts.append(self.commit.change_id)
423
424 # Join parts together with "." and write it out.
425 outfd.write('Message-Id: <%s@changeid>\n' % '.'.join(parts))
426
Simon Glass0d24de92012-01-14 15:12:45 +0000427 def ProcessStream(self, infd, outfd):
428 """Copy a stream from infd to outfd, filtering out unwanting things.
429
430 This is used to process patch files one at a time.
431
432 Args:
433 infd: Input stream file object
434 outfd: Output stream file object
435 """
436 # Extract the filename from each diff, for nice warnings
437 fname = None
438 last_fname = None
439 re_fname = re.compile('diff --git a/(.*) b/.*')
Douglas Anderson833e4192019-09-27 09:23:56 -0700440
441 self.WriteMessageId(outfd)
442
Simon Glass0d24de92012-01-14 15:12:45 +0000443 while True:
444 line = infd.readline()
445 if not line:
446 break
447 out = self.ProcessLine(line)
448
449 # Try to detect blank lines at EOF
450 for line in out:
451 match = re_fname.match(line)
452 if match:
453 last_fname = fname
454 fname = match.group(1)
455 if line == '+':
456 self.blank_count += 1
457 else:
458 if self.blank_count and (line == '-- ' or match):
459 self.warn.append("Found possible blank line(s) at "
460 "end of file '%s'" % last_fname)
461 outfd.write('+\n' * self.blank_count)
462 outfd.write(line + '\n')
463 self.blank_count = 0
464 self.Finalize()
465
466
Simon Glasse62f9052012-12-15 10:42:06 +0000467def GetMetaDataForList(commit_range, git_dir=None, count=None,
Simon Glass950a2312014-09-05 19:00:23 -0600468 series = None, allow_overwrite=False):
Simon Glasse62f9052012-12-15 10:42:06 +0000469 """Reads out patch series metadata from the commits
470
471 This does a 'git log' on the relevant commits and pulls out the tags we
472 are interested in.
473
474 Args:
475 commit_range: Range of commits to count (e.g. 'HEAD..base')
476 git_dir: Path to git repositiory (None to use default)
477 count: Number of commits to list, or None for no limit
478 series: Series object to add information into. By default a new series
479 is started.
Simon Glass950a2312014-09-05 19:00:23 -0600480 allow_overwrite: Allow tags to overwrite an existing tag
Simon Glasse62f9052012-12-15 10:42:06 +0000481 Returns:
482 A Series object containing information about the commits.
483 """
Simon Glass891b7a02014-09-05 19:00:19 -0600484 if not series:
485 series = Series()
Simon Glass950a2312014-09-05 19:00:23 -0600486 series.allow_overwrite = allow_overwrite
Simon Glass9ad96982016-03-06 19:45:33 -0700487 params = gitutil.LogCmd(commit_range, reverse=True, count=count,
Simon Glasscda2a612014-08-09 15:33:10 -0600488 git_dir=git_dir)
489 stdout = command.RunPipe([params], capture=True).stdout
Simon Glasse62f9052012-12-15 10:42:06 +0000490 ps = PatchStream(series, is_log=True)
491 for line in stdout.splitlines():
492 ps.ProcessLine(line)
493 ps.Finalize()
494 return series
495
Simon Glass0d24de92012-01-14 15:12:45 +0000496def GetMetaData(start, count):
497 """Reads out patch series metadata from the commits
498
499 This does a 'git log' on the relevant commits and pulls out the tags we
500 are interested in.
501
502 Args:
503 start: Commit to start from: 0=HEAD, 1=next one, etc.
504 count: Number of commits to list
505 """
Simon Glasse62f9052012-12-15 10:42:06 +0000506 return GetMetaDataForList('HEAD~%d' % start, None, count)
Simon Glass0d24de92012-01-14 15:12:45 +0000507
Simon Glass6e87ae12017-05-29 15:31:31 -0600508def GetMetaDataForTest(text):
509 """Process metadata from a file containing a git log. Used for tests
510
511 Args:
512 text:
513 """
514 series = Series()
515 ps = PatchStream(series, is_log=True)
516 for line in text.splitlines():
517 ps.ProcessLine(line)
518 ps.Finalize()
519 return series
520
Simon Glass0d24de92012-01-14 15:12:45 +0000521def FixPatch(backup_dir, fname, series, commit):
522 """Fix up a patch file, by adding/removing as required.
523
524 We remove our tags from the patch file, insert changes lists, etc.
525 The patch file is processed in place, and overwritten.
526
527 A backup file is put into backup_dir (if not None).
528
529 Args:
530 fname: Filename to patch file to process
531 series: Series information about this patch set
532 commit: Commit object for this patch file
533 Return:
534 A list of errors, or [] if all ok.
535 """
536 handle, tmpname = tempfile.mkstemp()
Simon Glass272cd852019-10-31 07:42:51 -0600537 outfd = os.fdopen(handle, 'w', encoding='utf-8')
538 infd = open(fname, 'r', encoding='utf-8')
Simon Glass0d24de92012-01-14 15:12:45 +0000539 ps = PatchStream(series)
540 ps.commit = commit
541 ps.ProcessStream(infd, outfd)
542 infd.close()
543 outfd.close()
544
545 # Create a backup file if required
546 if backup_dir:
547 shutil.copy(fname, os.path.join(backup_dir, os.path.basename(fname)))
548 shutil.move(tmpname, fname)
549 return ps.warn
550
551def FixPatches(series, fnames):
552 """Fix up a list of patches identified by filenames
553
554 The patch files are processed in place, and overwritten.
555
556 Args:
557 series: The series object
558 fnames: List of patch files to process
559 """
560 # Current workflow creates patches, so we shouldn't need a backup
561 backup_dir = None #tempfile.mkdtemp('clean-patch')
562 count = 0
563 for fname in fnames:
564 commit = series.commits[count]
565 commit.patch = fname
Douglas Anderson833e4192019-09-27 09:23:56 -0700566 commit.count = count
Simon Glass0d24de92012-01-14 15:12:45 +0000567 result = FixPatch(backup_dir, fname, series, commit)
568 if result:
Paul Burtona920a172016-09-27 16:03:50 +0100569 print('%d warnings for %s:' % (len(result), fname))
Simon Glass0d24de92012-01-14 15:12:45 +0000570 for warn in result:
Paul Burtona920a172016-09-27 16:03:50 +0100571 print('\t', warn)
Simon Glass0d24de92012-01-14 15:12:45 +0000572 print
573 count += 1
Paul Burtona920a172016-09-27 16:03:50 +0100574 print('Cleaned %d patches' % count)
Simon Glass0d24de92012-01-14 15:12:45 +0000575
576def InsertCoverLetter(fname, series, count):
577 """Inserts a cover letter with the required info into patch 0
578
579 Args:
580 fname: Input / output filename of the cover letter file
581 series: Series object
582 count: Number of patches in the series
583 """
584 fd = open(fname, 'r')
585 lines = fd.readlines()
586 fd.close()
587
588 fd = open(fname, 'w')
589 text = series.cover
590 prefix = series.GetPatchPrefix()
591 for line in lines:
592 if line.startswith('Subject:'):
Wu, Josh35ce2dc2015-04-03 10:51:17 +0800593 # if more than 10 or 100 patches, it should say 00/xx, 000/xxx, etc
594 zero_repeat = int(math.log10(count)) + 1
595 zero = '0' * zero_repeat
596 line = 'Subject: [%s %s/%d] %s\n' % (prefix, zero, count, text[0])
Simon Glass0d24de92012-01-14 15:12:45 +0000597
598 # Insert our cover letter
599 elif line.startswith('*** BLURB HERE ***'):
600 # First the blurb test
601 line = '\n'.join(text[1:]) + '\n'
602 if series.get('notes'):
603 line += '\n'.join(series.notes) + '\n'
604
605 # Now the change list
606 out = series.MakeChangeLog(None)
607 line += '\n' + '\n'.join(out)
608 fd.write(line)
609 fd.close()