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, 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"]]
235 args.append(patch["file"])
239 patch["quiltfile"] = self._quiltpatchpath(patch["file"])
240 patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
242 # TODO: determine if the file being imported:
243 # 1) is already imported, and is the same
244 # 2) is already imported, but differs
246 self.patches.insert(self._current or 0, patch)
249 def Push(self, force = None, all = None):
260 if self._current is not None:
261 self._current = self._current + 1
265 def Pop(self, force = None, all = None):
275 if self._current == 0:
278 if self._current is not None:
279 self._current = self._current - 1
281 def Refresh(self, **kwargs):
282 if kwargs.get("remote"):
283 patch = self.patches[kwargs["patch"]]
285 raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
286 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
289 if not patch.get("file") and patch.get("remote"):
290 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
292 shutil.copyfile(patch["quiltfile"], patch["file"])
294 raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
298 if kwargs.get("quiltfile"):
299 args.append(os.path.basename(kwargs["quiltfile"]))
300 elif kwargs.get("patch"):
301 args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
304 class Resolver(object):
305 def __init__(self, patchset):
306 raise NotImplementedError()
309 raise NotImplementedError()
312 raise NotImplementedError()
315 raise NotImplementedError()
317 class NOOPResolver(Resolver):
318 def __init__(self, patchset):
319 self.patchset = patchset
322 olddir = os.path.abspath(os.curdir)
323 os.chdir(self.patchset.dir)
330 # Patch resolver which relies on the user doing all the work involved in the
331 # resolution, with the exception of refreshing the remote copy of the patch
333 class UserResolver(Resolver):
334 def __init__(self, patchset):
335 self.patchset = patchset
337 # Force a push in the patchset, then drop to a shell for the user to
338 # resolve any rejected hunks
341 olddir = os.path.abspath(os.curdir)
342 os.chdir(self.patchset.dir)
344 self.patchset.Push(True)
346 # Patch application failed
347 if sys.exc_value.output.strip() == "No patches applied":
350 print('NOTE: dropping user into a shell, so that patch rejects can be fixed manually.')
354 # Construct a new PatchSet after the user's changes, compare the
355 # sets, checking patches for modifications, and doing a remote
357 oldpatchset = self.patchset
358 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
360 for patch in self.patchset.patches:
362 for opatch in oldpatchset.patches:
363 if opatch["quiltfile"] == patch["quiltfile"]:
367 patch["remote"] = oldpatch["remote"]
368 if patch["quiltfile"] == oldpatch["quiltfile"]:
369 if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
370 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
371 # user change? remote refresh
372 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
374 # User did not fix the problem. Abort.
375 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
382 g["PatchSet"] = PatchSet
383 g["PatchTree"] = PatchTree
384 g["QuiltTree"] = QuiltTree
385 g["Resolver"] = Resolver
386 g["UserResolver"] = UserResolver
387 g["NOOPResolver"] = NOOPResolver
388 g["NotFoundError"] = NotFoundError
389 g["CmdError"] = CmdError
391 addtask patch after do_unpack
392 do_patch[dirs] = "${WORKDIR}"
393 python patch_do_patch() {
399 src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
408 cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
411 "noop": NOOPResolver,
412 "user": UserResolver,
415 rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
417 s = bb.data.getVar('S', d, 1)
419 path = os.getenv('PATH')
420 os.putenv('PATH', bb.data.getVar('PATH', d, 1))
424 resolver = rcls(patchset)
426 workdir = bb.data.getVar('WORKDIR', d, 1)
428 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
429 if not "patch" in parm:
432 bb.fetch.init([url],d)
433 url = bb.encodeurl((type, host, path, user, pswd, []))
434 local = os.path.join('/', bb.fetch.localpath(url, d))
436 # did it need to be unpacked?
437 dots = os.path.basename(local).split(".")
438 if dots[-1] in ['gz', 'bz2', 'Z']:
439 unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
442 unpacked = bb.data.expand(unpacked, d)
450 pname = parm["pname"]
452 pname = os.path.basename(unpacked)
454 if "mindate" in parm:
455 mindate = parm["mindate"]
459 if "maxdate" in parm:
460 maxdate = parm["maxdate"]
464 pn = bb.data.getVar('PN', d, 1)
465 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
468 srcdate = bb.data.getVar('SRCDATE', d, 1)
471 srcdate = bb.data.getVar('DATE', d, 1)
473 if (maxdate < srcdate) or (mindate > srcdate):
474 if (maxdate < srcdate):
475 bb.note("Patch '%s' is outdated" % pname)
477 if (mindate > srcdate):
478 bb.note("Patch '%s' is predated" % pname)
482 bb.note("Applying patch '%s'" % pname)
484 patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
485 except NotFoundError:
487 raise bb.build.FuncFailed(str(sys.exc_value))
491 EXPORT_FUNCTIONS do_patch