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