1 # Copyright (C) 2006 OpenedHand LTD
19 class CmdError(Exception):
20 def __init__(self, exitstatus, output):
21 self.status = exitstatus
25 return "Command Error: exit status: %d Output:\n%s" % (self.status, self.output)
27 class NotFoundError(Exception):
28 def __init__(self, path):
31 return "Error: %s not found." % self.path
33 def runcmd(args, dir = None):
37 olddir = os.path.abspath(os.curdir)
38 if not os.path.exists(dir):
39 raise NotFoundError(dir)
41 # print("cwd: %s -> %s" % (olddir, self.dir))
44 args = [ commands.mkarg(str(arg)) for arg in args ]
46 # print("cmd: %s" % cmd)
47 (exitstatus, output) = commands.getstatusoutput(cmd)
49 raise CmdError(exitstatus >> 8, output)
56 class PatchError(Exception):
57 def __init__(self, msg):
61 return "Patch Error: %s" % self.msg
63 import bb, bb.data, bb.fetch
65 class PatchSet(object):
70 def __init__(self, dir, d):
81 Clean out the patch set. Generally includes unapplying all
82 patches and wiping out all associated metadata.
84 raise NotImplementedError()
86 def Import(self, patch, force):
87 if not patch.get("file"):
88 if not patch.get("remote"):
89 raise PatchError("Patch file must be specified in patch import.")
91 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
93 for param in PatchSet.defaults:
94 if not patch.get(param):
95 patch[param] = PatchSet.defaults[param]
97 if patch.get("remote"):
98 patch["file"] = bb.data.expand(bb.fetch.localpath(patch["remote"], self.d), self.d)
100 patch["filemd5"] = md5sum(patch["file"])
102 def Push(self, force):
103 raise NotImplementedError()
105 def Pop(self, force):
106 raise NotImplementedError()
108 def Refresh(self, remote = None, all = None):
109 raise NotImplementedError()
112 class PatchTree(PatchSet):
113 def __init__(self, dir, d):
114 PatchSet.__init__(self, dir, d)
116 def Import(self, patch, force = None):
118 PatchSet.Import(self, patch, force)
120 if self._current is not None:
121 i = self._current + 1
124 self.patches.insert(i, patch)
126 def _applypatch(self, patch, force = None, reverse = None):
127 shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
129 shellcmd.append('-R')
132 shellcmd.append('--dry-run')
134 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
139 shellcmd.pop(len(shellcmd) - 1)
140 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
143 def Push(self, force = None, all = None):
144 bb.note("self._current is %s" % self._current)
145 bb.note("patches is %s" % self.patches)
147 for i in self.patches:
148 if self._current is not None:
149 self._current = self._current + 1
152 bb.note("applying patch %s" % i)
153 self._applypatch(i, force)
155 if self._current is not None:
156 self._current = self._current + 1
159 bb.note("applying patch %s" % self.patches[self._current])
160 self._applypatch(self.patches[self._current], force)
163 def Pop(self, force = None, all = None):
165 for i in self.patches:
166 self._applypatch(i, force, True)
168 self._applypatch(self.patches[self._current], force, True)
173 class QuiltTree(PatchSet):
174 def _runcmd(self, args):
175 runcmd(["quilt"] + args, self.dir)
177 def _quiltpatchpath(self, file):
178 return os.path.join(self.dir, "patches", os.path.basename(file))
181 def __init__(self, dir, d):
182 PatchSet.__init__(self, dir, d)
183 self.initialized = False
184 p = os.path.join(self.dir, 'patches')
185 if not os.path.exists(p):
190 self._runcmd(["pop", "-a", "-f"])
193 self.initialized = True
195 def InitFromDir(self):
196 # read series -> self.patches
197 seriespath = os.path.join(self.dir, 'patches', 'series')
198 if not os.path.exists(self.dir):
199 raise Exception("Error: %s does not exist." % self.dir)
200 if os.path.exists(seriespath):
201 series = file(seriespath, 'r')
202 for line in series.readlines():
204 parts = line.strip().split()
205 patch["quiltfile"] = self._quiltpatchpath(parts[0])
206 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
208 patch["strippath"] = parts[1][2:]
209 self.patches.append(patch)
212 # determine which patches are applied -> self._current
214 output = runcmd(["quilt", "applied"], self.dir)
216 if sys.exc_value.output.strip() == "No patches applied":
220 output = [val for val in output.split('\n') if not val.startswith('#')]
221 for patch in self.patches:
222 if os.path.basename(patch["quiltfile"]) == output[-1]:
223 self._current = self.patches.index(patch)
224 self.initialized = True
226 def Import(self, patch, force = None):
227 if not self.initialized:
229 PatchSet.Import(self, patch, force)
231 args = ["import", "-p", patch["strippath"]]
234 args.append(patch["file"])
238 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
239 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
241 # TODO: determine if the file being imported:
242 # 1) is already imported, and is the same
243 # 2) is already imported, but differs
245 self.patches.insert(self._current or 0, patch)
248 def Push(self, force = None, all = None):
259 if self._current is not None:
260 self._current = self._current + 1
264 def Pop(self, force = None, all = None):
274 if self._current == 0:
277 if self._current is not None:
278 self._current = self._current - 1
280 def Refresh(self, **kwargs):
281 if kwargs.get("remote"):
282 patch = self.patches[kwargs["patch"]]
284 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
285 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
288 if not patch.get("file") and patch.get("remote"):
289 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
291 shutil.copyfile(patch["quiltfile"], patch["file"])
293 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
297 if kwargs.get("quiltfile"):
298 args.append(os.path.basename(kwargs["quiltfile"]))
299 elif kwargs.get("patch"):
300 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
303 class Resolver(object):
304 def __init__(self, patchset):
305 raise NotImplementedError()
308 raise NotImplementedError()
311 raise NotImplementedError()
314 raise NotImplementedError()
316 class NOOPResolver(Resolver):
317 def __init__(self, patchset):
318 self.patchset = patchset
321 olddir = os.path.abspath(os.curdir)
322 os.chdir(self.patchset.dir)
329 # Patch resolver which relies on the user doing all the work involved in the
330 # resolution, with the exception of refreshing the remote copy of the patch
332 class UserResolver(Resolver):
333 def __init__(self, patchset):
334 self.patchset = patchset
336 # Force a push in the patchset, then drop to a shell for the user to
337 # resolve any rejected hunks
340 olddir = os.path.abspath(os.curdir)
341 os.chdir(self.patchset.dir)
343 self.patchset.Push(True)
345 # Patch application failed
346 if sys.exc_value.output.strip() == "No patches applied":
349 print('NOTE: dropping user into a shell, so that patch rejects can be fixed manually.')
353 # Construct a new PatchSet after the user's changes, compare the
354 # sets, checking patches for modifications, and doing a remote
356 oldpatchset = self.patchset
357 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
359 for patch in self.patchset.patches:
361 for opatch in oldpatchset.patches:
362 if opatch["quiltfile"] == patch["quiltfile"]:
366 patch["remote"] = oldpatch["remote"]
367 if patch["quiltfile"] == oldpatch["quiltfile"]:
368 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
369 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
370 # user change? remote refresh
371 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
373 # User did not fix the problem. Abort.
374 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
381 g["PatchSet"] = PatchSet
382 g["PatchTree"] = PatchTree
383 g["QuiltTree"] = QuiltTree
384 g["Resolver"] = Resolver
385 g["UserResolver"] = UserResolver
386 g["NOOPResolver"] = NOOPResolver
387 g["NotFoundError"] = NotFoundError
388 g["CmdError"] = CmdError
390 addtask patch after do_unpack
391 do_patch[dirs] = "${WORKDIR}"
392 python patch_do_patch() {
398 src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
407 cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
410 "noop": NOOPResolver,
411 "user": UserResolver,
414 rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
416 s = bb.data.getVar('S', d, 1)
418 path = os.getenv('PATH')
419 os.putenv('PATH', bb.data.getVar('PATH', d, 1))
423 resolver = rcls(patchset)
425 workdir = bb.data.getVar('WORKDIR', d, 1)
427 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
428 if not "patch" in parm:
431 bb.fetch.init([url],d)
432 url = bb.encodeurl((type, host, path, user, pswd, []))
433 local = os.path.join('/', bb.fetch.localpath(url, d))
435 # did it need to be unpacked?
436 dots = os.path.basename(local).split(".")
437 if dots[-1] in ['gz', 'bz2', 'Z']:
438 unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
441 unpacked = bb.data.expand(unpacked, d)
449 pname = parm["pname"]
451 pname = os.path.basename(unpacked)
453 if "mindate" in parm:
454 mindate = parm["mindate"]
458 if "maxdate" in parm:
459 maxdate = parm["maxdate"]
463 pn = bb.data.getVar('PN', d, 1)
464 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
467 srcdate = bb.data.getVar('SRCDATE', d, 1)
470 srcdate = bb.data.getVar('DATE', d, 1)
472 if (maxdate < srcdate) or (mindate > srcdate):
473 if (maxdate < srcdate):
474 bb.note("Patch '%s' is outdated" % pname)
476 if (mindate > srcdate):
477 bb.note("Patch '%s' is predated" % pname)
481 bb.note("Applying patch '%s'" % pname)
483 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
484 except NotFoundError:
486 raise bb.build.FuncFailed(str(sys.exc_value))
490 EXPORT_FUNCTIONS do_patch