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 QuiltTree(PatchSet):
193 def _runcmd(self, args, run = True):
194 quiltrc = bb.data.getVar('QUILTRCFILE', self.d, 1)
196 return ["quilt"] + ["--quiltrc"] + [quiltrc] + args
197 runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir)
199 def _quiltpatchpath(self, file):
200 return os.path.join(self.dir, "patches", os.path.basename(file))
203 def __init__(self, dir, d):
204 PatchSet.__init__(self, dir, d)
205 self.initialized = False
206 p = os.path.join(self.dir, 'patches')
207 if not os.path.exists(p):
212 self._runcmd(["pop", "-a", "-f"])
215 self.initialized = True
217 def InitFromDir(self):
218 # read series -> self.patches
219 seriespath = os.path.join(self.dir, 'patches', 'series')
220 if not os.path.exists(self.dir):
221 raise Exception("Error: %s does not exist." % self.dir)
222 if os.path.exists(seriespath):
223 series = file(seriespath, 'r')
224 for line in series.readlines():
226 parts = line.strip().split()
227 patch["quiltfile"] = self._quiltpatchpath(parts[0])
228 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
230 patch["strippath"] = parts[1][2:]
231 self.patches.append(patch)
234 # determine which patches are applied -> self._current
236 output = runcmd(["quilt", "applied"], self.dir)
238 if sys.exc_value.output.strip() == "No patches applied":
242 output = [val for val in output.split('\n') if not val.startswith('#')]
243 for patch in self.patches:
244 if os.path.basename(patch["quiltfile"]) == output[-1]:
245 self._current = self.patches.index(patch)
246 self.initialized = True
248 def Import(self, patch, force = None):
249 if not self.initialized:
251 PatchSet.Import(self, patch, force)
253 args = ["import", "-p", patch["strippath"]]
257 args.append(patch["file"])
261 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
262 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
264 # TODO: determine if the file being imported:
265 # 1) is already imported, and is the same
266 # 2) is already imported, but differs
268 self.patches.insert(self._current or 0, patch)
271 def Push(self, force = False, all = False, run = True):
280 return self._runcmd(args, run)
284 if self._current is not None:
285 self._current = self._current + 1
289 def Pop(self, force = None, all = None):
299 if self._current == 0:
302 if self._current is not None:
303 self._current = self._current - 1
305 def Refresh(self, **kwargs):
306 if kwargs.get("remote"):
307 patch = self.patches[kwargs["patch"]]
309 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
310 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
313 if not patch.get("file") and patch.get("remote"):
314 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
316 shutil.copyfile(patch["quiltfile"], patch["file"])
318 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
322 if kwargs.get("quiltfile"):
323 args.append(os.path.basename(kwargs["quiltfile"]))
324 elif kwargs.get("patch"):
325 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
328 class Resolver(object):
329 def __init__(self, patchset):
330 raise NotImplementedError()
333 raise NotImplementedError()
336 raise NotImplementedError()
339 raise NotImplementedError()
341 class NOOPResolver(Resolver):
342 def __init__(self, patchset):
343 self.patchset = patchset
346 olddir = os.path.abspath(os.curdir)
347 os.chdir(self.patchset.dir)
354 # Patch resolver which relies on the user doing all the work involved in the
355 # resolution, with the exception of refreshing the remote copy of the patch
357 class UserResolver(Resolver):
358 def __init__(self, patchset):
359 self.patchset = patchset
361 # Force a push in the patchset, then drop to a shell for the user to
362 # resolve any rejected hunks
365 olddir = os.path.abspath(os.curdir)
366 os.chdir(self.patchset.dir)
368 self.patchset.Push(False)
370 # Patch application failed
371 patchcmd = self.patchset.Push(True, False, False)
373 t = bb.data.getVar('T', d, 1)
375 bb.msg.fatal(bb.msg.domain.Build, "T not set")
378 rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random())
379 f = open(rcfile, "w")
380 f.write("echo '*** Manual patch resolution mode ***'\n")
381 f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n")
382 f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n")
384 f.write(" ".join(patchcmd) + "\n")
385 f.write("#" + bb.data.getVar('TERMCMDRUN', d, 1))
387 os.chmod(rcfile, 0775)
389 os.environ['TERMWINDOWTITLE'] = "Bitbake: Please fix patch rejects manually"
390 os.environ['TERMRCFILE'] = rcfile
391 rc = os.system(bb.data.getVar('TERMCMDRUN', d, 1))
392 if os.WIFEXITED(rc) and os.WEXITSTATUS(rc) != 0:
393 bb.msg.fatal(bb.msg.domain.Build, ("Cannot proceed with manual patch resolution - '%s' not found. " \
394 + "Check TERMCMDRUN variable.") % bb.data.getVar('TERMCMDRUN', d, 1))
396 # Construct a new PatchSet after the user's changes, compare the
397 # sets, checking patches for modifications, and doing a remote
399 oldpatchset = self.patchset
400 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
402 for patch in self.patchset.patches:
404 for opatch in oldpatchset.patches:
405 if opatch["quiltfile"] == patch["quiltfile"]:
409 patch["remote"] = oldpatch["remote"]
410 if patch["quiltfile"] == oldpatch["quiltfile"]:
411 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
412 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
413 # user change? remote refresh
414 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
416 # User did not fix the problem. Abort.
417 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
424 g["PatchSet"] = PatchSet
425 g["PatchTree"] = PatchTree
426 g["QuiltTree"] = QuiltTree
427 g["Resolver"] = Resolver
428 g["UserResolver"] = UserResolver
429 g["NOOPResolver"] = NOOPResolver
430 g["NotFoundError"] = NotFoundError
431 g["CmdError"] = CmdError
433 addtask patch after do_unpack
434 do_patch[dirs] = "${WORKDIR}"
436 PATCHDEPENDENCY = "${PATCHTOOL}-native:do_populate_staging"
437 do_patch[depends] = "${PATCHDEPENDENCY}"
439 python patch_do_patch() {
445 src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
454 cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
457 "noop": NOOPResolver,
458 "user": UserResolver,
461 rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
463 s = bb.data.getVar('S', d, 1)
465 path = os.getenv('PATH')
466 os.putenv('PATH', bb.data.getVar('PATH', d, 1))
470 resolver = rcls(patchset)
472 workdir = bb.data.getVar('WORKDIR', d, 1)
474 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
475 if not "patch" in parm:
478 bb.fetch.init([url],d)
479 url = bb.encodeurl((type, host, path, user, pswd, []))
480 local = os.path.join('/', bb.fetch.localpath(url, d))
482 # did it need to be unpacked?
483 dots = os.path.basename(local).split(".")
484 if dots[-1] in ['gz', 'bz2', 'Z']:
485 unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
488 unpacked = bb.data.expand(unpacked, d)
496 pname = parm["pname"]
498 pname = os.path.basename(unpacked)
500 if "mindate" in parm or "maxdate" in parm:
501 pn = bb.data.getVar('PN', d, 1)
502 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
504 srcdate = bb.data.getVar('SRCDATE', d, 1)
507 srcdate = bb.data.getVar('DATE', d, 1)
509 if "maxdate" in parm and parm["maxdate"] < srcdate:
510 bb.note("Patch '%s' is outdated" % pname)
513 if "mindate" in parm and parm["mindate"] > srcdate:
514 bb.note("Patch '%s' is predated" % pname)
519 srcrev = bb.data.getVar('SRCREV', d, 1)
520 if srcrev and srcrev < parm["minrev"]:
521 bb.note("Patch '%s' applies to later revisions" % pname)
525 srcrev = bb.data.getVar('SRCREV', d, 1)
526 if srcrev and srcrev > parm["maxrev"]:
527 bb.note("Patch '%s' applies to earlier revisions" % pname)
530 bb.note("Applying patch '%s' (%s)" % (pname, base_path_out(unpacked, d)))
532 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
535 raise bb.build.FuncFailed(str(sys.exc_value))
539 EXPORT_FUNCTIONS do_patch