merge of '8c9fa400aa857e0110b0a702db34db034b841697'
[vuplus_openembedded] / classes / patch.bbclass
1 # Copyright (C) 2006  OpenedHand LTD
2
3 def patch_init(d):
4         import os, sys
5
6         def md5sum(fname):
7                 import md5, sys
8
9                 f = file(fname, 'rb')
10                 m = md5.new()
11                 while True:
12                         d = f.read(8096)
13                         if not d:
14                                 break
15                         m.update(d)
16                 f.close()
17                 return m.hexdigest()
18
19         class CmdError(Exception):
20                 def __init__(self, exitstatus, output):
21                         self.status = exitstatus
22                         self.output = output
23
24                 def __str__(self):
25                         return "Command Error: exit status: %d  Output:\n%s" % (self.status, self.output)
26
27         class NotFoundError(Exception):
28                 def __init__(self, path):
29                         self.path = path
30                 def __str__(self):
31                         return "Error: %s not found." % self.path
32
33         def runcmd(args, dir = None):
34                 import commands
35
36                 if dir:
37                         olddir = os.path.abspath(os.curdir)
38                         if not os.path.exists(dir):
39                                 raise NotFoundError(dir)
40                         os.chdir(dir)
41                         # print("cwd: %s -> %s" % (olddir, self.dir))
42
43                 try:
44                         args = [ commands.mkarg(str(arg)) for arg in args ]
45                         cmd = " ".join(args)
46                         # print("cmd: %s" % cmd)
47                         (exitstatus, output) = commands.getstatusoutput(cmd)
48                         if exitstatus != 0:
49                                 raise CmdError(exitstatus >> 8, output)
50                         return output
51
52                 finally:
53                         if dir:
54                                 os.chdir(olddir)
55
56         class PatchError(Exception):
57                 def __init__(self, msg):
58                         self.msg = msg
59
60                 def __str__(self):
61                         return "Patch Error: %s" % self.msg
62
63         import bb, bb.data, bb.fetch
64
65         class PatchSet(object):
66                 defaults = {
67                         "strippath": 1
68                 }
69
70                 def __init__(self, dir, d):
71                         self.dir = dir
72                         self.d = d
73                         self.patches = []
74                         self._current = None
75
76                 def current(self):
77                         return self._current
78
79                 def Clean(self):
80                         """
81                         Clean out the patch set.  Generally includes unapplying all
82                         patches and wiping out all associated metadata.
83                         """
84                         raise NotImplementedError()
85
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.")
90                                 else:
91                                         patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
92
93                         for param in PatchSet.defaults:
94                                 if not patch.get(param):
95                                         patch[param] = PatchSet.defaults[param]
96
97                         if patch.get("remote"):
98                                 patch["file"] = bb.data.expand(bb.fetch.localpath(patch["remote"], self.d), self.d)
99
100                         patch["filemd5"] = md5sum(patch["file"])
101
102                 def Push(self, force):
103                         raise NotImplementedError()
104
105                 def Pop(self, force):
106                         raise NotImplementedError()
107
108                 def Refresh(self, remote = None, all = None):
109                         raise NotImplementedError()
110
111
112         class PatchTree(PatchSet):
113                 def __init__(self, dir, d):
114                         PatchSet.__init__(self, dir, d)
115
116                 def Import(self, patch, force = None):
117                         """"""
118                         PatchSet.Import(self, patch, force)
119
120                         self.patches.insert(self._current or 0, patch)
121
122                 def _applypatch(self, patch, force = None, reverse = None):
123                         shellcmd = ["patch", "<", patch['file'], "-p", patch['strippath']]
124                         if reverse:
125                                 shellcmd.append('-R')
126                         shellcmd.append('--dry-run')
127
128                         try:
129                                 output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
130                         except CmdError:
131                                 if force:
132                                         shellcmd.pop(len(shellcmd) - 1)
133                                         output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
134                                 else:
135                                         import sys
136                                         raise sys.exc_value
137
138                         return output
139
140                 def Push(self, force = None, all = None):
141                         if all:
142                                 for i in self.patches:
143                                         if self._current is not None:
144                                                 self._current = self._current + 1
145                                         else:
146                                                 self._current = 0
147                                         self._applypatch(i, force)
148                         else:
149                                 if self._current is not None:
150                                         self._current = self._current + 1
151                                 else:
152                                         self._current = 0
153                                 self._applypatch(self.patches[self._current], force)
154
155
156                 def Pop(self, force = None, all = None):
157                         if all:
158                                 for i in self.patches:
159                                         self._applypatch(i, force, True)
160                         else:
161                                 self._applypatch(self.patches[self._current], force, True)
162
163                 def Clean(self):
164                         """"""
165
166         class QuiltTree(PatchSet):
167                 def _runcmd(self, args):
168                         runcmd(["quilt"] + args, self.dir)
169
170                 def _quiltpatchpath(self, file):
171                         return os.path.join(self.dir, "patches", os.path.basename(file))
172
173
174                 def __init__(self, dir, d):
175                         PatchSet.__init__(self, dir, d)
176                         self.initialized = False
177
178                 def Clean(self):
179                         try:
180                                 self._runcmd(["pop", "-a", "-f"])
181                         except CmdError:
182                                 pass
183                         except NotFoundError:
184                                 pass
185                         # runcmd(["rm", "-rf", os.path.join(self.dir, "patches"), os.path.join(self.dir, ".pc")])
186                         self.initialized = True
187
188                 def InitFromDir(self):
189                         # read series -> self.patches
190                         seriespath = os.path.join(self.dir, 'patches', 'series')
191                         if not os.path.exists(self.dir):
192                                 raise Exception("Error: %s does not exist." % self.dir)
193                         if os.path.exists(seriespath):
194                                 series = file(seriespath, 'r')
195                                 for line in series.readlines():
196                                         patch = {}
197                                         parts = line.strip().split()
198                                         patch["quiltfile"] = self._quiltpatchpath(parts[0])
199                                         patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
200                                         if len(parts) > 1:
201                                                 patch["strippath"] = parts[1][2:]
202                                         self.patches.append(patch)
203                                 series.close()
204
205                                 # determine which patches are applied -> self._current
206                                 try:
207                                         output = runcmd(["quilt", "applied"], self.dir)
208                                 except CmdError:
209                                         if sys.exc_value.output.strip() == "No patches applied":
210                                                 return
211                                         else:
212                                                 raise sys.exc_value
213                                 output = [val for val in output.split('\n') if not val.startswith('#')]
214                                 for patch in self.patches:
215                                         if os.path.basename(patch["quiltfile"]) == output[-1]:
216                                                 self._current = self.patches.index(patch)
217                         self.initialized = True
218
219                 def Import(self, patch, force = None):
220                         if not self.initialized:
221                                 self.InitFromDir()
222                         PatchSet.Import(self, patch, force)
223
224                         args = ["import", "-p", patch["strippath"]]
225                         if force:
226                                 args.append("-f")
227                         args.append(patch["file"])
228
229                         self._runcmd(args)
230
231                         patch["quiltfile"] = self._quiltpatchpath(patch["file"])
232                         patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
233
234                         # TODO: determine if the file being imported:
235                         #          1) is already imported, and is the same
236                         #          2) is already imported, but differs
237
238                         self.patches.insert(self._current or 0, patch)
239
240
241                 def Push(self, force = None, all = None):
242                         # quilt push [-f]
243
244                         args = ["push"]
245                         if force:
246                                 args.append("-f")
247                         if all:
248                                 args.append("-a")
249
250                         self._runcmd(args)
251
252                         if self._current is not None:
253                                 self._current = self._current + 1
254                         else:
255                                 self._current = 0
256
257                 def Pop(self, force = None, all = None):
258                         # quilt pop [-f]
259                         args = ["pop"]
260                         if force:
261                                 args.append("-f")
262                         if all:
263                                 args.append("-a")
264
265                         self._runcmd(args)
266
267                         if self._current == 0:
268                                 self._current = None
269
270                         if self._current is not None:
271                                 self._current = self._current - 1
272
273                 def Refresh(self, **kwargs):
274                         if kwargs.get("remote"):
275                                 patch = self.patches[kwargs["patch"]]
276                                 if not patch:
277                                         raise PatchError("No patch found at index %s in patchset." % kwargs["patch"])
278                                 (type, host, path, user, pswd, parm) = bb.decodeurl(patch["remote"])
279                                 if type == "file":
280                                         import shutil
281                                         if not patch.get("file") and patch.get("remote"):
282                                                 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
283
284                                         shutil.copyfile(patch["quiltfile"], patch["file"])
285                                 else:
286                                         raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
287                         else:
288                                 # quilt refresh
289                                 args = ["refresh"]
290                                 if kwargs.get("quiltfile"):
291                                         args.append(os.path.basename(kwargs["quiltfile"]))
292                                 elif kwargs.get("patch"):
293                                         args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"]))
294                                 self._runcmd(args)
295
296         class Resolver(object):
297                 def __init__(self, patchset):
298                         raise NotImplementedError()
299
300                 def Resolve(self):
301                         raise NotImplementedError()
302
303                 def Revert(self):
304                         raise NotImplementedError()
305
306                 def Finalize(self):
307                         raise NotImplementedError()
308
309         # Patch resolver which relies on the user doing all the work involved in the
310         # resolution, with the exception of refreshing the remote copy of the patch
311         # files (the urls).
312         class UserResolver(Resolver):
313                 def __init__(self, patchset):
314                         self.patchset = patchset
315
316                 # Force a push in the patchset, then drop to a shell for the user to
317                 # resolve any rejected hunks
318                 def Resolve(self):
319
320                         olddir = os.path.abspath(os.curdir)
321                         os.chdir(self.patchset.dir)
322                         try:
323                                 self.patchset.Push(True)
324                         except CmdError, v:
325                                 # Patch application failed
326                                 if sys.exc_value.output.strip() == "No patches applied":
327                                         return
328                                 print(sys.exc_value)
329                                 print('NOTE: dropping user into a shell, so that patch rejects can be fixed manually.')
330
331                                 os.system('/bin/sh')
332
333                                 # Construct a new PatchSet after the user's changes, compare the
334                                 # sets, checking patches for modifications, and doing a remote
335                                 # refresh on each.
336                                 oldpatchset = self.patchset
337                                 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
338
339                                 for patch in self.patchset.patches:
340                                         oldpatch = None
341                                         for opatch in oldpatchset.patches:
342                                                 if opatch["quiltfile"] == patch["quiltfile"]:
343                                                         oldpatch = opatch
344
345                                         if oldpatch:
346                                                 patch["remote"] = oldpatch["remote"]
347                                                 if patch["quiltfile"] == oldpatch["quiltfile"]:
348                                                         if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]:
349                                                                 bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"]))
350                                                                 # user change?  remote refresh
351                                                                 self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch))
352                                                         else:
353                                                                 # User did not fix the problem.  Abort.
354                                                                 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
355                         except Exception:
356                                 os.chdir(olddir)
357                                 raise
358                         os.chdir(olddir)
359
360                 # Throw away the changes to the patches in the patchset made by resolve()
361                 def Revert(self):
362                         raise NotImplementedError()
363
364                 # Apply the changes to the patches in the patchset made by resolve()
365                 def Finalize(self):
366                         raise NotImplementedError()
367
368         g = globals()
369         g["PatchSet"] = PatchSet
370         g["PatchTree"] = PatchTree
371         g["QuiltTree"] = QuiltTree
372         g["Resolver"] = Resolver
373         g["UserResolver"] = UserResolver
374         g["NotFoundError"] = NotFoundError
375         g["CmdError"] = CmdError
376
377 addtask patch after do_unpack
378 do_patch[dirs] = "${WORKDIR}"
379 python patch_do_patch() {
380         import re
381         import bb.fetch
382
383         patch_init(d)
384
385         src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
386         if not src_uri:
387                 return
388
389         patchsetmap = {
390                 "patch": PatchTree,
391                 "quilt": QuiltTree,
392         }
393
394         cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
395
396         resolvermap = {
397                 "user": UserResolver,
398         }
399
400         rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
401
402         s = bb.data.getVar('S', d, 1)
403
404         path = os.getenv('PATH')
405         os.putenv('PATH', bb.data.getVar('PATH', d, 1))
406         patchset = cls(s, d)
407         patchset.Clean()
408
409         resolver = rcls(patchset)
410
411         workdir = bb.data.getVar('WORKDIR', d, 1)
412         for url in src_uri:
413                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
414                 if not "patch" in parm:
415                         continue
416
417                 bb.fetch.init([url],d)
418                 url = bb.encodeurl((type, host, path, user, pswd, []))
419                 local = os.path.join('/', bb.fetch.localpath(url, d))
420
421                 # did it need to be unpacked?
422                 dots = os.path.basename(local).split(".")
423                 if dots[-1] in ['gz', 'bz2', 'Z']:
424                         unpacked = os.path.join(bb.data.getVar('WORKDIR', d),'.'.join(dots[0:-1]))
425                 else:
426                         unpacked = local
427                 unpacked = bb.data.expand(unpacked, d)
428
429                 if "pnum" in parm:
430                         pnum = parm["pnum"]
431                 else:
432                         pnum = "1"
433
434                 if "pname" in parm:
435                         pname = parm["pname"]
436                 else:
437                         pname = os.path.basename(unpacked)
438
439                 if "mindate" in parm:
440                         mindate = parm["mindate"]
441                 else:
442                         mindate = 0
443
444                 if "maxdate" in parm:
445                         maxdate = parm["maxdate"]
446                 else:
447                         maxdate = "20711226"
448
449                 pn = bb.data.getVar('PN', d, 1)
450                 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
451
452                 if not srcdate:
453                         srcdate = bb.data.getVar('SRCDATE', d, 1)
454
455                 if srcdate == "now":
456                         srcdate = bb.data.getVar('DATE', d, 1)
457
458                 if (maxdate < srcdate) or (mindate > srcdate):
459                         if (maxdate < srcdate):
460                                 bb.note("Patch '%s' is outdated" % pname)
461
462                         if (mindate > srcdate):
463                                 bb.note("Patch '%s' is predated" % pname)
464
465                         continue
466
467                 bb.note("Applying patch '%s'" % pname)
468                 try:
469                         patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
470                 except NotFoundError:
471                         import sys
472                         raise bb.build.FuncFailed(str(sys.exc_value))
473                 resolver.Resolve()
474 }
475
476 EXPORT_FUNCTIONS do_patch