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 = None, reverse = None):
132 shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
134 shellcmd.append('-R')
137 shellcmd.append('--dry-run')
139 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
144 shellcmd.pop(len(shellcmd) - 1)
145 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
148 def Push(self, force = None, all = None):
149 bb.note("self._current is %s" % self._current)
150 bb.note("patches is %s" % self.patches)
152 for i in self.patches:
153 if self._current is not None:
154 self._current = self._current + 1
157 bb.note("applying patch %s" % i)
158 self._applypatch(i, force)
160 if self._current is not None:
161 self._current = self._current + 1
164 bb.note("applying patch %s" % self.patches[self._current])
165 self._applypatch(self.patches[self._current], force)
168 def Pop(self, force = None, all = None):
170 for i in self.patches:
171 self._applypatch(i, force, True)
173 self._applypatch(self.patches[self._current], force, True)
178 class QuiltTree(PatchSet):
179 def _runcmd(self, args):
180 runcmd(["quilt"] + args, self.dir)
182 def _quiltpatchpath(self, file):
183 return os.path.join(self.dir, "patches", os.path.basename(file))
186 def __init__(self, dir, d):
187 PatchSet.__init__(self, dir, d)
188 self.initialized = False
189 p = os.path.join(self.dir, 'patches')
190 if not os.path.exists(p):
195 self._runcmd(["pop", "-a", "-f"])
198 self.initialized = True
200 def InitFromDir(self):
201 # read series -> self.patches
202 seriespath = os.path.join(self.dir, 'patches', 'series')
203 if not os.path.exists(self.dir):
204 raise Exception("Error: %s does not exist." % self.dir)
205 if os.path.exists(seriespath):
206 series = file(seriespath, 'r')
207 for line in series.readlines():
209 parts = line.strip().split()
210 patch["quiltfile"] = self._quiltpatchpath(parts[0])
211 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
213 patch["strippath"] = parts[1][2:]
214 self.patches.append(patch)
217 # determine which patches are applied -> self._current
219 output = runcmd(["quilt", "applied"], self.dir)
221 if sys.exc_value.output.strip() == "No patches applied":
225 output = [val for val in output.split('\n') if not val.startswith('#')]
226 for patch in self.patches:
227 if os.path.basename(patch["quiltfile"]) == output[-1]:
228 self._current = self.patches.index(patch)
229 self.initialized = True
231 def Import(self, patch, force = None):
232 if not self.initialized:
234 PatchSet.Import(self, patch, force)
236 args = ["import", "-p", patch["strippath"]]
240 args.append(patch["file"])
244 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
245 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
247 # TODO: determine if the file being imported:
248 # 1) is already imported, and is the same
249 # 2) is already imported, but differs
251 self.patches.insert(self._current or 0, patch)
254 def Push(self, force = None, all = None):
265 if self._current is not None:
266 self._current = self._current + 1
270 def Pop(self, force = None, all = None):
280 if self._current == 0:
283 if self._current is not None:
284 self._current = self._current - 1
286 def Refresh(self, **kwargs):
287 if kwargs.get("remote"):
288 patch = self.patches[kwargs["patch"]]
290 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
291 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
294 if not patch.get("file") and patch.get("remote"):
295 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
297 shutil.copyfile(patch["quiltfile"], patch["file"])
299 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
303 if kwargs.get("quiltfile"):
304 args.append(os.path.basename(kwargs["quiltfile"]))
305 elif kwargs.get("patch"):
306 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
309 class Resolver(object):
310 def __init__(self, patchset):
311 raise NotImplementedError()
314 raise NotImplementedError()
317 raise NotImplementedError()
320 raise NotImplementedError()
322 class NOOPResolver(Resolver):
323 def __init__(self, patchset):
324 self.patchset = patchset
327 olddir = os.path.abspath(os.curdir)
328 os.chdir(self.patchset.dir)
335 # Patch resolver which relies on the user doing all the work involved in the
336 # resolution, with the exception of refreshing the remote copy of the patch
338 class UserResolver(Resolver):
339 def __init__(self, patchset):
340 self.patchset = patchset
342 # Force a push in the patchset, then drop to a shell for the user to
343 # resolve any rejected hunks
346 olddir = os.path.abspath(os.curdir)
347 os.chdir(self.patchset.dir)
349 self.patchset.Push(True)
351 # Patch application failed
352 if sys.exc_value.output.strip() == "No patches applied":
355 print('NOTE: dropping user into a shell, so that patch rejects can be fixed manually.')
359 # Construct a new PatchSet after the user's changes, compare the
360 # sets, checking patches for modifications, and doing a remote
362 oldpatchset = self.patchset
363 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
365 for patch in self.patchset.patches:
367 for opatch in oldpatchset.patches:
368 if opatch["quiltfile"] == patch["quiltfile"]:
372 patch["remote"] = oldpatch["remote"]
373 if patch["quiltfile"] == oldpatch["quiltfile"]:
374 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
375 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
376 # user change? remote refresh
377 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
379 # User did not fix the problem. Abort.
380 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
387 g["PatchSet"] = PatchSet
388 g["PatchTree"] = PatchTree
389 g["QuiltTree"] = QuiltTree
390 g["Resolver"] = Resolver
391 g["UserResolver"] = UserResolver
392 g["NOOPResolver"] = NOOPResolver
393 g["NotFoundError"] = NotFoundError
394 g["CmdError"] = CmdError
396 addtask patch after do_unpack
397 do_patch[dirs] = "${WORKDIR}"
398 python patch_do_patch() {
404 src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
413 cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
416 "noop": NOOPResolver,
417 "user": UserResolver,
420 rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
422 s = bb.data.getVar('S', d, 1)
424 path = os.getenv('PATH')
425 os.putenv('PATH', bb.data.getVar('PATH', d, 1))
429 resolver = rcls(patchset)
431 workdir = bb.data.getVar('WORKDIR', d, 1)
433 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
434 if not "patch" in parm:
437 bb.fetch.init([url],d)
438 url = bb.encodeurl((type, host, path, user, pswd, []))
439 local = os.path.join('/', bb.fetch.localpath(url, d))
441 # did it need to be unpacked?
442 dots = os.path.basename(local).split(".")
443 if dots[-1] in ['gz', 'bz2', 'Z']:
444 unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
447 unpacked = bb.data.expand(unpacked, d)
455 pname = parm["pname"]
457 pname = os.path.basename(unpacked)
459 if "mindate" in parm:
460 mindate = parm["mindate"]
464 if "maxdate" in parm:
465 maxdate = parm["maxdate"]
469 pn = bb.data.getVar('PN', d, 1)
470 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
473 srcdate = bb.data.getVar('SRCDATE', d, 1)
476 srcdate = bb.data.getVar('DATE', d, 1)
478 if (maxdate < srcdate) or (mindate > srcdate):
479 if (maxdate < srcdate):
480 bb.note("Patch '%s' is outdated" % pname)
482 if (mindate > srcdate):
483 bb.note("Patch '%s' is predated" % pname)
487 bb.note("Applying patch '%s'" % pname)
489 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
492 raise bb.build.FuncFailed(str(sys.exc_value))
496 EXPORT_FUNCTIONS do_patch