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