blob: 7ca2e28b1f25aa07cd761d17f25acce0b822b0dc [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
Patrick Williamsc124f4f2015-09-15 14:41:29 -05005import oe.path
Brad Bishopd7bf8c12018-02-25 22:55:05 -05006import oe.types
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007
8class NotFoundError(bb.BBHandledException):
9 def __init__(self, path):
10 self.path = path
11
12 def __str__(self):
13 return "Error: %s not found." % self.path
14
15class CmdError(bb.BBHandledException):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050016 def __init__(self, command, exitstatus, output):
17 self.command = command
Patrick Williamsc124f4f2015-09-15 14:41:29 -050018 self.status = exitstatus
19 self.output = output
20
21 def __str__(self):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050022 return "Command Error: '%s' exited with %d Output:\n%s" % \
23 (self.command, self.status, self.output)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050024
25
26def runcmd(args, dir = None):
27 import pipes
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080028 import subprocess
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029
30 if dir:
31 olddir = os.path.abspath(os.curdir)
32 if not os.path.exists(dir):
33 raise NotFoundError(dir)
34 os.chdir(dir)
35 # print("cwd: %s -> %s" % (olddir, dir))
36
37 try:
38 args = [ pipes.quote(str(arg)) for arg in args ]
39 cmd = " ".join(args)
40 # print("cmd: %s" % cmd)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080041 (exitstatus, output) = subprocess.getstatusoutput(cmd)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050042 if exitstatus != 0:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050043 raise CmdError(cmd, exitstatus >> 8, output)
Brad Bishop316dfdd2018-06-25 12:45:53 -040044 if " fuzz " in output:
Brad Bishopd89cb5f2019-04-10 09:02:41 -040045 # Drop patch fuzz info with header and footer to log file so
46 # insane.bbclass can handle to throw error/warning
47 bb.note("--- Patch fuzz start ---\n%s\n--- Patch fuzz end ---" % format(output))
Brad Bishop316dfdd2018-06-25 12:45:53 -040048
Patrick Williamsc124f4f2015-09-15 14:41:29 -050049 return output
50
51 finally:
52 if dir:
53 os.chdir(olddir)
54
55class PatchError(Exception):
56 def __init__(self, msg):
57 self.msg = msg
58
59 def __str__(self):
60 return "Patch Error: %s" % self.msg
61
62class PatchSet(object):
63 defaults = {
64 "strippath": 1
65 }
66
67 def __init__(self, dir, d):
68 self.dir = dir
69 self.d = d
70 self.patches = []
71 self._current = None
72
73 def current(self):
74 return self._current
75
76 def Clean(self):
77 """
78 Clean out the patch set. Generally includes unapplying all
79 patches and wiping out all associated metadata.
80 """
81 raise NotImplementedError()
82
83 def Import(self, patch, force):
84 if not patch.get("file"):
85 if not patch.get("remote"):
86 raise PatchError("Patch file must be specified in patch import.")
87 else:
88 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
89
90 for param in PatchSet.defaults:
91 if not patch.get(param):
92 patch[param] = PatchSet.defaults[param]
93
94 if patch.get("remote"):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050095 patch["file"] = self.d.expand(bb.fetch2.localpath(patch["remote"], self.d))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050096
97 patch["filemd5"] = bb.utils.md5_file(patch["file"])
98
99 def Push(self, force):
100 raise NotImplementedError()
101
102 def Pop(self, force):
103 raise NotImplementedError()
104
105 def Refresh(self, remote = None, all = None):
106 raise NotImplementedError()
107
108 @staticmethod
109 def getPatchedFiles(patchfile, striplevel, srcdir=None):
110 """
111 Read a patch file and determine which files it will modify.
112 Params:
113 patchfile: the patch file to read
114 striplevel: the strip level at which the patch is going to be applied
115 srcdir: optional path to join onto the patched file paths
116 Returns:
117 A list of tuples of file path and change mode ('A' for add,
118 'D' for delete or 'M' for modify)
119 """
120
121 def patchedpath(patchline):
122 filepth = patchline.split()[1]
123 if filepth.endswith('/dev/null'):
124 return '/dev/null'
125 filesplit = filepth.split(os.sep)
126 if striplevel > len(filesplit):
127 bb.error('Patch %s has invalid strip level %d' % (patchfile, striplevel))
128 return None
129 return os.sep.join(filesplit[striplevel:])
130
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600131 for encoding in ['utf-8', 'latin-1']:
132 try:
133 copiedmode = False
134 filelist = []
135 with open(patchfile) as f:
136 for line in f:
137 if line.startswith('--- '):
138 patchpth = patchedpath(line)
139 if not patchpth:
140 break
141 if copiedmode:
142 addedfile = patchpth
143 else:
144 removedfile = patchpth
145 elif line.startswith('+++ '):
146 addedfile = patchedpath(line)
147 if not addedfile:
148 break
149 elif line.startswith('*** '):
150 copiedmode = True
151 removedfile = patchedpath(line)
152 if not removedfile:
153 break
154 else:
155 removedfile = None
156 addedfile = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500157
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600158 if addedfile and removedfile:
159 if removedfile == '/dev/null':
160 mode = 'A'
161 elif addedfile == '/dev/null':
162 mode = 'D'
163 else:
164 mode = 'M'
165 if srcdir:
166 fullpath = os.path.abspath(os.path.join(srcdir, addedfile))
167 else:
168 fullpath = addedfile
169 filelist.append((fullpath, mode))
170 except UnicodeDecodeError:
171 continue
172 break
173 else:
174 raise PatchError('Unable to decode %s' % patchfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500175
176 return filelist
177
178
179class PatchTree(PatchSet):
180 def __init__(self, dir, d):
181 PatchSet.__init__(self, dir, d)
182 self.patchdir = os.path.join(self.dir, 'patches')
183 self.seriespath = os.path.join(self.dir, 'patches', 'series')
184 bb.utils.mkdirhier(self.patchdir)
185
186 def _appendPatchFile(self, patch, strippath):
187 with open(self.seriespath, 'a') as f:
188 f.write(os.path.basename(patch) + "," + strippath + "\n")
189 shellcmd = ["cat", patch, ">" , self.patchdir + "/" + os.path.basename(patch)]
190 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
191
192 def _removePatch(self, p):
193 patch = {}
194 patch['file'] = p.split(",")[0]
195 patch['strippath'] = p.split(",")[1]
196 self._applypatch(patch, False, True)
197
198 def _removePatchFile(self, all = False):
199 if not os.path.exists(self.seriespath):
200 return
201 with open(self.seriespath, 'r+') as f:
202 patches = f.readlines()
203 if all:
204 for p in reversed(patches):
205 self._removePatch(os.path.join(self.patchdir, p.strip()))
206 patches = []
207 else:
208 self._removePatch(os.path.join(self.patchdir, patches[-1].strip()))
209 patches.pop()
210 with open(self.seriespath, 'w') as f:
211 for p in patches:
212 f.write(p)
213
214 def Import(self, patch, force = None):
215 """"""
216 PatchSet.Import(self, patch, force)
217
218 if self._current is not None:
219 i = self._current + 1
220 else:
221 i = 0
222 self.patches.insert(i, patch)
223
224 def _applypatch(self, patch, force = False, reverse = False, run = True):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400225 shellcmd = ["cat", patch['file'], "|", "patch", "--no-backup-if-mismatch", "-p", patch['strippath']]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500226 if reverse:
227 shellcmd.append('-R')
228
229 if not run:
230 return "sh" + "-c" + " ".join(shellcmd)
231
232 if not force:
233 shellcmd.append('--dry-run')
234
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500235 try:
236 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500237
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500238 if force:
239 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500241 shellcmd.pop(len(shellcmd) - 1)
242 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
243 except CmdError as err:
244 raise bb.BBHandledException("Applying '%s' failed:\n%s" %
245 (os.path.basename(patch['file']), err.output))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500246
247 if not reverse:
248 self._appendPatchFile(patch['file'], patch['strippath'])
249
250 return output
251
252 def Push(self, force = False, all = False, run = True):
253 bb.note("self._current is %s" % self._current)
254 bb.note("patches is %s" % self.patches)
255 if all:
256 for i in self.patches:
257 bb.note("applying patch %s" % i)
258 self._applypatch(i, force)
259 self._current = i
260 else:
261 if self._current is not None:
262 next = self._current + 1
263 else:
264 next = 0
265
266 bb.note("applying patch %s" % self.patches[next])
267 ret = self._applypatch(self.patches[next], force)
268
269 self._current = next
270 return ret
271
272 def Pop(self, force = None, all = None):
273 if all:
274 self._removePatchFile(True)
275 self._current = None
276 else:
277 self._removePatchFile(False)
278
279 if self._current == 0:
280 self._current = None
281
282 if self._current is not None:
283 self._current = self._current - 1
284
285 def Clean(self):
286 """"""
287 self.Pop(all=True)
288
289class GitApplyTree(PatchTree):
290 patch_line_prefix = '%% original patch'
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500291 ignore_commit_prefix = '%% ignore'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500292
293 def __init__(self, dir, d):
294 PatchTree.__init__(self, dir, d)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500295 self.commituser = d.getVar('PATCH_GIT_USER_NAME')
296 self.commitemail = d.getVar('PATCH_GIT_USER_EMAIL')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500297
298 @staticmethod
299 def extractPatchHeader(patchfile):
300 """
301 Extract just the header lines from the top of a patch file
302 """
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600303 for encoding in ['utf-8', 'latin-1']:
304 lines = []
305 try:
306 with open(patchfile, 'r', encoding=encoding) as f:
307 for line in f:
308 if line.startswith('Index: ') or line.startswith('diff -') or line.startswith('---'):
309 break
310 lines.append(line)
311 except UnicodeDecodeError:
312 continue
313 break
314 else:
315 raise PatchError('Unable to find a character encoding to decode %s' % patchfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500316 return lines
317
318 @staticmethod
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500319 def decodeAuthor(line):
320 from email.header import decode_header
321 authorval = line.split(':', 1)[1].strip().replace('"', '')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600322 result = decode_header(authorval)[0][0]
323 if hasattr(result, 'decode'):
324 result = result.decode('utf-8')
325 return result
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500326
327 @staticmethod
328 def interpretPatchHeader(headerlines):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500329 import re
Brad Bishop19323692019-04-05 15:28:33 -0400330 author_re = re.compile(r'[\S ]+ <\S+@\S+\.\S+>')
331 from_commit_re = re.compile(r'^From [a-z0-9]{40} .*')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500332 outlines = []
333 author = None
334 date = None
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500335 subject = None
336 for line in headerlines:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500337 if line.startswith('Subject: '):
338 subject = line.split(':', 1)[1]
339 # Remove any [PATCH][oe-core] etc.
340 subject = re.sub(r'\[.+?\]\s*', '', subject)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500341 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500342 elif line.startswith('From: ') or line.startswith('Author: '):
343 authorval = GitApplyTree.decodeAuthor(line)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500344 # git is fussy about author formatting i.e. it must be Name <email@domain>
345 if author_re.match(authorval):
346 author = authorval
347 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500348 elif line.startswith('Date: '):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500349 if date is None:
350 dateval = line.split(':', 1)[1].strip()
351 # Very crude check for date format, since git will blow up if it's not in the right
352 # format. Without e.g. a python-dateutils dependency we can't do a whole lot more
353 if len(dateval) > 12:
354 date = dateval
355 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500356 elif not author and line.lower().startswith('signed-off-by: '):
357 authorval = GitApplyTree.decodeAuthor(line)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500358 # git is fussy about author formatting i.e. it must be Name <email@domain>
359 if author_re.match(authorval):
360 author = authorval
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600361 elif from_commit_re.match(line):
362 # We don't want the From <commit> line - if it's present it will break rebasing
363 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500364 outlines.append(line)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600365
366 if not subject:
367 firstline = None
368 for line in headerlines:
369 line = line.strip()
370 if firstline:
371 if line:
372 # Second line is not blank, the first line probably isn't usable
373 firstline = None
374 break
375 elif line:
376 firstline = line
377 if firstline and not firstline.startswith(('#', 'Index:', 'Upstream-Status:')) and len(firstline) < 100:
378 subject = firstline
379
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500380 return outlines, author, date, subject
381
382 @staticmethod
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600383 def gitCommandUserOptions(cmd, commituser=None, commitemail=None, d=None):
384 if d:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500385 commituser = d.getVar('PATCH_GIT_USER_NAME')
386 commitemail = d.getVar('PATCH_GIT_USER_EMAIL')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600387 if commituser:
388 cmd += ['-c', 'user.name="%s"' % commituser]
389 if commitemail:
390 cmd += ['-c', 'user.email="%s"' % commitemail]
391
392 @staticmethod
393 def prepareCommit(patchfile, commituser=None, commitemail=None):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500394 """
395 Prepare a git commit command line based on the header from a patch file
396 (typically this is useful for patches that cannot be applied with "git am" due to formatting)
397 """
398 import tempfile
399 # Process patch header and extract useful information
400 lines = GitApplyTree.extractPatchHeader(patchfile)
401 outlines, author, date, subject = GitApplyTree.interpretPatchHeader(lines)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600402 if not author or not subject or not date:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500403 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600404 shellcmd = ["git", "log", "--format=email", "--follow", "--diff-filter=A", "--", patchfile]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500405 out = runcmd(["sh", "-c", " ".join(shellcmd)], os.path.dirname(patchfile))
406 except CmdError:
407 out = None
408 if out:
409 _, newauthor, newdate, newsubject = GitApplyTree.interpretPatchHeader(out.splitlines())
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600410 if not author:
411 # If we're setting the author then the date should be set as well
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500412 author = newauthor
413 date = newdate
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600414 elif not date:
415 # If we don't do this we'll get the current date, at least this will be closer
416 date = newdate
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500417 if not subject:
418 subject = newsubject
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500419 if subject and not (outlines and outlines[0].strip() == subject):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500420 outlines.insert(0, '%s\n\n' % subject.strip())
421
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500422 # Write out commit message to a file
423 with tempfile.NamedTemporaryFile('w', delete=False) as tf:
424 tmpfile = tf.name
425 for line in outlines:
426 tf.write(line)
427 # Prepare git command
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600428 cmd = ["git"]
429 GitApplyTree.gitCommandUserOptions(cmd, commituser, commitemail)
430 cmd += ["commit", "-F", tmpfile]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500431 # git doesn't like plain email addresses as authors
432 if author and '<' in author:
433 cmd.append('--author="%s"' % author)
434 if date:
435 cmd.append('--date="%s"' % date)
436 return (tmpfile, cmd)
437
438 @staticmethod
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500439 def extractPatches(tree, startcommit, outdir, paths=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500440 import tempfile
441 import shutil
442 tempdir = tempfile.mkdtemp(prefix='oepatch')
443 try:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400444 shellcmd = ["git", "format-patch", "--no-signature", "--no-numbered", startcommit, "-o", tempdir]
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500445 if paths:
446 shellcmd.append('--')
447 shellcmd.extend(paths)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500448 out = runcmd(["sh", "-c", " ".join(shellcmd)], tree)
449 if out:
450 for srcfile in out.split():
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600451 for encoding in ['utf-8', 'latin-1']:
452 patchlines = []
453 outfile = None
454 try:
455 with open(srcfile, 'r', encoding=encoding) as f:
456 for line in f:
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500457 if line.startswith(GitApplyTree.patch_line_prefix):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600458 outfile = line.split()[-1].strip()
459 continue
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500460 if line.startswith(GitApplyTree.ignore_commit_prefix):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600461 continue
462 patchlines.append(line)
463 except UnicodeDecodeError:
464 continue
465 break
466 else:
467 raise PatchError('Unable to find a character encoding to decode %s' % srcfile)
468
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500469 if not outfile:
470 outfile = os.path.basename(srcfile)
471 with open(os.path.join(outdir, outfile), 'w') as of:
472 for line in patchlines:
473 of.write(line)
474 finally:
475 shutil.rmtree(tempdir)
476
477 def _applypatch(self, patch, force = False, reverse = False, run = True):
478 import shutil
479
480 def _applypatchhelper(shellcmd, patch, force = False, reverse = False, run = True):
481 if reverse:
482 shellcmd.append('-R')
483
484 shellcmd.append(patch['file'])
485
486 if not run:
487 return "sh" + "-c" + " ".join(shellcmd)
488
489 return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
490
491 # Add hooks which add a pointer to the original patch file name in the commit message
492 reporoot = (runcmd("git rev-parse --show-toplevel".split(), self.dir) or '').strip()
493 if not reporoot:
494 raise Exception("Cannot get repository root for directory %s" % self.dir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500495 hooks_dir = os.path.join(reporoot, '.git', 'hooks')
496 hooks_dir_backup = hooks_dir + '.devtool-orig'
497 if os.path.lexists(hooks_dir_backup):
498 raise Exception("Git hooks backup directory already exists: %s" % hooks_dir_backup)
499 if os.path.lexists(hooks_dir):
500 shutil.move(hooks_dir, hooks_dir_backup)
501 os.mkdir(hooks_dir)
502 commithook = os.path.join(hooks_dir, 'commit-msg')
503 applyhook = os.path.join(hooks_dir, 'applypatch-msg')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500504 with open(commithook, 'w') as f:
505 # NOTE: the formatting here is significant; if you change it you'll also need to
506 # change other places which read it back
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500507 f.write('echo "\n%s: $PATCHFILE" >> $1' % GitApplyTree.patch_line_prefix)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600508 os.chmod(commithook, 0o755)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500509 shutil.copy2(commithook, applyhook)
510 try:
511 patchfilevar = 'PATCHFILE="%s"' % os.path.basename(patch['file'])
512 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600513 shellcmd = [patchfilevar, "git", "--work-tree=%s" % reporoot]
514 self.gitCommandUserOptions(shellcmd, self.commituser, self.commitemail)
515 shellcmd += ["am", "-3", "--keep-cr", "-p%s" % patch['strippath']]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500516 return _applypatchhelper(shellcmd, patch, force, reverse, run)
517 except CmdError:
518 # Need to abort the git am, or we'll still be within it at the end
519 try:
520 shellcmd = ["git", "--work-tree=%s" % reporoot, "am", "--abort"]
521 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
522 except CmdError:
523 pass
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500524 # git am won't always clean up after itself, sadly, so...
525 shellcmd = ["git", "--work-tree=%s" % reporoot, "reset", "--hard", "HEAD"]
526 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
527 # Also need to take care of any stray untracked files
528 shellcmd = ["git", "--work-tree=%s" % reporoot, "clean", "-f"]
529 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
530
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500531 # Fall back to git apply
532 shellcmd = ["git", "--git-dir=%s" % reporoot, "apply", "-p%s" % patch['strippath']]
533 try:
534 output = _applypatchhelper(shellcmd, patch, force, reverse, run)
535 except CmdError:
536 # Fall back to patch
537 output = PatchTree._applypatch(self, patch, force, reverse, run)
538 # Add all files
539 shellcmd = ["git", "add", "-f", "-A", "."]
540 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
541 # Exclude the patches directory
542 shellcmd = ["git", "reset", "HEAD", self.patchdir]
543 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
544 # Commit the result
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600545 (tmpfile, shellcmd) = self.prepareCommit(patch['file'], self.commituser, self.commitemail)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500546 try:
547 shellcmd.insert(0, patchfilevar)
548 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
549 finally:
550 os.remove(tmpfile)
551 return output
552 finally:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500553 shutil.rmtree(hooks_dir)
554 if os.path.lexists(hooks_dir_backup):
555 shutil.move(hooks_dir_backup, hooks_dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500556
557
558class QuiltTree(PatchSet):
559 def _runcmd(self, args, run = True):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500560 quiltrc = self.d.getVar('QUILTRCFILE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500561 if not run:
562 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
563 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
564
565 def _quiltpatchpath(self, file):
566 return os.path.join(self.dir, "patches", os.path.basename(file))
567
568
569 def __init__(self, dir, d):
570 PatchSet.__init__(self, dir, d)
571 self.initialized = False
572 p = os.path.join(self.dir, 'patches')
573 if not os.path.exists(p):
574 os.makedirs(p)
575
576 def Clean(self):
577 try:
578 self._runcmd(["pop", "-a", "-f"])
579 oe.path.remove(os.path.join(self.dir, "patches","series"))
580 except Exception:
581 pass
582 self.initialized = True
583
584 def InitFromDir(self):
585 # read series -> self.patches
586 seriespath = os.path.join(self.dir, 'patches', 'series')
587 if not os.path.exists(self.dir):
588 raise NotFoundError(self.dir)
589 if os.path.exists(seriespath):
590 with open(seriespath, 'r') as f:
591 for line in f.readlines():
592 patch = {}
593 parts = line.strip().split()
594 patch["quiltfile"] = self._quiltpatchpath(parts[0])
595 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
596 if len(parts) > 1:
597 patch["strippath"] = parts[1][2:]
598 self.patches.append(patch)
599
600 # determine which patches are applied -> self._current
601 try:
602 output = runcmd(["quilt", "applied"], self.dir)
603 except CmdError:
604 import sys
605 if sys.exc_value.output.strip() == "No patches applied":
606 return
607 else:
608 raise
609 output = [val for val in output.split('\n') if not val.startswith('#')]
610 for patch in self.patches:
611 if os.path.basename(patch["quiltfile"]) == output[-1]:
612 self._current = self.patches.index(patch)
613 self.initialized = True
614
615 def Import(self, patch, force = None):
616 if not self.initialized:
617 self.InitFromDir()
618 PatchSet.Import(self, patch, force)
619 oe.path.symlink(patch["file"], self._quiltpatchpath(patch["file"]), force=True)
620 with open(os.path.join(self.dir, "patches", "series"), "a") as f:
621 f.write(os.path.basename(patch["file"]) + " -p" + patch["strippath"] + "\n")
622 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
623 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
624
625 # TODO: determine if the file being imported:
626 # 1) is already imported, and is the same
627 # 2) is already imported, but differs
628
629 self.patches.insert(self._current or 0, patch)
630
631
632 def Push(self, force = False, all = False, run = True):
633 # quilt push [-f]
634
635 args = ["push"]
636 if force:
637 args.append("-f")
638 if all:
639 args.append("-a")
640 if not run:
641 return self._runcmd(args, run)
642
643 self._runcmd(args)
644
645 if self._current is not None:
646 self._current = self._current + 1
647 else:
648 self._current = 0
649
650 def Pop(self, force = None, all = None):
651 # quilt pop [-f]
652 args = ["pop"]
653 if force:
654 args.append("-f")
655 if all:
656 args.append("-a")
657
658 self._runcmd(args)
659
660 if self._current == 0:
661 self._current = None
662
663 if self._current is not None:
664 self._current = self._current - 1
665
666 def Refresh(self, **kwargs):
667 if kwargs.get("remote"):
668 patch = self.patches[kwargs["patch"]]
669 if not patch:
670 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
671 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(patch["remote"])
672 if type == "file":
673 import shutil
674 if not patch.get("file") and patch.get("remote"):
675 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
676
677 shutil.copyfile(patch["quiltfile"], patch["file"])
678 else:
679 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
680 else:
681 # quilt refresh
682 args = ["refresh"]
683 if kwargs.get("quiltfile"):
684 args.append(os.path.basename(kwargs["quiltfile"]))
685 elif kwargs.get("patch"):
686 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
687 self._runcmd(args)
688
689class Resolver(object):
690 def __init__(self, patchset, terminal):
691 raise NotImplementedError()
692
693 def Resolve(self):
694 raise NotImplementedError()
695
696 def Revert(self):
697 raise NotImplementedError()
698
699 def Finalize(self):
700 raise NotImplementedError()
701
702class NOOPResolver(Resolver):
703 def __init__(self, patchset, terminal):
704 self.patchset = patchset
705 self.terminal = terminal
706
707 def Resolve(self):
708 olddir = os.path.abspath(os.curdir)
709 os.chdir(self.patchset.dir)
710 try:
711 self.patchset.Push()
712 except Exception:
713 import sys
714 os.chdir(olddir)
715 raise
716
717# Patch resolver which relies on the user doing all the work involved in the
718# resolution, with the exception of refreshing the remote copy of the patch
719# files (the urls).
720class UserResolver(Resolver):
721 def __init__(self, patchset, terminal):
722 self.patchset = patchset
723 self.terminal = terminal
724
725 # Force a push in the patchset, then drop to a shell for the user to
726 # resolve any rejected hunks
727 def Resolve(self):
728 olddir = os.path.abspath(os.curdir)
729 os.chdir(self.patchset.dir)
730 try:
731 self.patchset.Push(False)
732 except CmdError as v:
733 # Patch application failed
734 patchcmd = self.patchset.Push(True, False, False)
735
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500736 t = self.patchset.d.getVar('T')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500737 if not t:
738 bb.msg.fatal("Build", "T not set")
739 bb.utils.mkdirhier(t)
740 import random
741 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
742 with open(rcfile, "w") as f:
743 f.write("echo '*** Manual patch resolution mode ***'\n")
744 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
745 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
746 f.write("echo ''\n")
747 f.write(" ".join(patchcmd) + "\n")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600748 os.chmod(rcfile, 0o775)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500749
750 self.terminal("bash --rcfile " + rcfile, 'Patch Rejects: Please fix patch rejects manually', self.patchset.d)
751
752 # Construct a new PatchSet after the user's changes, compare the
753 # sets, checking patches for modifications, and doing a remote
754 # refresh on each.
755 oldpatchset = self.patchset
756 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
757
758 for patch in self.patchset.patches:
759 oldpatch = None
760 for opatch in oldpatchset.patches:
761 if opatch["quiltfile"] == patch["quiltfile"]:
762 oldpatch = opatch
763
764 if oldpatch:
765 patch["remote"] = oldpatch["remote"]
766 if patch["quiltfile"] == oldpatch["quiltfile"]:
767 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
768 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
769 # user change? remote refresh
770 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
771 else:
772 # User did not fix the problem. Abort.
773 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
774 except Exception:
775 os.chdir(olddir)
776 raise
777 os.chdir(olddir)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500778
779
780def patch_path(url, fetch, workdir, expand=True):
Brad Bishop19323692019-04-05 15:28:33 -0400781 """Return the local path of a patch, or return nothing if this isn't a patch"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500782
783 local = fetch.localpath(url)
Brad Bishop19323692019-04-05 15:28:33 -0400784 if os.path.isdir(local):
785 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500786 base, ext = os.path.splitext(os.path.basename(local))
787 if ext in ('.gz', '.bz2', '.xz', '.Z'):
788 if expand:
789 local = os.path.join(workdir, base)
790 ext = os.path.splitext(base)[1]
791
792 urldata = fetch.ud[url]
793 if "apply" in urldata.parm:
794 apply = oe.types.boolean(urldata.parm["apply"])
795 if not apply:
796 return
797 elif ext not in (".diff", ".patch"):
798 return
799
800 return local
801
802def src_patches(d, all=False, expand=True):
803 workdir = d.getVar('WORKDIR')
804 fetch = bb.fetch2.Fetch([], d)
805 patches = []
806 sources = []
807 for url in fetch.urls:
808 local = patch_path(url, fetch, workdir, expand)
809 if not local:
810 if all:
811 local = fetch.localpath(url)
812 sources.append(local)
813 continue
814
815 urldata = fetch.ud[url]
816 parm = urldata.parm
817 patchname = parm.get('pname') or os.path.basename(local)
818
819 apply, reason = should_apply(parm, d)
820 if not apply:
821 if reason:
822 bb.note("Patch %s %s" % (patchname, reason))
823 continue
824
825 patchparm = {'patchname': patchname}
826 if "striplevel" in parm:
827 striplevel = parm["striplevel"]
828 elif "pnum" in parm:
829 #bb.msg.warn(None, "Deprecated usage of 'pnum' url parameter in '%s', please use 'striplevel'" % url)
830 striplevel = parm["pnum"]
831 else:
832 striplevel = '1'
833 patchparm['striplevel'] = striplevel
834
835 patchdir = parm.get('patchdir')
836 if patchdir:
837 patchparm['patchdir'] = patchdir
838
839 localurl = bb.fetch.encodeurl(('file', '', local, '', '', patchparm))
840 patches.append(localurl)
841
842 if all:
843 return sources
844
845 return patches
846
847
848def should_apply(parm, d):
Brad Bishopc342db32019-05-15 21:57:59 -0400849 import bb.utils
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500850 if "mindate" in parm or "maxdate" in parm:
851 pn = d.getVar('PN')
852 srcdate = d.getVar('SRCDATE_%s' % pn)
853 if not srcdate:
854 srcdate = d.getVar('SRCDATE')
855
856 if srcdate == "now":
857 srcdate = d.getVar('DATE')
858
859 if "maxdate" in parm and parm["maxdate"] < srcdate:
860 return False, 'is outdated'
861
862 if "mindate" in parm and parm["mindate"] > srcdate:
863 return False, 'is predated'
864
865
866 if "minrev" in parm:
867 srcrev = d.getVar('SRCREV')
868 if srcrev and srcrev < parm["minrev"]:
869 return False, 'applies to later revisions'
870
871 if "maxrev" in parm:
872 srcrev = d.getVar('SRCREV')
873 if srcrev and srcrev > parm["maxrev"]:
874 return False, 'applies to earlier revisions'
875
876 if "rev" in parm:
877 srcrev = d.getVar('SRCREV')
878 if srcrev and parm["rev"] not in srcrev:
879 return False, "doesn't apply to revision"
880
881 if "notrev" in parm:
882 srcrev = d.getVar('SRCREV')
883 if srcrev and parm["notrev"] in srcrev:
884 return False, "doesn't apply to revision"
885
Brad Bishopc342db32019-05-15 21:57:59 -0400886 if "maxver" in parm:
887 pv = d.getVar('PV')
888 if bb.utils.vercmp_string_op(pv, parm["maxver"], ">"):
889 return False, "applies to earlier version"
890
891 if "minver" in parm:
892 pv = d.getVar('PV')
893 if bb.utils.vercmp_string_op(pv, parm["minver"], "<"):
894 return False, "applies to later version"
895
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500896 return True, None
897