1 # Copyright (C) 2006 OpenedHand LTD
3 # Point to an empty file so any user's custom settings don't break things
4 QUILTRCFILE ?= "${STAGING_BINDIR_NATIVE}/quiltrc"
7 class NotFoundError(Exception):
8 def __init__(self, path):
11 return "Error: %s not found." % self.path
14 # when we move to Python 2.5 as minimal supported
15 # we can kill that try/except as hashlib is 2.5+
26 raise NotFoundError(fname)
36 class CmdError(Exception):
37 def __init__(self, exitstatus, output):
38 self.status = exitstatus
42 return "Command Error: exit status: %d Output:\n%s" % (self.status, self.output)
45 def runcmd(args, dir = None):
49 olddir = os.path.abspath(os.curdir)
50 if not os.path.exists(dir):
51 raise NotFoundError(dir)
53 # print("cwd: %s -> %s" % (olddir, dir))
56 args = [ commands.mkarg(str(arg)) for arg in args ]
58 # print("cmd: %s" % cmd)
59 (exitstatus, output) = commands.getstatusoutput(cmd)
61 raise CmdError(exitstatus >> 8, output)
68 class PatchError(Exception):
69 def __init__(self, msg):
73 return "Patch Error: %s" % self.msg
75 class PatchSet(object):
80 def __init__(self, dir, d):
91 Clean out the patch set. Generally includes unapplying all
92 patches and wiping out all associated metadata.
94 raise NotImplementedError()
96 def Import(self, patch, force):
97 if not patch.get("file"):
98 if not patch.get("remote"):
99 raise PatchError("Patch file must be specified in patch import.")
101 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
103 for param in PatchSet.defaults:
104 if not patch.get(param):
105 patch[param] = PatchSet.defaults[param]
107 if patch.get("remote"):
108 patch["file"] = bb.data.expand(bb.fetch.localpath(patch["remote"], self.d), self.d)
110 patch["filemd5"] = md5sum(patch["file"])
112 def Push(self, force):
113 raise NotImplementedError()
115 def Pop(self, force):
116 raise NotImplementedError()
118 def Refresh(self, remote = None, all = None):
119 raise NotImplementedError()
122 class PatchTree(PatchSet):
123 def __init__(self, dir, d):
124 PatchSet.__init__(self, dir, d)
126 def Import(self, patch, force = None):
128 PatchSet.Import(self, patch, force)
130 if self._current is not None:
131 i = self._current + 1
134 self.patches.insert(i, patch)
136 def _applypatch(self, patch, force = False, reverse = False, run = True):
137 shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
139 shellcmd.append('-R')
142 return "sh" + "-c" + " ".join(shellcmd)
145 shellcmd.append('--dry-run')
147 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
152 shellcmd.pop(len(shellcmd) - 1)
153 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
156 def Push(self, force = False, all = False, run = True):
157 bb.note("self._current is %s" % self._current)
158 bb.note("patches is %s" % self.patches)
160 for i in self.patches:
161 if self._current is not None:
162 self._current = self._current + 1
165 bb.note("applying patch %s" % i)
166 self._applypatch(i, force)
168 if self._current is not None:
169 self._current = self._current + 1
172 bb.note("applying patch %s" % self.patches[self._current])
173 return self._applypatch(self.patches[self._current], force)
176 def Pop(self, force = None, all = None):
178 for i in self.patches:
179 self._applypatch(i, force, True)
181 self._applypatch(self.patches[self._current], force, True)
186 class GitApplyTree(PatchTree):
187 def __init__(self, dir, d):
188 PatchTree.__init__(self, dir, d)
190 def _applypatch(self, patch, force = False, reverse = False, run = True):
191 shellcmd = ["git", "--git-dir=.", "apply", "-p%s" % patch['strippath']]
194 shellcmd.append('-R')
196 shellcmd.append(patch['file'])
199 return "sh" + "-c" + " ".join(shellcmd)
201 return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
204 class QuiltTree(PatchSet):
205 def _runcmd(self, args, run = True):
206 quiltrc = bb.data.getVar('QUILTRCFILE', self.d, 1)
208 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
209 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
211 def _quiltpatchpath(self, file):
212 return os.path.join(self.dir, "patches", os.path.basename(file))
215 def __init__(self, dir, d):
216 PatchSet.__init__(self, dir, d)
217 self.initialized = False
218 p = os.path.join(self.dir, 'patches')
219 if not os.path.exists(p):
224 self._runcmd(["pop", "-a", "-f"])
227 self.initialized = True
229 def InitFromDir(self):
230 # read series -> self.patches
231 seriespath = os.path.join(self.dir, 'patches', 'series')
232 if not os.path.exists(self.dir):
233 raise Exception("Error: %s does not exist." % self.dir)
234 if os.path.exists(seriespath):
235 series = file(seriespath, 'r')
236 for line in series.readlines():
238 parts = line.strip().split()
239 patch["quiltfile"] = self._quiltpatchpath(parts[0])
240 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
242 patch["strippath"] = parts[1][2:]
243 self.patches.append(patch)
246 # determine which patches are applied -> self._current
248 output = runcmd(["quilt", "applied"], self.dir)
251 if sys.exc_value.output.strip() == "No patches applied":
255 output = [val for val in output.split('\n') if not val.startswith('#')]
256 for patch in self.patches:
257 if os.path.basename(patch["quiltfile"]) == output[-1]:
258 self._current = self.patches.index(patch)
259 self.initialized = True
261 def Import(self, patch, force = None):
262 if not self.initialized:
264 PatchSet.Import(self, patch, force)
266 args = ["import", "-p", patch["strippath"]]
270 args.append(patch["file"])
274 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
275 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
277 # TODO: determine if the file being imported:
278 # 1) is already imported, and is the same
279 # 2) is already imported, but differs
281 self.patches.insert(self._current or 0, patch)
284 def Push(self, force = False, all = False, run = True):
293 return self._runcmd(args, run)
297 if self._current is not None:
298 self._current = self._current + 1
302 def Pop(self, force = None, all = None):
312 if self._current == 0:
315 if self._current is not None:
316 self._current = self._current - 1
318 def Refresh(self, **kwargs):
319 if kwargs.get("remote"):
320 patch = self.patches[kwargs["patch"]]
322 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
323 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
326 if not patch.get("file") and patch.get("remote"):
327 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
329 shutil.copyfile(patch["quiltfile"], patch["file"])
331 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
335 if kwargs.get("quiltfile"):
336 args.append(os.path.basename(kwargs["quiltfile"]))
337 elif kwargs.get("patch"):
338 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
341 class Resolver(object):
342 def __init__(self, patchset):
343 raise NotImplementedError()
346 raise NotImplementedError()
349 raise NotImplementedError()
352 raise NotImplementedError()
354 class NOOPResolver(Resolver):
355 def __init__(self, patchset):
356 self.patchset = patchset
359 olddir = os.path.abspath(os.curdir)
360 os.chdir(self.patchset.dir)
368 # Patch resolver which relies on the user doing all the work involved in the
369 # resolution, with the exception of refreshing the remote copy of the patch
371 class UserResolver(Resolver):
372 def __init__(self, patchset):
373 self.patchset = patchset
375 # Force a push in the patchset, then drop to a shell for the user to
376 # resolve any rejected hunks
379 olddir = os.path.abspath(os.curdir)
380 os.chdir(self.patchset.dir)
382 self.patchset.Push(False)
384 # Patch application failed
385 patchcmd = self.patchset.Push(True, False, False)
387 t = bb.data.getVar('T', d, 1)
389 bb.msg.fatal(bb.msg.domain.Build, "T not set")
392 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
393 f = open(rcfile, "w")
394 f.write("echo '*** Manual patch resolution mode ***'\n")
395 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
396 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
398 f.write(" ".join(patchcmd) + "\n")
399 f.write("#" + bb.data.getVar('TERMCMDRUN', d, 1))
401 os.chmod(rcfile, 0775)
403 os.environ['TERMWINDOWTITLE'] = "Bitbake: Please fix patch rejects manually"
404 os.environ['TERMRCFILE'] = rcfile
405 rc = os.system(bb.data.getVar('TERMCMDRUN', d, 1))
406 if os.WIFEXITED(rc) and os.WEXITSTATUS(rc) != 0:
407 bb.msg.fatal(bb.msg.domain.Build, ("Cannot proceed with manual patch resolution - '%s' not found. " \
408 + "Check TERMCMDRUN variable.") % bb.data.getVar('TERMCMDRUN', d, 1))
410 # Construct a new PatchSet after the user's changes, compare the
411 # sets, checking patches for modifications, and doing a remote
413 oldpatchset = self.patchset
414 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
416 for patch in self.patchset.patches:
418 for opatch in oldpatchset.patches:
419 if opatch["quiltfile"] == patch["quiltfile"]:
423 patch["remote"] = oldpatch["remote"]
424 if patch["quiltfile"] == oldpatch["quiltfile"]:
425 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
426 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
427 # user change? remote refresh
428 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
430 # User did not fix the problem. Abort.
431 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
438 g["PatchSet"] = PatchSet
439 g["PatchTree"] = PatchTree
440 g["QuiltTree"] = QuiltTree
441 g["GitApplyTree"] = GitApplyTree
442 g["Resolver"] = Resolver
443 g["UserResolver"] = UserResolver
444 g["NOOPResolver"] = NOOPResolver
445 g["NotFoundError"] = NotFoundError
446 g["CmdError"] = CmdError
448 addtask patch after do_unpack
449 do_patch[dirs] = "${WORKDIR}"
451 PATCHDEPENDENCY = "${PATCHTOOL}-native:do_populate_staging"
452 do_patch[depends] = "${PATCHDEPENDENCY}"
454 python patch_do_patch() {
457 src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
467 cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
470 "noop": NOOPResolver,
471 "user": UserResolver,
474 rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
476 s = bb.data.getVar('S', d, 1)
478 path = os.getenv('PATH')
479 os.putenv('PATH', bb.data.getVar('PATH', d, 1))
483 resolver = rcls(patchset)
485 workdir = bb.data.getVar('WORKDIR', d, 1)
487 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
488 if not "patch" in parm:
491 bb.fetch.init([url],d)
492 url = bb.encodeurl((type, host, path, user, pswd, []))
493 local = os.path.join('/', bb.fetch.localpath(url, d))
495 # did it need to be unpacked?
496 dots = os.path.basename(local).split(".")
497 if dots[-1] in ['gz', 'bz2', 'Z']:
498 unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
501 unpacked = bb.data.expand(unpacked, d)
509 pname = parm["pname"]
511 pname = os.path.basename(unpacked)
513 if "mindate" in parm or "maxdate" in parm:
514 pn = bb.data.getVar('PN', d, 1)
515 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
517 srcdate = bb.data.getVar('SRCDATE', d, 1)
520 srcdate = bb.data.getVar('DATE', d, 1)
522 if "maxdate" in parm and parm["maxdate"] < srcdate:
523 bb.note("Patch '%s' is outdated" % pname)
526 if "mindate" in parm and parm["mindate"] > srcdate:
527 bb.note("Patch '%s' is predated" % pname)
532 srcrev = bb.data.getVar('SRCREV', d, 1)
533 if srcrev and srcrev < parm["minrev"]:
534 bb.note("Patch '%s' applies to later revisions" % pname)
538 srcrev = bb.data.getVar('SRCREV', d, 1)
539 if srcrev and srcrev > parm["maxrev"]:
540 bb.note("Patch '%s' applies to earlier revisions" % pname)
543 bb.note("Applying patch '%s' (%s)" % (pname, base_path_out(unpacked, d)))
545 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
548 raise bb.build.FuncFailed(str(sys.exc_value))
552 EXPORT_FUNCTIONS do_patch