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"
9 class NotFoundError(Exception):
10 def __init__(self, path):
13 return "Error: %s not found." % self.path
18 # when we move to Python 2.5 as minimal supported
19 # we can kill that try/except as hashlib is 2.5+
30 raise NotFoundError(fname)
40 class CmdError(Exception):
41 def __init__(self, exitstatus, output):
42 self.status = exitstatus
46 return "Command Error: exit status: %d Output:\n%s" % (self.status, self.output)
49 def runcmd(args, dir = None):
53 olddir = os.path.abspath(os.curdir)
54 if not os.path.exists(dir):
55 raise NotFoundError(dir)
57 # print("cwd: %s -> %s" % (olddir, dir))
60 args = [ commands.mkarg(str(arg)) for arg in args ]
62 # print("cmd: %s" % cmd)
63 (exitstatus, output) = commands.getstatusoutput(cmd)
65 raise CmdError(exitstatus >> 8, output)
72 class PatchError(Exception):
73 def __init__(self, msg):
77 return "Patch Error: %s" % self.msg
79 import bb, bb.data, bb.fetch
81 class PatchSet(object):
86 def __init__(self, dir, d):
97 Clean out the patch set. Generally includes unapplying all
98 patches and wiping out all associated metadata.
100 raise NotImplementedError()
102 def Import(self, patch, force):
103 if not patch.get("file"):
104 if not patch.get("remote"):
105 raise PatchError("Patch file must be specified in patch import.")
107 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
109 for param in PatchSet.defaults:
110 if not patch.get(param):
111 patch[param] = PatchSet.defaults[param]
113 if patch.get("remote"):
114 patch["file"] = bb.data.expand(bb.fetch.localpath(patch["remote"], self.d), self.d)
116 patch["filemd5"] = md5sum(patch["file"])
118 def Push(self, force):
119 raise NotImplementedError()
121 def Pop(self, force):
122 raise NotImplementedError()
124 def Refresh(self, remote = None, all = None):
125 raise NotImplementedError()
128 class PatchTree(PatchSet):
129 def __init__(self, dir, d):
130 PatchSet.__init__(self, dir, d)
132 def Import(self, patch, force = None):
134 PatchSet.Import(self, patch, force)
136 if self._current is not None:
137 i = self._current + 1
140 self.patches.insert(i, patch)
142 def _applypatch(self, patch, force = False, reverse = False, run = True):
143 shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
145 shellcmd.append('-R')
148 return "sh" + "-c" + " ".join(shellcmd)
151 shellcmd.append('--dry-run')
153 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
158 shellcmd.pop(len(shellcmd) - 1)
159 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
162 def Push(self, force = False, all = False, run = True):
163 bb.note("self._current is %s" % self._current)
164 bb.note("patches is %s" % self.patches)
166 for i in self.patches:
167 if self._current is not None:
168 self._current = self._current + 1
171 bb.note("applying patch %s" % i)
172 self._applypatch(i, force)
174 if self._current is not None:
175 self._current = self._current + 1
178 bb.note("applying patch %s" % self.patches[self._current])
179 return self._applypatch(self.patches[self._current], force)
182 def Pop(self, force = None, all = None):
184 for i in self.patches:
185 self._applypatch(i, force, True)
187 self._applypatch(self.patches[self._current], force, True)
192 class GitApplyTree(PatchTree):
193 def __init__(self, dir, d):
194 PatchTree.__init__(self, dir, d)
196 def _applypatch(self, patch, force = False, reverse = False, run = True):
197 shellcmd = ["git", "--git-dir=.", "apply", "-p%s" % patch['strippath']]
200 shellcmd.append('-R')
202 shellcmd.append(patch['file'])
205 return "sh" + "-c" + " ".join(shellcmd)
207 return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
210 class QuiltTree(PatchSet):
211 def _runcmd(self, args, run = True):
212 quiltrc = bb.data.getVar('QUILTRCFILE', self.d, 1)
214 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
215 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
217 def _quiltpatchpath(self, file):
218 return os.path.join(self.dir, "patches", os.path.basename(file))
221 def __init__(self, dir, d):
222 PatchSet.__init__(self, dir, d)
223 self.initialized = False
224 p = os.path.join(self.dir, 'patches')
225 if not os.path.exists(p):
230 self._runcmd(["pop", "-a", "-f"])
233 self.initialized = True
235 def InitFromDir(self):
236 # read series -> self.patches
237 seriespath = os.path.join(self.dir, 'patches', 'series')
238 if not os.path.exists(self.dir):
239 raise Exception("Error: %s does not exist." % self.dir)
240 if os.path.exists(seriespath):
241 series = file(seriespath, 'r')
242 for line in series.readlines():
244 parts = line.strip().split()
245 patch["quiltfile"] = self._quiltpatchpath(parts[0])
246 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
248 patch["strippath"] = parts[1][2:]
249 self.patches.append(patch)
252 # determine which patches are applied -> self._current
254 output = runcmd(["quilt", "applied"], self.dir)
256 if sys.exc_value.output.strip() == "No patches applied":
260 output = [val for val in output.split('\n') if not val.startswith('#')]
261 for patch in self.patches:
262 if os.path.basename(patch["quiltfile"]) == output[-1]:
263 self._current = self.patches.index(patch)
264 self.initialized = True
266 def Import(self, patch, force = None):
267 if not self.initialized:
269 PatchSet.Import(self, patch, force)
271 args = ["import", "-p", patch["strippath"]]
275 args.append(patch["file"])
279 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
280 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
282 # TODO: determine if the file being imported:
283 # 1) is already imported, and is the same
284 # 2) is already imported, but differs
286 self.patches.insert(self._current or 0, patch)
289 def Push(self, force = False, all = False, run = True):
298 return self._runcmd(args, run)
302 if self._current is not None:
303 self._current = self._current + 1
307 def Pop(self, force = None, all = None):
317 if self._current == 0:
320 if self._current is not None:
321 self._current = self._current - 1
323 def Refresh(self, **kwargs):
324 if kwargs.get("remote"):
325 patch = self.patches[kwargs["patch"]]
327 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
328 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
331 if not patch.get("file") and patch.get("remote"):
332 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
334 shutil.copyfile(patch["quiltfile"], patch["file"])
336 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
340 if kwargs.get("quiltfile"):
341 args.append(os.path.basename(kwargs["quiltfile"]))
342 elif kwargs.get("patch"):
343 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
346 class Resolver(object):
347 def __init__(self, patchset):
348 raise NotImplementedError()
351 raise NotImplementedError()
354 raise NotImplementedError()
357 raise NotImplementedError()
359 class NOOPResolver(Resolver):
360 def __init__(self, patchset):
361 self.patchset = patchset
364 olddir = os.path.abspath(os.curdir)
365 os.chdir(self.patchset.dir)
372 # Patch resolver which relies on the user doing all the work involved in the
373 # resolution, with the exception of refreshing the remote copy of the patch
375 class UserResolver(Resolver):
376 def __init__(self, patchset):
377 self.patchset = patchset
379 # Force a push in the patchset, then drop to a shell for the user to
380 # resolve any rejected hunks
383 olddir = os.path.abspath(os.curdir)
384 os.chdir(self.patchset.dir)
386 self.patchset.Push(False)
388 # Patch application failed
389 patchcmd = self.patchset.Push(True, False, False)
391 t = bb.data.getVar('T', d, 1)
393 bb.msg.fatal(bb.msg.domain.Build, "T not set")
396 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
397 f = open(rcfile, "w")
398 f.write("echo '*** Manual patch resolution mode ***'\n")
399 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
400 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
402 f.write(" ".join(patchcmd) + "\n")
403 f.write("#" + bb.data.getVar('TERMCMDRUN', d, 1))
405 os.chmod(rcfile, 0775)
407 os.environ['TERMWINDOWTITLE'] = "Bitbake: Please fix patch rejects manually"
408 os.environ['TERMRCFILE'] = rcfile
409 rc = os.system(bb.data.getVar('TERMCMDRUN', d, 1))
410 if os.WIFEXITED(rc) and os.WEXITSTATUS(rc) != 0:
411 bb.msg.fatal(bb.msg.domain.Build, ("Cannot proceed with manual patch resolution - '%s' not found. " \
412 + "Check TERMCMDRUN variable.") % bb.data.getVar('TERMCMDRUN', d, 1))
414 # Construct a new PatchSet after the user's changes, compare the
415 # sets, checking patches for modifications, and doing a remote
417 oldpatchset = self.patchset
418 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
420 for patch in self.patchset.patches:
422 for opatch in oldpatchset.patches:
423 if opatch["quiltfile"] == patch["quiltfile"]:
427 patch["remote"] = oldpatch["remote"]
428 if patch["quiltfile"] == oldpatch["quiltfile"]:
429 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
430 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
431 # user change? remote refresh
432 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
434 # User did not fix the problem. Abort.
435 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
442 g["PatchSet"] = PatchSet
443 g["PatchTree"] = PatchTree
444 g["QuiltTree"] = QuiltTree
445 g["GitApplyTree"] = GitApplyTree
446 g["Resolver"] = Resolver
447 g["UserResolver"] = UserResolver
448 g["NOOPResolver"] = NOOPResolver
449 g["NotFoundError"] = NotFoundError
450 g["CmdError"] = CmdError
452 addtask patch after do_unpack
453 do_patch[dirs] = "${WORKDIR}"
455 PATCHDEPENDENCY = "${PATCHTOOL}-native:do_populate_staging"
456 do_patch[depends] = "${PATCHDEPENDENCY}"
458 python patch_do_patch() {
464 src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
474 cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
477 "noop": NOOPResolver,
478 "user": UserResolver,
481 rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
483 s = bb.data.getVar('S', d, 1)
485 path = os.getenv('PATH')
486 os.putenv('PATH', bb.data.getVar('PATH', d, 1))
490 resolver = rcls(patchset)
492 workdir = bb.data.getVar('WORKDIR', d, 1)
494 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
495 if not "patch" in parm:
498 bb.fetch.init([url],d)
499 url = bb.encodeurl((type, host, path, user, pswd, []))
500 local = os.path.join('/', bb.fetch.localpath(url, d))
502 # did it need to be unpacked?
503 dots = os.path.basename(local).split(".")
504 if dots[-1] in ['gz', 'bz2', 'Z']:
505 unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
508 unpacked = bb.data.expand(unpacked, d)
516 pname = parm["pname"]
518 pname = os.path.basename(unpacked)
520 if "mindate" in parm or "maxdate" in parm:
521 pn = bb.data.getVar('PN', d, 1)
522 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
524 srcdate = bb.data.getVar('SRCDATE', d, 1)
527 srcdate = bb.data.getVar('DATE', d, 1)
529 if "maxdate" in parm and parm["maxdate"] < srcdate:
530 bb.note("Patch '%s' is outdated" % pname)
533 if "mindate" in parm and parm["mindate"] > srcdate:
534 bb.note("Patch '%s' is predated" % pname)
539 srcrev = bb.data.getVar('SRCREV', d, 1)
540 if srcrev and srcrev < parm["minrev"]:
541 bb.note("Patch '%s' applies to later revisions" % pname)
545 srcrev = bb.data.getVar('SRCREV', d, 1)
546 if srcrev and srcrev > parm["maxrev"]:
547 bb.note("Patch '%s' applies to earlier revisions" % pname)
550 bb.note("Applying patch '%s' (%s)" % (pname, base_path_out(unpacked, d)))
552 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
555 raise bb.build.FuncFailed(str(sys.exc_value))
559 EXPORT_FUNCTIONS do_patch