blob: ff9afc9df9f63f7cc11593e26ecbc3f44cd5c664 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Patrick Williams92b42cb2022-09-03 06:53:57 -05002# Copyright OpenEmbedded Contributors
3#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: GPL-2.0-only
5#
6
Patrick Williams8e7b46e2023-05-01 14:19:06 -05007import os
8import shlex
9import subprocess
Patrick Williamsc124f4f2015-09-15 14:41:29 -050010import oe.path
Brad Bishopd7bf8c12018-02-25 22:55:05 -050011import oe.types
Patrick Williamsc124f4f2015-09-15 14:41:29 -050012
13class NotFoundError(bb.BBHandledException):
14 def __init__(self, path):
15 self.path = path
16
17 def __str__(self):
18 return "Error: %s not found." % self.path
19
20class CmdError(bb.BBHandledException):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050021 def __init__(self, command, exitstatus, output):
22 self.command = command
Patrick Williamsc124f4f2015-09-15 14:41:29 -050023 self.status = exitstatus
24 self.output = output
25
26 def __str__(self):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050027 return "Command Error: '%s' exited with %d Output:\n%s" % \
28 (self.command, self.status, self.output)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029
30
31def runcmd(args, dir = None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050032 if dir:
33 olddir = os.path.abspath(os.curdir)
34 if not os.path.exists(dir):
35 raise NotFoundError(dir)
36 os.chdir(dir)
37 # print("cwd: %s -> %s" % (olddir, dir))
38
39 try:
Patrick Williams8e7b46e2023-05-01 14:19:06 -050040 args = [ shlex.quote(str(arg)) for arg in args ]
Patrick Williamsc124f4f2015-09-15 14:41:29 -050041 cmd = " ".join(args)
42 # print("cmd: %s" % cmd)
Andrew Geisslerd1e89492021-02-12 15:35:20 -060043 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
44 stdout, stderr = proc.communicate()
45 stdout = stdout.decode('utf-8')
46 stderr = stderr.decode('utf-8')
47 exitstatus = proc.returncode
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048 if exitstatus != 0:
Andrew Geisslerd1e89492021-02-12 15:35:20 -060049 raise CmdError(cmd, exitstatus >> 8, "stdout: %s\nstderr: %s" % (stdout, stderr))
50 if " fuzz " in stdout and "Hunk " in stdout:
Brad Bishopd89cb5f2019-04-10 09:02:41 -040051 # Drop patch fuzz info with header and footer to log file so
52 # insane.bbclass can handle to throw error/warning
Andrew Geisslerd1e89492021-02-12 15:35:20 -060053 bb.note("--- Patch fuzz start ---\n%s\n--- Patch fuzz end ---" % format(stdout))
Brad Bishop316dfdd2018-06-25 12:45:53 -040054
Andrew Geisslerd1e89492021-02-12 15:35:20 -060055 return stdout
Patrick Williamsc124f4f2015-09-15 14:41:29 -050056
57 finally:
58 if dir:
59 os.chdir(olddir)
60
Andrew Geissler595f6302022-01-24 19:11:47 +000061
Patrick Williamsc124f4f2015-09-15 14:41:29 -050062class PatchError(Exception):
63 def __init__(self, msg):
64 self.msg = msg
65
66 def __str__(self):
67 return "Patch Error: %s" % self.msg
68
69class PatchSet(object):
70 defaults = {
71 "strippath": 1
72 }
73
74 def __init__(self, dir, d):
75 self.dir = dir
76 self.d = d
77 self.patches = []
78 self._current = None
79
80 def current(self):
81 return self._current
82
83 def Clean(self):
84 """
85 Clean out the patch set. Generally includes unapplying all
86 patches and wiping out all associated metadata.
87 """
88 raise NotImplementedError()
89
90 def Import(self, patch, force):
91 if not patch.get("file"):
92 if not patch.get("remote"):
93 raise PatchError("Patch file must be specified in patch import.")
94 else:
95 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
96
97 for param in PatchSet.defaults:
98 if not patch.get(param):
99 patch[param] = PatchSet.defaults[param]
100
101 if patch.get("remote"):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500102 patch["file"] = self.d.expand(bb.fetch2.localpath(patch["remote"], self.d))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500103
104 patch["filemd5"] = bb.utils.md5_file(patch["file"])
105
106 def Push(self, force):
107 raise NotImplementedError()
108
109 def Pop(self, force):
110 raise NotImplementedError()
111
112 def Refresh(self, remote = None, all = None):
113 raise NotImplementedError()
114
115 @staticmethod
116 def getPatchedFiles(patchfile, striplevel, srcdir=None):
117 """
118 Read a patch file and determine which files it will modify.
119 Params:
120 patchfile: the patch file to read
121 striplevel: the strip level at which the patch is going to be applied
122 srcdir: optional path to join onto the patched file paths
123 Returns:
124 A list of tuples of file path and change mode ('A' for add,
125 'D' for delete or 'M' for modify)
126 """
127
128 def patchedpath(patchline):
129 filepth = patchline.split()[1]
130 if filepth.endswith('/dev/null'):
131 return '/dev/null'
132 filesplit = filepth.split(os.sep)
133 if striplevel > len(filesplit):
134 bb.error('Patch %s has invalid strip level %d' % (patchfile, striplevel))
135 return None
136 return os.sep.join(filesplit[striplevel:])
137
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600138 for encoding in ['utf-8', 'latin-1']:
139 try:
140 copiedmode = False
141 filelist = []
142 with open(patchfile) as f:
143 for line in f:
144 if line.startswith('--- '):
145 patchpth = patchedpath(line)
146 if not patchpth:
147 break
148 if copiedmode:
149 addedfile = patchpth
150 else:
151 removedfile = patchpth
152 elif line.startswith('+++ '):
153 addedfile = patchedpath(line)
154 if not addedfile:
155 break
156 elif line.startswith('*** '):
157 copiedmode = True
158 removedfile = patchedpath(line)
159 if not removedfile:
160 break
161 else:
162 removedfile = None
163 addedfile = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500164
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600165 if addedfile and removedfile:
166 if removedfile == '/dev/null':
167 mode = 'A'
168 elif addedfile == '/dev/null':
169 mode = 'D'
170 else:
171 mode = 'M'
172 if srcdir:
173 fullpath = os.path.abspath(os.path.join(srcdir, addedfile))
174 else:
175 fullpath = addedfile
176 filelist.append((fullpath, mode))
177 except UnicodeDecodeError:
178 continue
179 break
180 else:
181 raise PatchError('Unable to decode %s' % patchfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500182
183 return filelist
184
185
186class PatchTree(PatchSet):
187 def __init__(self, dir, d):
188 PatchSet.__init__(self, dir, d)
189 self.patchdir = os.path.join(self.dir, 'patches')
190 self.seriespath = os.path.join(self.dir, 'patches', 'series')
191 bb.utils.mkdirhier(self.patchdir)
192
193 def _appendPatchFile(self, patch, strippath):
194 with open(self.seriespath, 'a') as f:
195 f.write(os.path.basename(patch) + "," + strippath + "\n")
196 shellcmd = ["cat", patch, ">" , self.patchdir + "/" + os.path.basename(patch)]
197 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
198
199 def _removePatch(self, p):
200 patch = {}
201 patch['file'] = p.split(",")[0]
202 patch['strippath'] = p.split(",")[1]
203 self._applypatch(patch, False, True)
204
205 def _removePatchFile(self, all = False):
206 if not os.path.exists(self.seriespath):
207 return
208 with open(self.seriespath, 'r+') as f:
209 patches = f.readlines()
210 if all:
211 for p in reversed(patches):
212 self._removePatch(os.path.join(self.patchdir, p.strip()))
213 patches = []
214 else:
215 self._removePatch(os.path.join(self.patchdir, patches[-1].strip()))
216 patches.pop()
217 with open(self.seriespath, 'w') as f:
218 for p in patches:
219 f.write(p)
Patrick Williams8e7b46e2023-05-01 14:19:06 -0500220
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500221 def Import(self, patch, force = None):
222 """"""
223 PatchSet.Import(self, patch, force)
224
225 if self._current is not None:
226 i = self._current + 1
227 else:
228 i = 0
229 self.patches.insert(i, patch)
230
231 def _applypatch(self, patch, force = False, reverse = False, run = True):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400232 shellcmd = ["cat", patch['file'], "|", "patch", "--no-backup-if-mismatch", "-p", patch['strippath']]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500233 if reverse:
234 shellcmd.append('-R')
235
236 if not run:
237 return "sh" + "-c" + " ".join(shellcmd)
238
239 if not force:
240 shellcmd.append('--dry-run')
241
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500242 try:
243 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500244
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500245 if force:
246 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500247
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500248 shellcmd.pop(len(shellcmd) - 1)
249 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
250 except CmdError as err:
251 raise bb.BBHandledException("Applying '%s' failed:\n%s" %
252 (os.path.basename(patch['file']), err.output))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500253
254 if not reverse:
255 self._appendPatchFile(patch['file'], patch['strippath'])
256
257 return output
258
259 def Push(self, force = False, all = False, run = True):
260 bb.note("self._current is %s" % self._current)
261 bb.note("patches is %s" % self.patches)
262 if all:
263 for i in self.patches:
264 bb.note("applying patch %s" % i)
265 self._applypatch(i, force)
266 self._current = i
267 else:
268 if self._current is not None:
269 next = self._current + 1
270 else:
271 next = 0
272
273 bb.note("applying patch %s" % self.patches[next])
274 ret = self._applypatch(self.patches[next], force)
275
276 self._current = next
277 return ret
278
279 def Pop(self, force = None, all = None):
280 if all:
281 self._removePatchFile(True)
282 self._current = None
283 else:
284 self._removePatchFile(False)
285
286 if self._current == 0:
287 self._current = None
288
289 if self._current is not None:
290 self._current = self._current - 1
291
292 def Clean(self):
293 """"""
294 self.Pop(all=True)
295
296class GitApplyTree(PatchTree):
297 patch_line_prefix = '%% original patch'
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500298 ignore_commit_prefix = '%% ignore'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500299
300 def __init__(self, dir, d):
301 PatchTree.__init__(self, dir, d)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500302 self.commituser = d.getVar('PATCH_GIT_USER_NAME')
303 self.commitemail = d.getVar('PATCH_GIT_USER_EMAIL')
Andrew Geissler615f2f12022-07-15 14:00:58 -0500304 if not self._isInitialized(d):
Andrew Geissler595f6302022-01-24 19:11:47 +0000305 self._initRepo()
306
Andrew Geissler615f2f12022-07-15 14:00:58 -0500307 def _isInitialized(self, d):
Andrew Geissler595f6302022-01-24 19:11:47 +0000308 cmd = "git rev-parse --show-toplevel"
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000309 try:
310 output = runcmd(cmd.split(), self.dir).strip()
311 except CmdError as err:
312 ## runcmd returned non-zero which most likely means 128
313 ## Not a git directory
314 return False
Andrew Geissler615f2f12022-07-15 14:00:58 -0500315 ## Make sure repo is in builddir to not break top-level git repos, or under workdir
316 return os.path.samefile(output, self.dir) or oe.path.is_path_parent(d.getVar('WORKDIR'), output)
Andrew Geissler595f6302022-01-24 19:11:47 +0000317
318 def _initRepo(self):
319 runcmd("git init".split(), self.dir)
320 runcmd("git add .".split(), self.dir)
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000321 runcmd("git commit -a --allow-empty -m bitbake_patching_started".split(), self.dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500322
323 @staticmethod
324 def extractPatchHeader(patchfile):
325 """
326 Extract just the header lines from the top of a patch file
327 """
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600328 for encoding in ['utf-8', 'latin-1']:
329 lines = []
330 try:
331 with open(patchfile, 'r', encoding=encoding) as f:
332 for line in f:
333 if line.startswith('Index: ') or line.startswith('diff -') or line.startswith('---'):
334 break
335 lines.append(line)
336 except UnicodeDecodeError:
337 continue
338 break
339 else:
340 raise PatchError('Unable to find a character encoding to decode %s' % patchfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500341 return lines
342
343 @staticmethod
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500344 def decodeAuthor(line):
345 from email.header import decode_header
346 authorval = line.split(':', 1)[1].strip().replace('"', '')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600347 result = decode_header(authorval)[0][0]
348 if hasattr(result, 'decode'):
349 result = result.decode('utf-8')
350 return result
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500351
352 @staticmethod
353 def interpretPatchHeader(headerlines):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500354 import re
Brad Bishop19323692019-04-05 15:28:33 -0400355 author_re = re.compile(r'[\S ]+ <\S+@\S+\.\S+>')
356 from_commit_re = re.compile(r'^From [a-z0-9]{40} .*')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500357 outlines = []
358 author = None
359 date = None
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500360 subject = None
361 for line in headerlines:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500362 if line.startswith('Subject: '):
363 subject = line.split(':', 1)[1]
364 # Remove any [PATCH][oe-core] etc.
365 subject = re.sub(r'\[.+?\]\s*', '', subject)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500366 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500367 elif line.startswith('From: ') or line.startswith('Author: '):
368 authorval = GitApplyTree.decodeAuthor(line)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500369 # git is fussy about author formatting i.e. it must be Name <email@domain>
370 if author_re.match(authorval):
371 author = authorval
372 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500373 elif line.startswith('Date: '):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500374 if date is None:
375 dateval = line.split(':', 1)[1].strip()
376 # Very crude check for date format, since git will blow up if it's not in the right
377 # format. Without e.g. a python-dateutils dependency we can't do a whole lot more
378 if len(dateval) > 12:
379 date = dateval
380 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500381 elif not author and line.lower().startswith('signed-off-by: '):
382 authorval = GitApplyTree.decodeAuthor(line)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500383 # git is fussy about author formatting i.e. it must be Name <email@domain>
384 if author_re.match(authorval):
385 author = authorval
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600386 elif from_commit_re.match(line):
387 # We don't want the From <commit> line - if it's present it will break rebasing
388 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500389 outlines.append(line)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600390
391 if not subject:
392 firstline = None
393 for line in headerlines:
394 line = line.strip()
395 if firstline:
396 if line:
397 # Second line is not blank, the first line probably isn't usable
398 firstline = None
399 break
400 elif line:
401 firstline = line
402 if firstline and not firstline.startswith(('#', 'Index:', 'Upstream-Status:')) and len(firstline) < 100:
403 subject = firstline
404
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500405 return outlines, author, date, subject
406
407 @staticmethod
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600408 def gitCommandUserOptions(cmd, commituser=None, commitemail=None, d=None):
409 if d:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500410 commituser = d.getVar('PATCH_GIT_USER_NAME')
411 commitemail = d.getVar('PATCH_GIT_USER_EMAIL')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600412 if commituser:
413 cmd += ['-c', 'user.name="%s"' % commituser]
414 if commitemail:
415 cmd += ['-c', 'user.email="%s"' % commitemail]
416
417 @staticmethod
418 def prepareCommit(patchfile, commituser=None, commitemail=None):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500419 """
420 Prepare a git commit command line based on the header from a patch file
421 (typically this is useful for patches that cannot be applied with "git am" due to formatting)
422 """
423 import tempfile
424 # Process patch header and extract useful information
425 lines = GitApplyTree.extractPatchHeader(patchfile)
426 outlines, author, date, subject = GitApplyTree.interpretPatchHeader(lines)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600427 if not author or not subject or not date:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500428 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600429 shellcmd = ["git", "log", "--format=email", "--follow", "--diff-filter=A", "--", patchfile]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500430 out = runcmd(["sh", "-c", " ".join(shellcmd)], os.path.dirname(patchfile))
431 except CmdError:
432 out = None
433 if out:
434 _, newauthor, newdate, newsubject = GitApplyTree.interpretPatchHeader(out.splitlines())
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600435 if not author:
436 # If we're setting the author then the date should be set as well
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500437 author = newauthor
438 date = newdate
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600439 elif not date:
440 # If we don't do this we'll get the current date, at least this will be closer
441 date = newdate
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500442 if not subject:
443 subject = newsubject
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500444 if subject and not (outlines and outlines[0].strip() == subject):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500445 outlines.insert(0, '%s\n\n' % subject.strip())
446
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500447 # Write out commit message to a file
448 with tempfile.NamedTemporaryFile('w', delete=False) as tf:
449 tmpfile = tf.name
450 for line in outlines:
451 tf.write(line)
452 # Prepare git command
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600453 cmd = ["git"]
454 GitApplyTree.gitCommandUserOptions(cmd, commituser, commitemail)
455 cmd += ["commit", "-F", tmpfile]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500456 # git doesn't like plain email addresses as authors
457 if author and '<' in author:
458 cmd.append('--author="%s"' % author)
459 if date:
460 cmd.append('--date="%s"' % date)
461 return (tmpfile, cmd)
462
463 @staticmethod
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500464 def extractPatches(tree, startcommit, outdir, paths=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500465 import tempfile
466 import shutil
467 tempdir = tempfile.mkdtemp(prefix='oepatch')
468 try:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400469 shellcmd = ["git", "format-patch", "--no-signature", "--no-numbered", startcommit, "-o", tempdir]
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500470 if paths:
471 shellcmd.append('--')
472 shellcmd.extend(paths)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500473 out = runcmd(["sh", "-c", " ".join(shellcmd)], tree)
474 if out:
475 for srcfile in out.split():
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600476 for encoding in ['utf-8', 'latin-1']:
477 patchlines = []
478 outfile = None
479 try:
480 with open(srcfile, 'r', encoding=encoding) as f:
481 for line in f:
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500482 if line.startswith(GitApplyTree.patch_line_prefix):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600483 outfile = line.split()[-1].strip()
484 continue
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500485 if line.startswith(GitApplyTree.ignore_commit_prefix):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600486 continue
487 patchlines.append(line)
488 except UnicodeDecodeError:
489 continue
490 break
491 else:
492 raise PatchError('Unable to find a character encoding to decode %s' % srcfile)
493
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500494 if not outfile:
495 outfile = os.path.basename(srcfile)
496 with open(os.path.join(outdir, outfile), 'w') as of:
497 for line in patchlines:
498 of.write(line)
499 finally:
500 shutil.rmtree(tempdir)
501
Patrick Williams8e7b46e2023-05-01 14:19:06 -0500502 def _need_dirty_check(self):
503 fetch = bb.fetch2.Fetch([], self.d)
504 check_dirtyness = False
505 for url in fetch.urls:
506 url_data = fetch.ud[url]
507 parm = url_data.parm
508 # a git url with subpath param will surely be dirty
509 # since the git tree from which we clone will be emptied
510 # from all files that are not in the subpath
511 if url_data.type == 'git' and parm.get('subpath'):
512 check_dirtyness = True
513 return check_dirtyness
514
515 def _commitpatch(self, patch, patchfilevar):
516 output = ""
517 # Add all files
518 shellcmd = ["git", "add", "-f", "-A", "."]
519 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
520 # Exclude the patches directory
521 shellcmd = ["git", "reset", "HEAD", self.patchdir]
522 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
523 # Commit the result
524 (tmpfile, shellcmd) = self.prepareCommit(patch['file'], self.commituser, self.commitemail)
525 try:
526 shellcmd.insert(0, patchfilevar)
527 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
528 finally:
529 os.remove(tmpfile)
530 return output
531
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500532 def _applypatch(self, patch, force = False, reverse = False, run = True):
533 import shutil
534
535 def _applypatchhelper(shellcmd, patch, force = False, reverse = False, run = True):
536 if reverse:
537 shellcmd.append('-R')
538
539 shellcmd.append(patch['file'])
540
541 if not run:
542 return "sh" + "-c" + " ".join(shellcmd)
543
544 return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
545
546 # Add hooks which add a pointer to the original patch file name in the commit message
547 reporoot = (runcmd("git rev-parse --show-toplevel".split(), self.dir) or '').strip()
548 if not reporoot:
549 raise Exception("Cannot get repository root for directory %s" % self.dir)
Andrew Geissler5082cc72023-09-11 08:41:39 -0400550 gitdir = (runcmd("git rev-parse --absolute-git-dir".split(), self.dir) or '').strip()
551 if not gitdir:
552 raise Exception("Cannot get gitdir for directory %s" % self.dir)
553 hooks_dir = os.path.join(gitdir, 'hooks')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500554 hooks_dir_backup = hooks_dir + '.devtool-orig'
555 if os.path.lexists(hooks_dir_backup):
556 raise Exception("Git hooks backup directory already exists: %s" % hooks_dir_backup)
557 if os.path.lexists(hooks_dir):
558 shutil.move(hooks_dir, hooks_dir_backup)
559 os.mkdir(hooks_dir)
560 commithook = os.path.join(hooks_dir, 'commit-msg')
561 applyhook = os.path.join(hooks_dir, 'applypatch-msg')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500562 with open(commithook, 'w') as f:
563 # NOTE: the formatting here is significant; if you change it you'll also need to
564 # change other places which read it back
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500565 f.write('echo "\n%s: $PATCHFILE" >> $1' % GitApplyTree.patch_line_prefix)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600566 os.chmod(commithook, 0o755)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500567 shutil.copy2(commithook, applyhook)
568 try:
569 patchfilevar = 'PATCHFILE="%s"' % os.path.basename(patch['file'])
Patrick Williams8e7b46e2023-05-01 14:19:06 -0500570 if self._need_dirty_check():
571 # Check dirtyness of the tree
572 try:
573 output = runcmd(["git", "--work-tree=%s" % reporoot, "status", "--short"])
574 except CmdError:
575 pass
576 else:
577 if output:
578 # The tree is dirty, not need to try to apply patches with git anymore
579 # since they fail, fallback directly to patch
580 output = PatchTree._applypatch(self, patch, force, reverse, run)
581 output += self._commitpatch(patch, patchfilevar)
582 return output
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500583 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600584 shellcmd = [patchfilevar, "git", "--work-tree=%s" % reporoot]
585 self.gitCommandUserOptions(shellcmd, self.commituser, self.commitemail)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600586 shellcmd += ["am", "-3", "--keep-cr", "--no-scissors", "-p%s" % patch['strippath']]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500587 return _applypatchhelper(shellcmd, patch, force, reverse, run)
588 except CmdError:
589 # Need to abort the git am, or we'll still be within it at the end
590 try:
591 shellcmd = ["git", "--work-tree=%s" % reporoot, "am", "--abort"]
592 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
593 except CmdError:
594 pass
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500595 # git am won't always clean up after itself, sadly, so...
596 shellcmd = ["git", "--work-tree=%s" % reporoot, "reset", "--hard", "HEAD"]
597 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
598 # Also need to take care of any stray untracked files
599 shellcmd = ["git", "--work-tree=%s" % reporoot, "clean", "-f"]
600 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
601
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500602 # Fall back to git apply
603 shellcmd = ["git", "--git-dir=%s" % reporoot, "apply", "-p%s" % patch['strippath']]
604 try:
605 output = _applypatchhelper(shellcmd, patch, force, reverse, run)
606 except CmdError:
607 # Fall back to patch
608 output = PatchTree._applypatch(self, patch, force, reverse, run)
Patrick Williams8e7b46e2023-05-01 14:19:06 -0500609 output += self._commitpatch(patch, patchfilevar)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500610 return output
611 finally:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500612 shutil.rmtree(hooks_dir)
613 if os.path.lexists(hooks_dir_backup):
614 shutil.move(hooks_dir_backup, hooks_dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500615
616
617class QuiltTree(PatchSet):
618 def _runcmd(self, args, run = True):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500619 quiltrc = self.d.getVar('QUILTRCFILE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500620 if not run:
621 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
622 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
623
624 def _quiltpatchpath(self, file):
625 return os.path.join(self.dir, "patches", os.path.basename(file))
626
627
628 def __init__(self, dir, d):
629 PatchSet.__init__(self, dir, d)
630 self.initialized = False
631 p = os.path.join(self.dir, 'patches')
632 if not os.path.exists(p):
633 os.makedirs(p)
634
635 def Clean(self):
636 try:
Andrew Geissler78b72792022-06-14 06:47:25 -0500637 # make sure that patches/series file exists before quilt pop to keep quilt-0.67 happy
638 open(os.path.join(self.dir, "patches","series"), 'a').close()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500639 self._runcmd(["pop", "-a", "-f"])
640 oe.path.remove(os.path.join(self.dir, "patches","series"))
641 except Exception:
642 pass
643 self.initialized = True
644
645 def InitFromDir(self):
646 # read series -> self.patches
647 seriespath = os.path.join(self.dir, 'patches', 'series')
648 if not os.path.exists(self.dir):
649 raise NotFoundError(self.dir)
650 if os.path.exists(seriespath):
651 with open(seriespath, 'r') as f:
652 for line in f.readlines():
653 patch = {}
654 parts = line.strip().split()
655 patch["quiltfile"] = self._quiltpatchpath(parts[0])
656 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
657 if len(parts) > 1:
658 patch["strippath"] = parts[1][2:]
659 self.patches.append(patch)
660
661 # determine which patches are applied -> self._current
662 try:
663 output = runcmd(["quilt", "applied"], self.dir)
664 except CmdError:
665 import sys
666 if sys.exc_value.output.strip() == "No patches applied":
667 return
668 else:
669 raise
670 output = [val for val in output.split('\n') if not val.startswith('#')]
671 for patch in self.patches:
672 if os.path.basename(patch["quiltfile"]) == output[-1]:
673 self._current = self.patches.index(patch)
674 self.initialized = True
675
676 def Import(self, patch, force = None):
677 if not self.initialized:
678 self.InitFromDir()
679 PatchSet.Import(self, patch, force)
680 oe.path.symlink(patch["file"], self._quiltpatchpath(patch["file"]), force=True)
681 with open(os.path.join(self.dir, "patches", "series"), "a") as f:
682 f.write(os.path.basename(patch["file"]) + " -p" + patch["strippath"] + "\n")
683 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
684 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
685
686 # TODO: determine if the file being imported:
687 # 1) is already imported, and is the same
688 # 2) is already imported, but differs
689
690 self.patches.insert(self._current or 0, patch)
691
692
693 def Push(self, force = False, all = False, run = True):
694 # quilt push [-f]
695
696 args = ["push"]
697 if force:
698 args.append("-f")
699 if all:
700 args.append("-a")
701 if not run:
702 return self._runcmd(args, run)
703
704 self._runcmd(args)
705
706 if self._current is not None:
707 self._current = self._current + 1
708 else:
709 self._current = 0
710
711 def Pop(self, force = None, all = None):
712 # quilt pop [-f]
713 args = ["pop"]
714 if force:
715 args.append("-f")
716 if all:
717 args.append("-a")
718
719 self._runcmd(args)
720
721 if self._current == 0:
722 self._current = None
723
724 if self._current is not None:
725 self._current = self._current - 1
726
727 def Refresh(self, **kwargs):
728 if kwargs.get("remote"):
729 patch = self.patches[kwargs["patch"]]
730 if not patch:
731 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
732 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(patch["remote"])
733 if type == "file":
734 import shutil
735 if not patch.get("file") and patch.get("remote"):
736 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
737
738 shutil.copyfile(patch["quiltfile"], patch["file"])
739 else:
740 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
741 else:
742 # quilt refresh
743 args = ["refresh"]
744 if kwargs.get("quiltfile"):
745 args.append(os.path.basename(kwargs["quiltfile"]))
746 elif kwargs.get("patch"):
747 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
748 self._runcmd(args)
749
750class Resolver(object):
751 def __init__(self, patchset, terminal):
752 raise NotImplementedError()
753
754 def Resolve(self):
755 raise NotImplementedError()
756
757 def Revert(self):
758 raise NotImplementedError()
759
760 def Finalize(self):
761 raise NotImplementedError()
762
763class NOOPResolver(Resolver):
764 def __init__(self, patchset, terminal):
765 self.patchset = patchset
766 self.terminal = terminal
767
768 def Resolve(self):
769 olddir = os.path.abspath(os.curdir)
770 os.chdir(self.patchset.dir)
771 try:
772 self.patchset.Push()
773 except Exception:
774 import sys
775 os.chdir(olddir)
776 raise
777
778# Patch resolver which relies on the user doing all the work involved in the
779# resolution, with the exception of refreshing the remote copy of the patch
780# files (the urls).
781class UserResolver(Resolver):
782 def __init__(self, patchset, terminal):
783 self.patchset = patchset
784 self.terminal = terminal
785
786 # Force a push in the patchset, then drop to a shell for the user to
787 # resolve any rejected hunks
788 def Resolve(self):
789 olddir = os.path.abspath(os.curdir)
790 os.chdir(self.patchset.dir)
791 try:
792 self.patchset.Push(False)
793 except CmdError as v:
794 # Patch application failed
795 patchcmd = self.patchset.Push(True, False, False)
796
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500797 t = self.patchset.d.getVar('T')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500798 if not t:
799 bb.msg.fatal("Build", "T not set")
800 bb.utils.mkdirhier(t)
801 import random
802 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
803 with open(rcfile, "w") as f:
804 f.write("echo '*** Manual patch resolution mode ***'\n")
805 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
806 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
807 f.write("echo ''\n")
808 f.write(" ".join(patchcmd) + "\n")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600809 os.chmod(rcfile, 0o775)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500810
811 self.terminal("bash --rcfile " + rcfile, 'Patch Rejects: Please fix patch rejects manually', self.patchset.d)
812
813 # Construct a new PatchSet after the user's changes, compare the
814 # sets, checking patches for modifications, and doing a remote
815 # refresh on each.
816 oldpatchset = self.patchset
817 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
818
819 for patch in self.patchset.patches:
820 oldpatch = None
821 for opatch in oldpatchset.patches:
822 if opatch["quiltfile"] == patch["quiltfile"]:
823 oldpatch = opatch
824
825 if oldpatch:
826 patch["remote"] = oldpatch["remote"]
827 if patch["quiltfile"] == oldpatch["quiltfile"]:
828 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
829 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
830 # user change? remote refresh
831 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
832 else:
833 # User did not fix the problem. Abort.
834 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
835 except Exception:
836 os.chdir(olddir)
837 raise
838 os.chdir(olddir)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500839
840
841def patch_path(url, fetch, workdir, expand=True):
Brad Bishop19323692019-04-05 15:28:33 -0400842 """Return the local path of a patch, or return nothing if this isn't a patch"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500843
844 local = fetch.localpath(url)
Brad Bishop19323692019-04-05 15:28:33 -0400845 if os.path.isdir(local):
846 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500847 base, ext = os.path.splitext(os.path.basename(local))
848 if ext in ('.gz', '.bz2', '.xz', '.Z'):
849 if expand:
850 local = os.path.join(workdir, base)
851 ext = os.path.splitext(base)[1]
852
853 urldata = fetch.ud[url]
854 if "apply" in urldata.parm:
855 apply = oe.types.boolean(urldata.parm["apply"])
856 if not apply:
857 return
858 elif ext not in (".diff", ".patch"):
859 return
860
861 return local
862
863def src_patches(d, all=False, expand=True):
864 workdir = d.getVar('WORKDIR')
865 fetch = bb.fetch2.Fetch([], d)
866 patches = []
867 sources = []
868 for url in fetch.urls:
869 local = patch_path(url, fetch, workdir, expand)
870 if not local:
871 if all:
872 local = fetch.localpath(url)
873 sources.append(local)
874 continue
875
876 urldata = fetch.ud[url]
877 parm = urldata.parm
878 patchname = parm.get('pname') or os.path.basename(local)
879
880 apply, reason = should_apply(parm, d)
881 if not apply:
882 if reason:
883 bb.note("Patch %s %s" % (patchname, reason))
884 continue
885
886 patchparm = {'patchname': patchname}
887 if "striplevel" in parm:
888 striplevel = parm["striplevel"]
889 elif "pnum" in parm:
890 #bb.msg.warn(None, "Deprecated usage of 'pnum' url parameter in '%s', please use 'striplevel'" % url)
891 striplevel = parm["pnum"]
892 else:
893 striplevel = '1'
894 patchparm['striplevel'] = striplevel
895
896 patchdir = parm.get('patchdir')
897 if patchdir:
898 patchparm['patchdir'] = patchdir
899
900 localurl = bb.fetch.encodeurl(('file', '', local, '', '', patchparm))
901 patches.append(localurl)
902
903 if all:
904 return sources
905
906 return patches
907
908
909def should_apply(parm, d):
Brad Bishopc342db32019-05-15 21:57:59 -0400910 import bb.utils
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500911 if "mindate" in parm or "maxdate" in parm:
912 pn = d.getVar('PN')
913 srcdate = d.getVar('SRCDATE_%s' % pn)
914 if not srcdate:
915 srcdate = d.getVar('SRCDATE')
916
917 if srcdate == "now":
918 srcdate = d.getVar('DATE')
919
920 if "maxdate" in parm and parm["maxdate"] < srcdate:
921 return False, 'is outdated'
922
923 if "mindate" in parm and parm["mindate"] > srcdate:
924 return False, 'is predated'
925
926
927 if "minrev" in parm:
928 srcrev = d.getVar('SRCREV')
929 if srcrev and srcrev < parm["minrev"]:
930 return False, 'applies to later revisions'
931
932 if "maxrev" in parm:
933 srcrev = d.getVar('SRCREV')
934 if srcrev and srcrev > parm["maxrev"]:
935 return False, 'applies to earlier revisions'
936
937 if "rev" in parm:
938 srcrev = d.getVar('SRCREV')
939 if srcrev and parm["rev"] not in srcrev:
940 return False, "doesn't apply to revision"
941
942 if "notrev" in parm:
943 srcrev = d.getVar('SRCREV')
944 if srcrev and parm["notrev"] in srcrev:
945 return False, "doesn't apply to revision"
946
Brad Bishopc342db32019-05-15 21:57:59 -0400947 if "maxver" in parm:
948 pv = d.getVar('PV')
949 if bb.utils.vercmp_string_op(pv, parm["maxver"], ">"):
950 return False, "applies to earlier version"
951
952 if "minver" in parm:
953 pv = d.getVar('PV')
954 if bb.utils.vercmp_string_op(pv, parm["minver"], "<"):
955 return False, "applies to later version"
956
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500957 return True, None