blob: 950fe723dcfdc92b366faf7138d903bc401c9e37 [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
Andrew Geissler595f6302022-01-24 19:11:47 +00007import subprocess
Patrick Williamsc124f4f2015-09-15 14:41:29 -05008
9class NotFoundError(bb.BBHandledException):
10 def __init__(self, path):
11 self.path = path
12
13 def __str__(self):
14 return "Error: %s not found." % self.path
15
16class CmdError(bb.BBHandledException):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050017 def __init__(self, command, exitstatus, output):
18 self.command = command
Patrick Williamsc124f4f2015-09-15 14:41:29 -050019 self.status = exitstatus
20 self.output = output
21
22 def __str__(self):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050023 return "Command Error: '%s' exited with %d Output:\n%s" % \
24 (self.command, self.status, self.output)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025
26
27def runcmd(args, dir = None):
28 import pipes
29
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)
Andrew Geisslerd1e89492021-02-12 15:35:20 -060041 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
42 stdout, stderr = proc.communicate()
43 stdout = stdout.decode('utf-8')
44 stderr = stderr.decode('utf-8')
45 exitstatus = proc.returncode
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046 if exitstatus != 0:
Andrew Geisslerd1e89492021-02-12 15:35:20 -060047 raise CmdError(cmd, exitstatus >> 8, "stdout: %s\nstderr: %s" % (stdout, stderr))
48 if " fuzz " in stdout and "Hunk " in stdout:
Brad Bishopd89cb5f2019-04-10 09:02:41 -040049 # Drop patch fuzz info with header and footer to log file so
50 # insane.bbclass can handle to throw error/warning
Andrew Geisslerd1e89492021-02-12 15:35:20 -060051 bb.note("--- Patch fuzz start ---\n%s\n--- Patch fuzz end ---" % format(stdout))
Brad Bishop316dfdd2018-06-25 12:45:53 -040052
Andrew Geisslerd1e89492021-02-12 15:35:20 -060053 return stdout
Patrick Williamsc124f4f2015-09-15 14:41:29 -050054
55 finally:
56 if dir:
57 os.chdir(olddir)
58
Andrew Geissler595f6302022-01-24 19:11:47 +000059
Patrick Williamsc124f4f2015-09-15 14:41:29 -050060class PatchError(Exception):
61 def __init__(self, msg):
62 self.msg = msg
63
64 def __str__(self):
65 return "Patch Error: %s" % self.msg
66
67class PatchSet(object):
68 defaults = {
69 "strippath": 1
70 }
71
72 def __init__(self, dir, d):
73 self.dir = dir
74 self.d = d
75 self.patches = []
76 self._current = None
77
78 def current(self):
79 return self._current
80
81 def Clean(self):
82 """
83 Clean out the patch set. Generally includes unapplying all
84 patches and wiping out all associated metadata.
85 """
86 raise NotImplementedError()
87
88 def Import(self, patch, force):
89 if not patch.get("file"):
90 if not patch.get("remote"):
91 raise PatchError("Patch file must be specified in patch import.")
92 else:
93 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
94
95 for param in PatchSet.defaults:
96 if not patch.get(param):
97 patch[param] = PatchSet.defaults[param]
98
99 if patch.get("remote"):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500100 patch["file"] = self.d.expand(bb.fetch2.localpath(patch["remote"], self.d))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500101
102 patch["filemd5"] = bb.utils.md5_file(patch["file"])
103
104 def Push(self, force):
105 raise NotImplementedError()
106
107 def Pop(self, force):
108 raise NotImplementedError()
109
110 def Refresh(self, remote = None, all = None):
111 raise NotImplementedError()
112
113 @staticmethod
114 def getPatchedFiles(patchfile, striplevel, srcdir=None):
115 """
116 Read a patch file and determine which files it will modify.
117 Params:
118 patchfile: the patch file to read
119 striplevel: the strip level at which the patch is going to be applied
120 srcdir: optional path to join onto the patched file paths
121 Returns:
122 A list of tuples of file path and change mode ('A' for add,
123 'D' for delete or 'M' for modify)
124 """
125
126 def patchedpath(patchline):
127 filepth = patchline.split()[1]
128 if filepth.endswith('/dev/null'):
129 return '/dev/null'
130 filesplit = filepth.split(os.sep)
131 if striplevel > len(filesplit):
132 bb.error('Patch %s has invalid strip level %d' % (patchfile, striplevel))
133 return None
134 return os.sep.join(filesplit[striplevel:])
135
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600136 for encoding in ['utf-8', 'latin-1']:
137 try:
138 copiedmode = False
139 filelist = []
140 with open(patchfile) as f:
141 for line in f:
142 if line.startswith('--- '):
143 patchpth = patchedpath(line)
144 if not patchpth:
145 break
146 if copiedmode:
147 addedfile = patchpth
148 else:
149 removedfile = patchpth
150 elif line.startswith('+++ '):
151 addedfile = patchedpath(line)
152 if not addedfile:
153 break
154 elif line.startswith('*** '):
155 copiedmode = True
156 removedfile = patchedpath(line)
157 if not removedfile:
158 break
159 else:
160 removedfile = None
161 addedfile = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500162
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600163 if addedfile and removedfile:
164 if removedfile == '/dev/null':
165 mode = 'A'
166 elif addedfile == '/dev/null':
167 mode = 'D'
168 else:
169 mode = 'M'
170 if srcdir:
171 fullpath = os.path.abspath(os.path.join(srcdir, addedfile))
172 else:
173 fullpath = addedfile
174 filelist.append((fullpath, mode))
175 except UnicodeDecodeError:
176 continue
177 break
178 else:
179 raise PatchError('Unable to decode %s' % patchfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180
181 return filelist
182
183
184class PatchTree(PatchSet):
185 def __init__(self, dir, d):
186 PatchSet.__init__(self, dir, d)
187 self.patchdir = os.path.join(self.dir, 'patches')
188 self.seriespath = os.path.join(self.dir, 'patches', 'series')
189 bb.utils.mkdirhier(self.patchdir)
190
191 def _appendPatchFile(self, patch, strippath):
192 with open(self.seriespath, 'a') as f:
193 f.write(os.path.basename(patch) + "," + strippath + "\n")
194 shellcmd = ["cat", patch, ">" , self.patchdir + "/" + os.path.basename(patch)]
195 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
196
197 def _removePatch(self, p):
198 patch = {}
199 patch['file'] = p.split(",")[0]
200 patch['strippath'] = p.split(",")[1]
201 self._applypatch(patch, False, True)
202
203 def _removePatchFile(self, all = False):
204 if not os.path.exists(self.seriespath):
205 return
206 with open(self.seriespath, 'r+') as f:
207 patches = f.readlines()
208 if all:
209 for p in reversed(patches):
210 self._removePatch(os.path.join(self.patchdir, p.strip()))
211 patches = []
212 else:
213 self._removePatch(os.path.join(self.patchdir, patches[-1].strip()))
214 patches.pop()
215 with open(self.seriespath, 'w') as f:
216 for p in patches:
217 f.write(p)
218
219 def Import(self, patch, force = None):
220 """"""
221 PatchSet.Import(self, patch, force)
222
223 if self._current is not None:
224 i = self._current + 1
225 else:
226 i = 0
227 self.patches.insert(i, patch)
228
229 def _applypatch(self, patch, force = False, reverse = False, run = True):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400230 shellcmd = ["cat", patch['file'], "|", "patch", "--no-backup-if-mismatch", "-p", patch['strippath']]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500231 if reverse:
232 shellcmd.append('-R')
233
234 if not run:
235 return "sh" + "-c" + " ".join(shellcmd)
236
237 if not force:
238 shellcmd.append('--dry-run')
239
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500240 try:
241 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500242
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500243 if force:
244 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500245
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500246 shellcmd.pop(len(shellcmd) - 1)
247 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
248 except CmdError as err:
249 raise bb.BBHandledException("Applying '%s' failed:\n%s" %
250 (os.path.basename(patch['file']), err.output))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500251
252 if not reverse:
253 self._appendPatchFile(patch['file'], patch['strippath'])
254
255 return output
256
257 def Push(self, force = False, all = False, run = True):
258 bb.note("self._current is %s" % self._current)
259 bb.note("patches is %s" % self.patches)
260 if all:
261 for i in self.patches:
262 bb.note("applying patch %s" % i)
263 self._applypatch(i, force)
264 self._current = i
265 else:
266 if self._current is not None:
267 next = self._current + 1
268 else:
269 next = 0
270
271 bb.note("applying patch %s" % self.patches[next])
272 ret = self._applypatch(self.patches[next], force)
273
274 self._current = next
275 return ret
276
277 def Pop(self, force = None, all = None):
278 if all:
279 self._removePatchFile(True)
280 self._current = None
281 else:
282 self._removePatchFile(False)
283
284 if self._current == 0:
285 self._current = None
286
287 if self._current is not None:
288 self._current = self._current - 1
289
290 def Clean(self):
291 """"""
292 self.Pop(all=True)
293
294class GitApplyTree(PatchTree):
295 patch_line_prefix = '%% original patch'
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500296 ignore_commit_prefix = '%% ignore'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500297
298 def __init__(self, dir, d):
299 PatchTree.__init__(self, dir, d)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500300 self.commituser = d.getVar('PATCH_GIT_USER_NAME')
301 self.commitemail = d.getVar('PATCH_GIT_USER_EMAIL')
Andrew Geissler595f6302022-01-24 19:11:47 +0000302 if not self._isInitialized():
303 self._initRepo()
304
305 def _isInitialized(self):
306 cmd = "git rev-parse --show-toplevel"
307 (status, output) = subprocess.getstatusoutput(cmd.split())
308 ## Make sure repo is in builddir to not break top-level git repos
309 return status == 0 and os.path.samedir(output, self.dir)
310
311 def _initRepo(self):
312 runcmd("git init".split(), self.dir)
313 runcmd("git add .".split(), self.dir)
314 runcmd("git commit -a --allow-empty -m Patching_started".split(), self.dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500315
316 @staticmethod
317 def extractPatchHeader(patchfile):
318 """
319 Extract just the header lines from the top of a patch file
320 """
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600321 for encoding in ['utf-8', 'latin-1']:
322 lines = []
323 try:
324 with open(patchfile, 'r', encoding=encoding) as f:
325 for line in f:
326 if line.startswith('Index: ') or line.startswith('diff -') or line.startswith('---'):
327 break
328 lines.append(line)
329 except UnicodeDecodeError:
330 continue
331 break
332 else:
333 raise PatchError('Unable to find a character encoding to decode %s' % patchfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500334 return lines
335
336 @staticmethod
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500337 def decodeAuthor(line):
338 from email.header import decode_header
339 authorval = line.split(':', 1)[1].strip().replace('"', '')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600340 result = decode_header(authorval)[0][0]
341 if hasattr(result, 'decode'):
342 result = result.decode('utf-8')
343 return result
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500344
345 @staticmethod
346 def interpretPatchHeader(headerlines):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347 import re
Brad Bishop19323692019-04-05 15:28:33 -0400348 author_re = re.compile(r'[\S ]+ <\S+@\S+\.\S+>')
349 from_commit_re = re.compile(r'^From [a-z0-9]{40} .*')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500350 outlines = []
351 author = None
352 date = None
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500353 subject = None
354 for line in headerlines:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500355 if line.startswith('Subject: '):
356 subject = line.split(':', 1)[1]
357 # Remove any [PATCH][oe-core] etc.
358 subject = re.sub(r'\[.+?\]\s*', '', subject)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500359 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500360 elif line.startswith('From: ') or line.startswith('Author: '):
361 authorval = GitApplyTree.decodeAuthor(line)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500362 # git is fussy about author formatting i.e. it must be Name <email@domain>
363 if author_re.match(authorval):
364 author = authorval
365 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500366 elif line.startswith('Date: '):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500367 if date is None:
368 dateval = line.split(':', 1)[1].strip()
369 # Very crude check for date format, since git will blow up if it's not in the right
370 # format. Without e.g. a python-dateutils dependency we can't do a whole lot more
371 if len(dateval) > 12:
372 date = dateval
373 continue
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500374 elif not author and line.lower().startswith('signed-off-by: '):
375 authorval = GitApplyTree.decodeAuthor(line)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500376 # git is fussy about author formatting i.e. it must be Name <email@domain>
377 if author_re.match(authorval):
378 author = authorval
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600379 elif from_commit_re.match(line):
380 # We don't want the From <commit> line - if it's present it will break rebasing
381 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500382 outlines.append(line)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600383
384 if not subject:
385 firstline = None
386 for line in headerlines:
387 line = line.strip()
388 if firstline:
389 if line:
390 # Second line is not blank, the first line probably isn't usable
391 firstline = None
392 break
393 elif line:
394 firstline = line
395 if firstline and not firstline.startswith(('#', 'Index:', 'Upstream-Status:')) and len(firstline) < 100:
396 subject = firstline
397
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500398 return outlines, author, date, subject
399
400 @staticmethod
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600401 def gitCommandUserOptions(cmd, commituser=None, commitemail=None, d=None):
402 if d:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500403 commituser = d.getVar('PATCH_GIT_USER_NAME')
404 commitemail = d.getVar('PATCH_GIT_USER_EMAIL')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600405 if commituser:
406 cmd += ['-c', 'user.name="%s"' % commituser]
407 if commitemail:
408 cmd += ['-c', 'user.email="%s"' % commitemail]
409
410 @staticmethod
411 def prepareCommit(patchfile, commituser=None, commitemail=None):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500412 """
413 Prepare a git commit command line based on the header from a patch file
414 (typically this is useful for patches that cannot be applied with "git am" due to formatting)
415 """
416 import tempfile
417 # Process patch header and extract useful information
418 lines = GitApplyTree.extractPatchHeader(patchfile)
419 outlines, author, date, subject = GitApplyTree.interpretPatchHeader(lines)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600420 if not author or not subject or not date:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500421 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600422 shellcmd = ["git", "log", "--format=email", "--follow", "--diff-filter=A", "--", patchfile]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500423 out = runcmd(["sh", "-c", " ".join(shellcmd)], os.path.dirname(patchfile))
424 except CmdError:
425 out = None
426 if out:
427 _, newauthor, newdate, newsubject = GitApplyTree.interpretPatchHeader(out.splitlines())
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600428 if not author:
429 # If we're setting the author then the date should be set as well
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500430 author = newauthor
431 date = newdate
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600432 elif not date:
433 # If we don't do this we'll get the current date, at least this will be closer
434 date = newdate
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500435 if not subject:
436 subject = newsubject
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500437 if subject and not (outlines and outlines[0].strip() == subject):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500438 outlines.insert(0, '%s\n\n' % subject.strip())
439
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500440 # Write out commit message to a file
441 with tempfile.NamedTemporaryFile('w', delete=False) as tf:
442 tmpfile = tf.name
443 for line in outlines:
444 tf.write(line)
445 # Prepare git command
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600446 cmd = ["git"]
447 GitApplyTree.gitCommandUserOptions(cmd, commituser, commitemail)
448 cmd += ["commit", "-F", tmpfile]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500449 # git doesn't like plain email addresses as authors
450 if author and '<' in author:
451 cmd.append('--author="%s"' % author)
452 if date:
453 cmd.append('--date="%s"' % date)
454 return (tmpfile, cmd)
455
456 @staticmethod
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500457 def extractPatches(tree, startcommit, outdir, paths=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500458 import tempfile
459 import shutil
460 tempdir = tempfile.mkdtemp(prefix='oepatch')
461 try:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400462 shellcmd = ["git", "format-patch", "--no-signature", "--no-numbered", startcommit, "-o", tempdir]
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500463 if paths:
464 shellcmd.append('--')
465 shellcmd.extend(paths)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500466 out = runcmd(["sh", "-c", " ".join(shellcmd)], tree)
467 if out:
468 for srcfile in out.split():
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600469 for encoding in ['utf-8', 'latin-1']:
470 patchlines = []
471 outfile = None
472 try:
473 with open(srcfile, 'r', encoding=encoding) as f:
474 for line in f:
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500475 if line.startswith(GitApplyTree.patch_line_prefix):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600476 outfile = line.split()[-1].strip()
477 continue
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500478 if line.startswith(GitApplyTree.ignore_commit_prefix):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600479 continue
480 patchlines.append(line)
481 except UnicodeDecodeError:
482 continue
483 break
484 else:
485 raise PatchError('Unable to find a character encoding to decode %s' % srcfile)
486
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500487 if not outfile:
488 outfile = os.path.basename(srcfile)
489 with open(os.path.join(outdir, outfile), 'w') as of:
490 for line in patchlines:
491 of.write(line)
492 finally:
493 shutil.rmtree(tempdir)
494
495 def _applypatch(self, patch, force = False, reverse = False, run = True):
496 import shutil
497
498 def _applypatchhelper(shellcmd, patch, force = False, reverse = False, run = True):
499 if reverse:
500 shellcmd.append('-R')
501
502 shellcmd.append(patch['file'])
503
504 if not run:
505 return "sh" + "-c" + " ".join(shellcmd)
506
507 return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
508
509 # Add hooks which add a pointer to the original patch file name in the commit message
510 reporoot = (runcmd("git rev-parse --show-toplevel".split(), self.dir) or '').strip()
511 if not reporoot:
512 raise Exception("Cannot get repository root for directory %s" % self.dir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500513 hooks_dir = os.path.join(reporoot, '.git', 'hooks')
514 hooks_dir_backup = hooks_dir + '.devtool-orig'
515 if os.path.lexists(hooks_dir_backup):
516 raise Exception("Git hooks backup directory already exists: %s" % hooks_dir_backup)
517 if os.path.lexists(hooks_dir):
518 shutil.move(hooks_dir, hooks_dir_backup)
519 os.mkdir(hooks_dir)
520 commithook = os.path.join(hooks_dir, 'commit-msg')
521 applyhook = os.path.join(hooks_dir, 'applypatch-msg')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500522 with open(commithook, 'w') as f:
523 # NOTE: the formatting here is significant; if you change it you'll also need to
524 # change other places which read it back
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500525 f.write('echo "\n%s: $PATCHFILE" >> $1' % GitApplyTree.patch_line_prefix)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600526 os.chmod(commithook, 0o755)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500527 shutil.copy2(commithook, applyhook)
528 try:
529 patchfilevar = 'PATCHFILE="%s"' % os.path.basename(patch['file'])
530 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600531 shellcmd = [patchfilevar, "git", "--work-tree=%s" % reporoot]
532 self.gitCommandUserOptions(shellcmd, self.commituser, self.commitemail)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600533 shellcmd += ["am", "-3", "--keep-cr", "--no-scissors", "-p%s" % patch['strippath']]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500534 return _applypatchhelper(shellcmd, patch, force, reverse, run)
535 except CmdError:
536 # Need to abort the git am, or we'll still be within it at the end
537 try:
538 shellcmd = ["git", "--work-tree=%s" % reporoot, "am", "--abort"]
539 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
540 except CmdError:
541 pass
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500542 # git am won't always clean up after itself, sadly, so...
543 shellcmd = ["git", "--work-tree=%s" % reporoot, "reset", "--hard", "HEAD"]
544 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
545 # Also need to take care of any stray untracked files
546 shellcmd = ["git", "--work-tree=%s" % reporoot, "clean", "-f"]
547 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
548
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500549 # Fall back to git apply
550 shellcmd = ["git", "--git-dir=%s" % reporoot, "apply", "-p%s" % patch['strippath']]
551 try:
552 output = _applypatchhelper(shellcmd, patch, force, reverse, run)
553 except CmdError:
554 # Fall back to patch
555 output = PatchTree._applypatch(self, patch, force, reverse, run)
556 # Add all files
557 shellcmd = ["git", "add", "-f", "-A", "."]
558 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
559 # Exclude the patches directory
560 shellcmd = ["git", "reset", "HEAD", self.patchdir]
561 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
562 # Commit the result
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600563 (tmpfile, shellcmd) = self.prepareCommit(patch['file'], self.commituser, self.commitemail)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500564 try:
565 shellcmd.insert(0, patchfilevar)
566 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
567 finally:
568 os.remove(tmpfile)
569 return output
570 finally:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500571 shutil.rmtree(hooks_dir)
572 if os.path.lexists(hooks_dir_backup):
573 shutil.move(hooks_dir_backup, hooks_dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500574
575
576class QuiltTree(PatchSet):
577 def _runcmd(self, args, run = True):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500578 quiltrc = self.d.getVar('QUILTRCFILE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500579 if not run:
580 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
581 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
582
583 def _quiltpatchpath(self, file):
584 return os.path.join(self.dir, "patches", os.path.basename(file))
585
586
587 def __init__(self, dir, d):
588 PatchSet.__init__(self, dir, d)
589 self.initialized = False
590 p = os.path.join(self.dir, 'patches')
591 if not os.path.exists(p):
592 os.makedirs(p)
593
594 def Clean(self):
595 try:
596 self._runcmd(["pop", "-a", "-f"])
597 oe.path.remove(os.path.join(self.dir, "patches","series"))
598 except Exception:
599 pass
600 self.initialized = True
601
602 def InitFromDir(self):
603 # read series -> self.patches
604 seriespath = os.path.join(self.dir, 'patches', 'series')
605 if not os.path.exists(self.dir):
606 raise NotFoundError(self.dir)
607 if os.path.exists(seriespath):
608 with open(seriespath, 'r') as f:
609 for line in f.readlines():
610 patch = {}
611 parts = line.strip().split()
612 patch["quiltfile"] = self._quiltpatchpath(parts[0])
613 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
614 if len(parts) > 1:
615 patch["strippath"] = parts[1][2:]
616 self.patches.append(patch)
617
618 # determine which patches are applied -> self._current
619 try:
620 output = runcmd(["quilt", "applied"], self.dir)
621 except CmdError:
622 import sys
623 if sys.exc_value.output.strip() == "No patches applied":
624 return
625 else:
626 raise
627 output = [val for val in output.split('\n') if not val.startswith('#')]
628 for patch in self.patches:
629 if os.path.basename(patch["quiltfile"]) == output[-1]:
630 self._current = self.patches.index(patch)
631 self.initialized = True
632
633 def Import(self, patch, force = None):
634 if not self.initialized:
635 self.InitFromDir()
636 PatchSet.Import(self, patch, force)
637 oe.path.symlink(patch["file"], self._quiltpatchpath(patch["file"]), force=True)
638 with open(os.path.join(self.dir, "patches", "series"), "a") as f:
639 f.write(os.path.basename(patch["file"]) + " -p" + patch["strippath"] + "\n")
640 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
641 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
642
643 # TODO: determine if the file being imported:
644 # 1) is already imported, and is the same
645 # 2) is already imported, but differs
646
647 self.patches.insert(self._current or 0, patch)
648
649
650 def Push(self, force = False, all = False, run = True):
651 # quilt push [-f]
652
653 args = ["push"]
654 if force:
655 args.append("-f")
656 if all:
657 args.append("-a")
658 if not run:
659 return self._runcmd(args, run)
660
661 self._runcmd(args)
662
663 if self._current is not None:
664 self._current = self._current + 1
665 else:
666 self._current = 0
667
668 def Pop(self, force = None, all = None):
669 # quilt pop [-f]
670 args = ["pop"]
671 if force:
672 args.append("-f")
673 if all:
674 args.append("-a")
675
676 self._runcmd(args)
677
678 if self._current == 0:
679 self._current = None
680
681 if self._current is not None:
682 self._current = self._current - 1
683
684 def Refresh(self, **kwargs):
685 if kwargs.get("remote"):
686 patch = self.patches[kwargs["patch"]]
687 if not patch:
688 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
689 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(patch["remote"])
690 if type == "file":
691 import shutil
692 if not patch.get("file") and patch.get("remote"):
693 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
694
695 shutil.copyfile(patch["quiltfile"], patch["file"])
696 else:
697 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
698 else:
699 # quilt refresh
700 args = ["refresh"]
701 if kwargs.get("quiltfile"):
702 args.append(os.path.basename(kwargs["quiltfile"]))
703 elif kwargs.get("patch"):
704 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
705 self._runcmd(args)
706
707class Resolver(object):
708 def __init__(self, patchset, terminal):
709 raise NotImplementedError()
710
711 def Resolve(self):
712 raise NotImplementedError()
713
714 def Revert(self):
715 raise NotImplementedError()
716
717 def Finalize(self):
718 raise NotImplementedError()
719
720class NOOPResolver(Resolver):
721 def __init__(self, patchset, terminal):
722 self.patchset = patchset
723 self.terminal = terminal
724
725 def Resolve(self):
726 olddir = os.path.abspath(os.curdir)
727 os.chdir(self.patchset.dir)
728 try:
729 self.patchset.Push()
730 except Exception:
731 import sys
732 os.chdir(olddir)
733 raise
734
735# Patch resolver which relies on the user doing all the work involved in the
736# resolution, with the exception of refreshing the remote copy of the patch
737# files (the urls).
738class UserResolver(Resolver):
739 def __init__(self, patchset, terminal):
740 self.patchset = patchset
741 self.terminal = terminal
742
743 # Force a push in the patchset, then drop to a shell for the user to
744 # resolve any rejected hunks
745 def Resolve(self):
746 olddir = os.path.abspath(os.curdir)
747 os.chdir(self.patchset.dir)
748 try:
749 self.patchset.Push(False)
750 except CmdError as v:
751 # Patch application failed
752 patchcmd = self.patchset.Push(True, False, False)
753
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500754 t = self.patchset.d.getVar('T')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500755 if not t:
756 bb.msg.fatal("Build", "T not set")
757 bb.utils.mkdirhier(t)
758 import random
759 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
760 with open(rcfile, "w") as f:
761 f.write("echo '*** Manual patch resolution mode ***'\n")
762 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
763 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
764 f.write("echo ''\n")
765 f.write(" ".join(patchcmd) + "\n")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600766 os.chmod(rcfile, 0o775)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500767
768 self.terminal("bash --rcfile " + rcfile, 'Patch Rejects: Please fix patch rejects manually', self.patchset.d)
769
770 # Construct a new PatchSet after the user's changes, compare the
771 # sets, checking patches for modifications, and doing a remote
772 # refresh on each.
773 oldpatchset = self.patchset
774 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
775
776 for patch in self.patchset.patches:
777 oldpatch = None
778 for opatch in oldpatchset.patches:
779 if opatch["quiltfile"] == patch["quiltfile"]:
780 oldpatch = opatch
781
782 if oldpatch:
783 patch["remote"] = oldpatch["remote"]
784 if patch["quiltfile"] == oldpatch["quiltfile"]:
785 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
786 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
787 # user change? remote refresh
788 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
789 else:
790 # User did not fix the problem. Abort.
791 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
792 except Exception:
793 os.chdir(olddir)
794 raise
795 os.chdir(olddir)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500796
797
798def patch_path(url, fetch, workdir, expand=True):
Brad Bishop19323692019-04-05 15:28:33 -0400799 """Return the local path of a patch, or return nothing if this isn't a patch"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500800
801 local = fetch.localpath(url)
Brad Bishop19323692019-04-05 15:28:33 -0400802 if os.path.isdir(local):
803 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500804 base, ext = os.path.splitext(os.path.basename(local))
805 if ext in ('.gz', '.bz2', '.xz', '.Z'):
806 if expand:
807 local = os.path.join(workdir, base)
808 ext = os.path.splitext(base)[1]
809
810 urldata = fetch.ud[url]
811 if "apply" in urldata.parm:
812 apply = oe.types.boolean(urldata.parm["apply"])
813 if not apply:
814 return
815 elif ext not in (".diff", ".patch"):
816 return
817
818 return local
819
820def src_patches(d, all=False, expand=True):
821 workdir = d.getVar('WORKDIR')
822 fetch = bb.fetch2.Fetch([], d)
823 patches = []
824 sources = []
825 for url in fetch.urls:
826 local = patch_path(url, fetch, workdir, expand)
827 if not local:
828 if all:
829 local = fetch.localpath(url)
830 sources.append(local)
831 continue
832
833 urldata = fetch.ud[url]
834 parm = urldata.parm
835 patchname = parm.get('pname') or os.path.basename(local)
836
837 apply, reason = should_apply(parm, d)
838 if not apply:
839 if reason:
840 bb.note("Patch %s %s" % (patchname, reason))
841 continue
842
843 patchparm = {'patchname': patchname}
844 if "striplevel" in parm:
845 striplevel = parm["striplevel"]
846 elif "pnum" in parm:
847 #bb.msg.warn(None, "Deprecated usage of 'pnum' url parameter in '%s', please use 'striplevel'" % url)
848 striplevel = parm["pnum"]
849 else:
850 striplevel = '1'
851 patchparm['striplevel'] = striplevel
852
853 patchdir = parm.get('patchdir')
854 if patchdir:
855 patchparm['patchdir'] = patchdir
856
857 localurl = bb.fetch.encodeurl(('file', '', local, '', '', patchparm))
858 patches.append(localurl)
859
860 if all:
861 return sources
862
863 return patches
864
865
866def should_apply(parm, d):
Brad Bishopc342db32019-05-15 21:57:59 -0400867 import bb.utils
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500868 if "mindate" in parm or "maxdate" in parm:
869 pn = d.getVar('PN')
870 srcdate = d.getVar('SRCDATE_%s' % pn)
871 if not srcdate:
872 srcdate = d.getVar('SRCDATE')
873
874 if srcdate == "now":
875 srcdate = d.getVar('DATE')
876
877 if "maxdate" in parm and parm["maxdate"] < srcdate:
878 return False, 'is outdated'
879
880 if "mindate" in parm and parm["mindate"] > srcdate:
881 return False, 'is predated'
882
883
884 if "minrev" in parm:
885 srcrev = d.getVar('SRCREV')
886 if srcrev and srcrev < parm["minrev"]:
887 return False, 'applies to later revisions'
888
889 if "maxrev" in parm:
890 srcrev = d.getVar('SRCREV')
891 if srcrev and srcrev > parm["maxrev"]:
892 return False, 'applies to earlier revisions'
893
894 if "rev" in parm:
895 srcrev = d.getVar('SRCREV')
896 if srcrev and parm["rev"] not in srcrev:
897 return False, "doesn't apply to revision"
898
899 if "notrev" in parm:
900 srcrev = d.getVar('SRCREV')
901 if srcrev and parm["notrev"] in srcrev:
902 return False, "doesn't apply to revision"
903
Brad Bishopc342db32019-05-15 21:57:59 -0400904 if "maxver" in parm:
905 pv = d.getVar('PV')
906 if bb.utils.vercmp_string_op(pv, parm["maxver"], ">"):
907 return False, "applies to earlier version"
908
909 if "minver" in parm:
910 pv = d.getVar('PV')
911 if bb.utils.vercmp_string_op(pv, parm["minver"], "<"):
912 return False, "applies to later version"
913
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500914 return True, None
915