1 # Copyright (C) 2006 OpenedHand LTD
6 class NotFoundError(Exception):
7 def __init__(self, path):
10 return "Error: %s not found." % self.path
18 raise NotFoundError(fname)
29 class CmdError(Exception):
30 def __init__(self, exitstatus, output):
31 self.status = exitstatus
35 return "Command Error: exit status: %d Output:\n%s" % (self.status, self.output)
38 def runcmd(args, dir = None):
42 olddir = os.path.abspath(os.curdir)
43 if not os.path.exists(dir):
44 raise NotFoundError(dir)
46 # print("cwd: %s -> %s" % (olddir, dir))
49 args = [ commands.mkarg(str(arg)) for arg in args ]
51 # print("cmd: %s" % cmd)
52 (exitstatus, output) = commands.getstatusoutput(cmd)
54 raise CmdError(exitstatus >> 8, output)
61 class PatchError(Exception):
62 def __init__(self, msg):
66 return "Patch Error: %s" % self.msg
68 import bb, bb.data, bb.fetch
70 class PatchSet(object):
75 def __init__(self, dir, d):
86 Clean out the patch set. Generally includes unapplying all
87 patches and wiping out all associated metadata.
89 raise NotImplementedError()
91 def Import(self, patch, force):
92 if not patch.get("file"):
93 if not patch.get("remote"):
94 raise PatchError("Patch file must be specified in patch import.")
96 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
98 for param in PatchSet.defaults:
99 if not patch.get(param):
100 patch[param] = PatchSet.defaults[param]
102 if patch.get("remote"):
103 patch["file"] = bb.data.expand(bb.fetch.localpath(patch["remote"], self.d), self.d)
105 patch["filemd5"] = md5sum(patch["file"])
107 def Push(self, force):
108 raise NotImplementedError()
110 def Pop(self, force):
111 raise NotImplementedError()
113 def Refresh(self, remote = None, all = None):
114 raise NotImplementedError()
117 class PatchTree(PatchSet):
118 def __init__(self, dir, d):
119 PatchSet.__init__(self, dir, d)
121 def Import(self, patch, force = None):
123 PatchSet.Import(self, patch, force)
125 if self._current is not None:
126 i = self._current + 1
129 self.patches.insert(i, patch)
131 def _applypatch(self, patch, force = False, reverse = False, run = True):
132 shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
134 shellcmd.append('-R')
137 return "sh" + "-c" + " ".join(shellcmd)
140 shellcmd.append('--dry-run')
142 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
147 shellcmd.pop(len(shellcmd) - 1)
148 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
151 def Push(self, force = False, all = False, run = True):
152 bb.note("self._current is %s" % self._current)
153 bb.note("patches is %s" % self.patches)
155 for i in self.patches:
156 if self._current is not None:
157 self._current = self._current + 1
160 bb.note("applying patch %s" % i)
161 self._applypatch(i, force)
163 if self._current is not None:
164 self._current = self._current + 1
167 bb.note("applying patch %s" % self.patches[self._current])
168 return self._applypatch(self.patches[self._current], force)
171 def Pop(self, force = None, all = None):
173 for i in self.patches:
174 self._applypatch(i, force, True)
176 self._applypatch(self.patches[self._current], force, True)
181 class QuiltTree(PatchSet):
182 def _runcmd(self, args, run = True):
184 return ["quilt"] + args
185 runcmd(["quilt"] + args, self.dir)
187 def _quiltpatchpath(self, file):
188 return os.path.join(self.dir, "patches", os.path.basename(file))
191 def __init__(self, dir, d):
192 PatchSet.__init__(self, dir, d)
193 self.initialized = False
194 p = os.path.join(self.dir, 'patches')
195 if not os.path.exists(p):
200 self._runcmd(["pop", "-a", "-f"])
203 self.initialized = True
205 def InitFromDir(self):
206 # read series -> self.patches
207 seriespath = os.path.join(self.dir, 'patches', 'series')
208 if not os.path.exists(self.dir):
209 raise Exception("Error: %s does not exist." % self.dir)
210 if os.path.exists(seriespath):
211 series = file(seriespath, 'r')
212 for line in series.readlines():
214 parts = line.strip().split()
215 patch["quiltfile"] = self._quiltpatchpath(parts[0])
216 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
218 patch["strippath"] = parts[1][2:]
219 self.patches.append(patch)
222 # determine which patches are applied -> self._current
224 output = runcmd(["quilt", "applied"], self.dir)
226 if sys.exc_value.output.strip() == "No patches applied":
230 output = [val for val in output.split('\n') if not val.startswith('#')]
231 for patch in self.patches:
232 if os.path.basename(patch["quiltfile"]) == output[-1]:
233 self._current = self.patches.index(patch)
234 self.initialized = True
236 def Import(self, patch, force = None):
237 if not self.initialized:
239 PatchSet.Import(self, patch, force)
241 args = ["import", "-p", patch["strippath"]]
245 args.append(patch["file"])
249 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
250 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
252 # TODO: determine if the file being imported:
253 # 1) is already imported, and is the same
254 # 2) is already imported, but differs
256 self.patches.insert(self._current or 0, patch)
259 def Push(self, force = False, all = False, run = True):
268 return self._runcmd(args, run)
272 if self._current is not None:
273 self._current = self._current + 1
277 def Pop(self, force = None, all = None):
287 if self._current == 0:
290 if self._current is not None:
291 self._current = self._current - 1
293 def Refresh(self, **kwargs):
294 if kwargs.get("remote"):
295 patch = self.patches[kwargs["patch"]]
297 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
298 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
301 if not patch.get("file") and patch.get("remote"):
302 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
304 shutil.copyfile(patch["quiltfile"], patch["file"])
306 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
310 if kwargs.get("quiltfile"):
311 args.append(os.path.basename(kwargs["quiltfile"]))
312 elif kwargs.get("patch"):
313 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
316 class Resolver(object):
317 def __init__(self, patchset):
318 raise NotImplementedError()
321 raise NotImplementedError()
324 raise NotImplementedError()
327 raise NotImplementedError()
329 class NOOPResolver(Resolver):
330 def __init__(self, patchset):
331 self.patchset = patchset
334 olddir = os.path.abspath(os.curdir)
335 os.chdir(self.patchset.dir)
342 # Patch resolver which relies on the user doing all the work involved in the
343 # resolution, with the exception of refreshing the remote copy of the patch
345 class UserResolver(Resolver):
346 def __init__(self, patchset):
347 self.patchset = patchset
349 # Force a push in the patchset, then drop to a shell for the user to
350 # resolve any rejected hunks
353 olddir = os.path.abspath(os.curdir)
354 os.chdir(self.patchset.dir)
356 self.patchset.Push(False)
358 # Patch application failed
359 patchcmd = self.patchset.Push(True, False, False)
361 t = bb.data.getVar('T', d, 1)
363 bb.msg.fatal(bb.msg.domain.Build, "T not set")
366 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
367 f = open(rcfile, "w")
368 f.write("echo '*** Manual patch resolution mode ***'\n")
369 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
370 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
372 f.write(" ".join(patchcmd) + "\n")
373 f.write("#" + bb.data.getVar('TERMCMDRUN', d, 1))
375 os.chmod(rcfile, 0775)
377 os.environ['TERMWINDOWTITLE'] = "Bitbake: Please fix patch rejects manually"
378 os.environ['TERMRCFILE'] = rcfile
379 os.system(bb.data.getVar('TERMCMDRUN', d, 1))
381 # Construct a new PatchSet after the user's changes, compare the
382 # sets, checking patches for modifications, and doing a remote
384 oldpatchset = self.patchset
385 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
387 for patch in self.patchset.patches:
389 for opatch in oldpatchset.patches:
390 if opatch["quiltfile"] == patch["quiltfile"]:
394 patch["remote"] = oldpatch["remote"]
395 if patch["quiltfile"] == oldpatch["quiltfile"]:
396 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
397 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
398 # user change? remote refresh
399 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
401 # User did not fix the problem. Abort.
402 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
409 g["PatchSet"] = PatchSet
410 g["PatchTree"] = PatchTree
411 g["QuiltTree"] = QuiltTree
412 g["Resolver"] = Resolver
413 g["UserResolver"] = UserResolver
414 g["NOOPResolver"] = NOOPResolver
415 g["NotFoundError"] = NotFoundError
416 g["CmdError"] = CmdError
418 addtask patch after do_unpack
419 do_patch[dirs] = "${WORKDIR}"
423 # do_patch tasks require PATCHTOOL-native to have staged
424 patchdeps = bb.data.getVar("PATCHTOOL", d, True)
426 patchdeps = "%s-native" % patchdeps
427 if not patchdeps in bb.data.getVar("PROVIDES", d, True):
428 bb.data.setVarFlag('do_patch', 'depends', patchdeps + ":do_populate_staging", d)
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:
493 mindate = parm["mindate"]
497 if "maxdate" in parm:
498 maxdate = parm["maxdate"]
502 pn = bb.data.getVar('PN', d, 1)
503 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
506 srcdate = bb.data.getVar('SRCDATE', d, 1)
509 srcdate = bb.data.getVar('DATE', d, 1)
511 if (maxdate < srcdate) or (mindate > srcdate):
512 if (maxdate < srcdate):
513 bb.note("Patch '%s' is outdated" % pname)
515 if (mindate > srcdate):
516 bb.note("Patch '%s' is predated" % pname)
520 bb.note("Applying patch '%s'" % pname)
522 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
525 raise bb.build.FuncFailed(str(sys.exc_value))
529 EXPORT_FUNCTIONS do_patch