blob: 108bf1de564b9629f323e6650ecee5b413d45752 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001import oe.path
2
3class NotFoundError(bb.BBHandledException):
4 def __init__(self, path):
5 self.path = path
6
7 def __str__(self):
8 return "Error: %s not found." % self.path
9
10class CmdError(bb.BBHandledException):
11 def __init__(self, exitstatus, output):
12 self.status = exitstatus
13 self.output = output
14
15 def __str__(self):
16 return "Command Error: exit status: %d Output:\n%s" % (self.status, self.output)
17
18
19def runcmd(args, dir = None):
20 import pipes
21
22 if dir:
23 olddir = os.path.abspath(os.curdir)
24 if not os.path.exists(dir):
25 raise NotFoundError(dir)
26 os.chdir(dir)
27 # print("cwd: %s -> %s" % (olddir, dir))
28
29 try:
30 args = [ pipes.quote(str(arg)) for arg in args ]
31 cmd = " ".join(args)
32 # print("cmd: %s" % cmd)
33 (exitstatus, output) = oe.utils.getstatusoutput(cmd)
34 if exitstatus != 0:
35 raise CmdError(exitstatus >> 8, output)
36 return output
37
38 finally:
39 if dir:
40 os.chdir(olddir)
41
42class PatchError(Exception):
43 def __init__(self, msg):
44 self.msg = msg
45
46 def __str__(self):
47 return "Patch Error: %s" % self.msg
48
49class PatchSet(object):
50 defaults = {
51 "strippath": 1
52 }
53
54 def __init__(self, dir, d):
55 self.dir = dir
56 self.d = d
57 self.patches = []
58 self._current = None
59
60 def current(self):
61 return self._current
62
63 def Clean(self):
64 """
65 Clean out the patch set. Generally includes unapplying all
66 patches and wiping out all associated metadata.
67 """
68 raise NotImplementedError()
69
70 def Import(self, patch, force):
71 if not patch.get("file"):
72 if not patch.get("remote"):
73 raise PatchError("Patch file must be specified in patch import.")
74 else:
75 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
76
77 for param in PatchSet.defaults:
78 if not patch.get(param):
79 patch[param] = PatchSet.defaults[param]
80
81 if patch.get("remote"):
82 patch["file"] = bb.data.expand(bb.fetch2.localpath(patch["remote"], self.d), self.d)
83
84 patch["filemd5"] = bb.utils.md5_file(patch["file"])
85
86 def Push(self, force):
87 raise NotImplementedError()
88
89 def Pop(self, force):
90 raise NotImplementedError()
91
92 def Refresh(self, remote = None, all = None):
93 raise NotImplementedError()
94
95 @staticmethod
96 def getPatchedFiles(patchfile, striplevel, srcdir=None):
97 """
98 Read a patch file and determine which files it will modify.
99 Params:
100 patchfile: the patch file to read
101 striplevel: the strip level at which the patch is going to be applied
102 srcdir: optional path to join onto the patched file paths
103 Returns:
104 A list of tuples of file path and change mode ('A' for add,
105 'D' for delete or 'M' for modify)
106 """
107
108 def patchedpath(patchline):
109 filepth = patchline.split()[1]
110 if filepth.endswith('/dev/null'):
111 return '/dev/null'
112 filesplit = filepth.split(os.sep)
113 if striplevel > len(filesplit):
114 bb.error('Patch %s has invalid strip level %d' % (patchfile, striplevel))
115 return None
116 return os.sep.join(filesplit[striplevel:])
117
118 copiedmode = False
119 filelist = []
120 with open(patchfile) as f:
121 for line in f:
122 if line.startswith('--- '):
123 patchpth = patchedpath(line)
124 if not patchpth:
125 break
126 if copiedmode:
127 addedfile = patchpth
128 else:
129 removedfile = patchpth
130 elif line.startswith('+++ '):
131 addedfile = patchedpath(line)
132 if not addedfile:
133 break
134 elif line.startswith('*** '):
135 copiedmode = True
136 removedfile = patchedpath(line)
137 if not removedfile:
138 break
139 else:
140 removedfile = None
141 addedfile = None
142
143 if addedfile and removedfile:
144 if removedfile == '/dev/null':
145 mode = 'A'
146 elif addedfile == '/dev/null':
147 mode = 'D'
148 else:
149 mode = 'M'
150 if srcdir:
151 fullpath = os.path.abspath(os.path.join(srcdir, addedfile))
152 else:
153 fullpath = addedfile
154 filelist.append((fullpath, mode))
155
156 return filelist
157
158
159class PatchTree(PatchSet):
160 def __init__(self, dir, d):
161 PatchSet.__init__(self, dir, d)
162 self.patchdir = os.path.join(self.dir, 'patches')
163 self.seriespath = os.path.join(self.dir, 'patches', 'series')
164 bb.utils.mkdirhier(self.patchdir)
165
166 def _appendPatchFile(self, patch, strippath):
167 with open(self.seriespath, 'a') as f:
168 f.write(os.path.basename(patch) + "," + strippath + "\n")
169 shellcmd = ["cat", patch, ">" , self.patchdir + "/" + os.path.basename(patch)]
170 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
171
172 def _removePatch(self, p):
173 patch = {}
174 patch['file'] = p.split(",")[0]
175 patch['strippath'] = p.split(",")[1]
176 self._applypatch(patch, False, True)
177
178 def _removePatchFile(self, all = False):
179 if not os.path.exists(self.seriespath):
180 return
181 with open(self.seriespath, 'r+') as f:
182 patches = f.readlines()
183 if all:
184 for p in reversed(patches):
185 self._removePatch(os.path.join(self.patchdir, p.strip()))
186 patches = []
187 else:
188 self._removePatch(os.path.join(self.patchdir, patches[-1].strip()))
189 patches.pop()
190 with open(self.seriespath, 'w') as f:
191 for p in patches:
192 f.write(p)
193
194 def Import(self, patch, force = None):
195 """"""
196 PatchSet.Import(self, patch, force)
197
198 if self._current is not None:
199 i = self._current + 1
200 else:
201 i = 0
202 self.patches.insert(i, patch)
203
204 def _applypatch(self, patch, force = False, reverse = False, run = True):
205 shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
206 if reverse:
207 shellcmd.append('-R')
208
209 if not run:
210 return "sh" + "-c" + " ".join(shellcmd)
211
212 if not force:
213 shellcmd.append('--dry-run')
214
215 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
216
217 if force:
218 return
219
220 shellcmd.pop(len(shellcmd) - 1)
221 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
222
223 if not reverse:
224 self._appendPatchFile(patch['file'], patch['strippath'])
225
226 return output
227
228 def Push(self, force = False, all = False, run = True):
229 bb.note("self._current is %s" % self._current)
230 bb.note("patches is %s" % self.patches)
231 if all:
232 for i in self.patches:
233 bb.note("applying patch %s" % i)
234 self._applypatch(i, force)
235 self._current = i
236 else:
237 if self._current is not None:
238 next = self._current + 1
239 else:
240 next = 0
241
242 bb.note("applying patch %s" % self.patches[next])
243 ret = self._applypatch(self.patches[next], force)
244
245 self._current = next
246 return ret
247
248 def Pop(self, force = None, all = None):
249 if all:
250 self._removePatchFile(True)
251 self._current = None
252 else:
253 self._removePatchFile(False)
254
255 if self._current == 0:
256 self._current = None
257
258 if self._current is not None:
259 self._current = self._current - 1
260
261 def Clean(self):
262 """"""
263 self.Pop(all=True)
264
265class GitApplyTree(PatchTree):
266 patch_line_prefix = '%% original patch'
267
268 def __init__(self, dir, d):
269 PatchTree.__init__(self, dir, d)
270
271 @staticmethod
272 def extractPatchHeader(patchfile):
273 """
274 Extract just the header lines from the top of a patch file
275 """
276 lines = []
277 with open(patchfile, 'r') as f:
278 for line in f.readlines():
279 if line.startswith('Index: ') or line.startswith('diff -') or line.startswith('---'):
280 break
281 lines.append(line)
282 return lines
283
284 @staticmethod
285 def prepareCommit(patchfile):
286 """
287 Prepare a git commit command line based on the header from a patch file
288 (typically this is useful for patches that cannot be applied with "git am" due to formatting)
289 """
290 import tempfile
291 import re
292 author_re = re.compile('[\S ]+ <\S+@\S+\.\S+>')
293 # Process patch header and extract useful information
294 lines = GitApplyTree.extractPatchHeader(patchfile)
295 outlines = []
296 author = None
297 date = None
298 for line in lines:
299 if line.startswith('Subject: '):
300 subject = line.split(':', 1)[1]
301 # Remove any [PATCH][oe-core] etc.
302 subject = re.sub(r'\[.+?\]\s*', '', subject)
303 outlines.insert(0, '%s\n\n' % subject.strip())
304 continue
305 if line.startswith('From: ') or line.startswith('Author: '):
306 authorval = line.split(':', 1)[1].strip().replace('"', '')
307 # git is fussy about author formatting i.e. it must be Name <email@domain>
308 if author_re.match(authorval):
309 author = authorval
310 continue
311 if line.startswith('Date: '):
312 if date is None:
313 dateval = line.split(':', 1)[1].strip()
314 # Very crude check for date format, since git will blow up if it's not in the right
315 # format. Without e.g. a python-dateutils dependency we can't do a whole lot more
316 if len(dateval) > 12:
317 date = dateval
318 continue
319 if line.startswith('Signed-off-by: '):
320 authorval = line.split(':', 1)[1].strip().replace('"', '')
321 # git is fussy about author formatting i.e. it must be Name <email@domain>
322 if author_re.match(authorval):
323 author = authorval
324 outlines.append(line)
325 # Write out commit message to a file
326 with tempfile.NamedTemporaryFile('w', delete=False) as tf:
327 tmpfile = tf.name
328 for line in outlines:
329 tf.write(line)
330 # Prepare git command
331 cmd = ["git", "commit", "-F", tmpfile]
332 # git doesn't like plain email addresses as authors
333 if author and '<' in author:
334 cmd.append('--author="%s"' % author)
335 if date:
336 cmd.append('--date="%s"' % date)
337 return (tmpfile, cmd)
338
339 @staticmethod
340 def extractPatches(tree, startcommit, outdir):
341 import tempfile
342 import shutil
343 tempdir = tempfile.mkdtemp(prefix='oepatch')
344 try:
345 shellcmd = ["git", "format-patch", startcommit, "-o", tempdir]
346 out = runcmd(["sh", "-c", " ".join(shellcmd)], tree)
347 if out:
348 for srcfile in out.split():
349 patchlines = []
350 outfile = None
351 with open(srcfile, 'r') as f:
352 for line in f:
353 if line.startswith(GitApplyTree.patch_line_prefix):
354 outfile = line.split()[-1].strip()
355 continue
356 patchlines.append(line)
357 if not outfile:
358 outfile = os.path.basename(srcfile)
359 with open(os.path.join(outdir, outfile), 'w') as of:
360 for line in patchlines:
361 of.write(line)
362 finally:
363 shutil.rmtree(tempdir)
364
365 def _applypatch(self, patch, force = False, reverse = False, run = True):
366 import shutil
367
368 def _applypatchhelper(shellcmd, patch, force = False, reverse = False, run = True):
369 if reverse:
370 shellcmd.append('-R')
371
372 shellcmd.append(patch['file'])
373
374 if not run:
375 return "sh" + "-c" + " ".join(shellcmd)
376
377 return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
378
379 # Add hooks which add a pointer to the original patch file name in the commit message
380 reporoot = (runcmd("git rev-parse --show-toplevel".split(), self.dir) or '').strip()
381 if not reporoot:
382 raise Exception("Cannot get repository root for directory %s" % self.dir)
383 commithook = os.path.join(reporoot, '.git', 'hooks', 'commit-msg')
384 commithook_backup = commithook + '.devtool-orig'
385 applyhook = os.path.join(reporoot, '.git', 'hooks', 'applypatch-msg')
386 applyhook_backup = applyhook + '.devtool-orig'
387 if os.path.exists(commithook):
388 shutil.move(commithook, commithook_backup)
389 if os.path.exists(applyhook):
390 shutil.move(applyhook, applyhook_backup)
391 with open(commithook, 'w') as f:
392 # NOTE: the formatting here is significant; if you change it you'll also need to
393 # change other places which read it back
394 f.write('echo >> $1\n')
395 f.write('echo "%s: $PATCHFILE" >> $1\n' % GitApplyTree.patch_line_prefix)
396 os.chmod(commithook, 0755)
397 shutil.copy2(commithook, applyhook)
398 try:
399 patchfilevar = 'PATCHFILE="%s"' % os.path.basename(patch['file'])
400 try:
401 shellcmd = [patchfilevar, "git", "--work-tree=%s" % reporoot, "am", "-3", "--keep-cr", "-p%s" % patch['strippath']]
402 return _applypatchhelper(shellcmd, patch, force, reverse, run)
403 except CmdError:
404 # Need to abort the git am, or we'll still be within it at the end
405 try:
406 shellcmd = ["git", "--work-tree=%s" % reporoot, "am", "--abort"]
407 runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
408 except CmdError:
409 pass
410 # Fall back to git apply
411 shellcmd = ["git", "--git-dir=%s" % reporoot, "apply", "-p%s" % patch['strippath']]
412 try:
413 output = _applypatchhelper(shellcmd, patch, force, reverse, run)
414 except CmdError:
415 # Fall back to patch
416 output = PatchTree._applypatch(self, patch, force, reverse, run)
417 # Add all files
418 shellcmd = ["git", "add", "-f", "-A", "."]
419 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
420 # Exclude the patches directory
421 shellcmd = ["git", "reset", "HEAD", self.patchdir]
422 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
423 # Commit the result
424 (tmpfile, shellcmd) = self.prepareCommit(patch['file'])
425 try:
426 shellcmd.insert(0, patchfilevar)
427 output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
428 finally:
429 os.remove(tmpfile)
430 return output
431 finally:
432 os.remove(commithook)
433 os.remove(applyhook)
434 if os.path.exists(commithook_backup):
435 shutil.move(commithook_backup, commithook)
436 if os.path.exists(applyhook_backup):
437 shutil.move(applyhook_backup, applyhook)
438
439
440class QuiltTree(PatchSet):
441 def _runcmd(self, args, run = True):
442 quiltrc = self.d.getVar('QUILTRCFILE', True)
443 if not run:
444 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
445 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
446
447 def _quiltpatchpath(self, file):
448 return os.path.join(self.dir, "patches", os.path.basename(file))
449
450
451 def __init__(self, dir, d):
452 PatchSet.__init__(self, dir, d)
453 self.initialized = False
454 p = os.path.join(self.dir, 'patches')
455 if not os.path.exists(p):
456 os.makedirs(p)
457
458 def Clean(self):
459 try:
460 self._runcmd(["pop", "-a", "-f"])
461 oe.path.remove(os.path.join(self.dir, "patches","series"))
462 except Exception:
463 pass
464 self.initialized = True
465
466 def InitFromDir(self):
467 # read series -> self.patches
468 seriespath = os.path.join(self.dir, 'patches', 'series')
469 if not os.path.exists(self.dir):
470 raise NotFoundError(self.dir)
471 if os.path.exists(seriespath):
472 with open(seriespath, 'r') as f:
473 for line in f.readlines():
474 patch = {}
475 parts = line.strip().split()
476 patch["quiltfile"] = self._quiltpatchpath(parts[0])
477 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
478 if len(parts) > 1:
479 patch["strippath"] = parts[1][2:]
480 self.patches.append(patch)
481
482 # determine which patches are applied -> self._current
483 try:
484 output = runcmd(["quilt", "applied"], self.dir)
485 except CmdError:
486 import sys
487 if sys.exc_value.output.strip() == "No patches applied":
488 return
489 else:
490 raise
491 output = [val for val in output.split('\n') if not val.startswith('#')]
492 for patch in self.patches:
493 if os.path.basename(patch["quiltfile"]) == output[-1]:
494 self._current = self.patches.index(patch)
495 self.initialized = True
496
497 def Import(self, patch, force = None):
498 if not self.initialized:
499 self.InitFromDir()
500 PatchSet.Import(self, patch, force)
501 oe.path.symlink(patch["file"], self._quiltpatchpath(patch["file"]), force=True)
502 with open(os.path.join(self.dir, "patches", "series"), "a") as f:
503 f.write(os.path.basename(patch["file"]) + " -p" + patch["strippath"] + "\n")
504 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
505 patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"])
506
507 # TODO: determine if the file being imported:
508 # 1) is already imported, and is the same
509 # 2) is already imported, but differs
510
511 self.patches.insert(self._current or 0, patch)
512
513
514 def Push(self, force = False, all = False, run = True):
515 # quilt push [-f]
516
517 args = ["push"]
518 if force:
519 args.append("-f")
520 if all:
521 args.append("-a")
522 if not run:
523 return self._runcmd(args, run)
524
525 self._runcmd(args)
526
527 if self._current is not None:
528 self._current = self._current + 1
529 else:
530 self._current = 0
531
532 def Pop(self, force = None, all = None):
533 # quilt pop [-f]
534 args = ["pop"]
535 if force:
536 args.append("-f")
537 if all:
538 args.append("-a")
539
540 self._runcmd(args)
541
542 if self._current == 0:
543 self._current = None
544
545 if self._current is not None:
546 self._current = self._current - 1
547
548 def Refresh(self, **kwargs):
549 if kwargs.get("remote"):
550 patch = self.patches[kwargs["patch"]]
551 if not patch:
552 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
553 (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(patch["remote"])
554 if type == "file":
555 import shutil
556 if not patch.get("file") and patch.get("remote"):
557 patch["file"] = bb.fetch2.localpath(patch["remote"], self.d)
558
559 shutil.copyfile(patch["quiltfile"], patch["file"])
560 else:
561 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
562 else:
563 # quilt refresh
564 args = ["refresh"]
565 if kwargs.get("quiltfile"):
566 args.append(os.path.basename(kwargs["quiltfile"]))
567 elif kwargs.get("patch"):
568 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
569 self._runcmd(args)
570
571class Resolver(object):
572 def __init__(self, patchset, terminal):
573 raise NotImplementedError()
574
575 def Resolve(self):
576 raise NotImplementedError()
577
578 def Revert(self):
579 raise NotImplementedError()
580
581 def Finalize(self):
582 raise NotImplementedError()
583
584class NOOPResolver(Resolver):
585 def __init__(self, patchset, terminal):
586 self.patchset = patchset
587 self.terminal = terminal
588
589 def Resolve(self):
590 olddir = os.path.abspath(os.curdir)
591 os.chdir(self.patchset.dir)
592 try:
593 self.patchset.Push()
594 except Exception:
595 import sys
596 os.chdir(olddir)
597 raise
598
599# Patch resolver which relies on the user doing all the work involved in the
600# resolution, with the exception of refreshing the remote copy of the patch
601# files (the urls).
602class UserResolver(Resolver):
603 def __init__(self, patchset, terminal):
604 self.patchset = patchset
605 self.terminal = terminal
606
607 # Force a push in the patchset, then drop to a shell for the user to
608 # resolve any rejected hunks
609 def Resolve(self):
610 olddir = os.path.abspath(os.curdir)
611 os.chdir(self.patchset.dir)
612 try:
613 self.patchset.Push(False)
614 except CmdError as v:
615 # Patch application failed
616 patchcmd = self.patchset.Push(True, False, False)
617
618 t = self.patchset.d.getVar('T', True)
619 if not t:
620 bb.msg.fatal("Build", "T not set")
621 bb.utils.mkdirhier(t)
622 import random
623 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
624 with open(rcfile, "w") as f:
625 f.write("echo '*** Manual patch resolution mode ***'\n")
626 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
627 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
628 f.write("echo ''\n")
629 f.write(" ".join(patchcmd) + "\n")
630 os.chmod(rcfile, 0775)
631
632 self.terminal("bash --rcfile " + rcfile, 'Patch Rejects: Please fix patch rejects manually', self.patchset.d)
633
634 # Construct a new PatchSet after the user's changes, compare the
635 # sets, checking patches for modifications, and doing a remote
636 # refresh on each.
637 oldpatchset = self.patchset
638 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
639
640 for patch in self.patchset.patches:
641 oldpatch = None
642 for opatch in oldpatchset.patches:
643 if opatch["quiltfile"] == patch["quiltfile"]:
644 oldpatch = opatch
645
646 if oldpatch:
647 patch["remote"] = oldpatch["remote"]
648 if patch["quiltfile"] == oldpatch["quiltfile"]:
649 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
650 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
651 # user change? remote refresh
652 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
653 else:
654 # User did not fix the problem. Abort.
655 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
656 except Exception:
657 os.chdir(olddir)
658 raise
659 os.chdir(olddir)