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
21 raise NotFoundError(fname)
32 class CmdError(Exception):
33 def __init__(self, exitstatus, output):
34 self.status = exitstatus
38 return "Command Error: exit status: %d Output:\n%s" % (self.status, self.output)
41 def runcmd(args, dir = None):
45 olddir = os.path.abspath(os.curdir)
46 if not os.path.exists(dir):
47 raise NotFoundError(dir)
49 # print("cwd: %s -> %s" % (olddir, dir))
52 args = [ commands.mkarg(str(arg)) for arg in args ]
54 # print("cmd: %s" % cmd)
55 (exitstatus, output) = commands.getstatusoutput(cmd)
57 raise CmdError(exitstatus >> 8, output)
64 class PatchError(Exception):
65 def __init__(self, msg):
69 return "Patch Error: %s" % self.msg
71 import bb, bb.data, bb.fetch
73 class PatchSet(object):
78 def __init__(self, dir, d):
89 Clean out the patch set. Generally includes unapplying all
90 patches and wiping out all associated metadata.
92 raise NotImplementedError()
94 def Import(self, patch, force):
95 if not patch.get("file"):
96 if not patch.get("remote"):
97 raise PatchError("Patch file must be specified in patch import.")
99 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
101 for param in PatchSet.defaults:
102 if not patch.get(param):
103 patch[param] = PatchSet.defaults[param]
105 if patch.get("remote"):
106 patch["file"] = bb.data.expand(bb.fetch.localpath(patch["remote"], self.d), self.d)
108 patch["filemd5"] = md5sum(patch["file"])
110 def Push(self, force):
111 raise NotImplementedError()
113 def Pop(self, force):
114 raise NotImplementedError()
116 def Refresh(self, remote = None, all = None):
117 raise NotImplementedError()
120 class PatchTree(PatchSet):
121 def __init__(self, dir, d):
122 PatchSet.__init__(self, dir, d)
124 def Import(self, patch, force = None):
126 PatchSet.Import(self, patch, force)
128 if self._current is not None:
129 i = self._current + 1
132 self.patches.insert(i, patch)
134 def _applypatch(self, patch, force = False, reverse = False, run = True):
135 shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
137 shellcmd.append('-R')
140 return "sh" + "-c" + " ".join(shellcmd)
143 shellcmd.append('--dry-run')
145 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
150 shellcmd.pop(len(shellcmd) - 1)
151 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
154 def Push(self, force = False, all = False, run = True):
155 bb.note("self._current is %s" % self._current)
156 bb.note("patches is %s" % self.patches)
158 for i in self.patches:
159 if self._current is not None:
160 self._current = self._current + 1
163 bb.note("applying patch %s" % i)
164 self._applypatch(i, force)
166 if self._current is not None:
167 self._current = self._current + 1
170 bb.note("applying patch %s" % self.patches[self._current])
171 return self._applypatch(self.patches[self._current], force)
174 def Pop(self, force = None, all = None):
176 for i in self.patches:
177 self._applypatch(i, force, True)
179 self._applypatch(self.patches[self._current], force, True)
184 class QuiltTree(PatchSet):
185 def _runcmd(self, args, run = True):
186 quiltrc = bb.data.getVar('QUILTRCFILE', self.d, 1)
188 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
189 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
191 def _quiltpatchpath(self, file):
192 return os.path.join(self.dir, "patches", os.path.basename(file))
195 def __init__(self, dir, d):
196 PatchSet.__init__(self, dir, d)
197 self.initialized = False
198 p = os.path.join(self.dir, 'patches')
199 if not os.path.exists(p):
204 self._runcmd(["pop", "-a", "-f"])
207 self.initialized = True
209 def InitFromDir(self):
210 # read series -> self.patches
211 seriespath = os.path.join(self.dir, 'patches', 'series')
212 if not os.path.exists(self.dir):
213 raise Exception("Error: %s does not exist." % self.dir)
214 if os.path.exists(seriespath):
215 series = file(seriespath, 'r')
216 for line in series.readlines():
218 parts = line.strip().split()
219 patch["quiltfile"] = self._quiltpatchpath(parts[0])
220 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
222 patch["strippath"] = parts[1][2:]
223 self.patches.append(patch)
226 # determine which patches are applied -> self._current
228 output = runcmd(["quilt", "applied"], self.dir)
230 if sys.exc_value.output.strip() == "No patches applied":
234 output = [val for val in output.split('\n') if not val.startswith('#')]
235 for patch in self.patches:
236 if os.path.basename(patch["quiltfile"]) == output[-1]:
237 self._current = self.patches.index(patch)
238 self.initialized = True
240 def Import(self, patch, force = None):
241 if not self.initialized:
243 PatchSet.Import(self, patch, force)
245 args = ["import", "-p", patch["strippath"]]
249 args.append(patch["file"])
253 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
254 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
256 # TODO: determine if the file being imported:
257 # 1) is already imported, and is the same
258 # 2) is already imported, but differs
260 self.patches.insert(self._current or 0, patch)
263 def Push(self, force = False, all = False, run = True):
272 return self._runcmd(args, run)
276 if self._current is not None:
277 self._current = self._current + 1
281 def Pop(self, force = None, all = None):
291 if self._current == 0:
294 if self._current is not None:
295 self._current = self._current - 1
297 def Refresh(self, **kwargs):
298 if kwargs.get("remote"):
299 patch = self.patches[kwargs["patch"]]
301 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
302 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
305 if not patch.get("file") and patch.get("remote"):
306 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
308 shutil.copyfile(patch["quiltfile"], patch["file"])
310 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
314 if kwargs.get("quiltfile"):
315 args.append(os.path.basename(kwargs["quiltfile"]))
316 elif kwargs.get("patch"):
317 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
320 class Resolver(object):
321 def __init__(self, patchset):
322 raise NotImplementedError()
325 raise NotImplementedError()
328 raise NotImplementedError()
331 raise NotImplementedError()
333 class NOOPResolver(Resolver):
334 def __init__(self, patchset):
335 self.patchset = patchset
338 olddir = os.path.abspath(os.curdir)
339 os.chdir(self.patchset.dir)
346 # Patch resolver which relies on the user doing all the work involved in the
347 # resolution, with the exception of refreshing the remote copy of the patch
349 class UserResolver(Resolver):
350 def __init__(self, patchset):
351 self.patchset = patchset
353 # Force a push in the patchset, then drop to a shell for the user to
354 # resolve any rejected hunks
357 olddir = os.path.abspath(os.curdir)
358 os.chdir(self.patchset.dir)
360 self.patchset.Push(False)
362 # Patch application failed
363 patchcmd = self.patchset.Push(True, False, False)
365 t = bb.data.getVar('T', d, 1)
367 bb.msg.fatal(bb.msg.domain.Build, "T not set")
370 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
371 f = open(rcfile, "w")
372 f.write("echo '*** Manual patch resolution mode ***'\n")
373 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
374 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
376 f.write(" ".join(patchcmd) + "\n")
377 f.write("#" + bb.data.getVar('TERMCMDRUN', d, 1))
379 os.chmod(rcfile, 0775)
381 os.environ['TERMWINDOWTITLE'] = "Bitbake: Please fix patch rejects manually"
382 os.environ['TERMRCFILE'] = rcfile
383 rc = os.system(bb.data.getVar('TERMCMDRUN', d, 1))
384 if os.WIFEXITED(rc) and os.WEXITSTATUS(rc) != 0:
385 bb.msg.fatal(bb.msg.domain.Build, ("Cannot proceed with manual patch resolution - '%s' not found. " \
386 + "Check TERMCMDRUN variable.") % bb.data.getVar('TERMCMDRUN', d, 1))
388 # Construct a new PatchSet after the user's changes, compare the
389 # sets, checking patches for modifications, and doing a remote
391 oldpatchset = self.patchset
392 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
394 for patch in self.patchset.patches:
396 for opatch in oldpatchset.patches:
397 if opatch["quiltfile"] == patch["quiltfile"]:
401 patch["remote"] = oldpatch["remote"]
402 if patch["quiltfile"] == oldpatch["quiltfile"]:
403 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
404 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
405 # user change? remote refresh
406 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
408 # User did not fix the problem. Abort.
409 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
416 g["PatchSet"] = PatchSet
417 g["PatchTree"] = PatchTree
418 g["QuiltTree"] = QuiltTree
419 g["Resolver"] = Resolver
420 g["UserResolver"] = UserResolver
421 g["NOOPResolver"] = NOOPResolver
422 g["NotFoundError"] = NotFoundError
423 g["CmdError"] = CmdError
425 addtask patch after do_unpack
426 do_patch[dirs] = "${WORKDIR}"
428 PATCHDEPENDENCY = "${PATCHTOOL}-native:do_populate_staging"
429 do_patch[depends] = "${PATCHDEPENDENCY}"
431 python patch_do_patch() {
437 src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
446 cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
449 "noop": NOOPResolver,
450 "user": UserResolver,
453 rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
455 s = bb.data.getVar('S', d, 1)
457 path = os.getenv('PATH')
458 os.putenv('PATH', bb.data.getVar('PATH', d, 1))
462 resolver = rcls(patchset)
464 workdir = bb.data.getVar('WORKDIR', d, 1)
466 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
467 if not "patch" in parm:
470 bb.fetch.init([url],d)
471 url = bb.encodeurl((type, host, path, user, pswd, []))
472 local = os.path.join('/', bb.fetch.localpath(url, d))
474 # did it need to be unpacked?
475 dots = os.path.basename(local).split(".")
476 if dots[-1] in ['gz', 'bz2', 'Z']:
477 unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
480 unpacked = bb.data.expand(unpacked, d)
488 pname = parm["pname"]
490 pname = os.path.basename(unpacked)
492 if "mindate" in parm or "maxdate" in parm:
493 pn = bb.data.getVar('PN', d, 1)
494 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
496 srcdate = bb.data.getVar('SRCDATE', d, 1)
499 srcdate = bb.data.getVar('DATE', d, 1)
501 if "maxdate" in parm and parm["maxdate"] < srcdate:
502 bb.note("Patch '%s' is outdated" % pname)
505 if "mindate" in parm and parm["mindate"] > srcdate:
506 bb.note("Patch '%s' is predated" % pname)
511 srcrev = bb.data.getVar('SRCREV', d, 1)
512 if srcrev and srcrev < parm["minrev"]:
513 bb.note("Patch '%s' applies to later revisions" % pname)
517 srcrev = bb.data.getVar('SRCREV', d, 1)
518 if srcrev and srcrev > parm["maxrev"]:
519 bb.note("Patch '%s' applies to earlier revisions" % pname)
522 bb.note("Applying patch '%s' (%s)" % (pname, unpacked))
524 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
527 raise bb.build.FuncFailed(str(sys.exc_value))
531 EXPORT_FUNCTIONS do_patch