patch.bbclass: Fix errors when reapplying patches
[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, 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                         if self._current is not None:
121                                 i = self._current + 1
122                         else:
123                                 i = 0
124                         self.patches.insert(i, patch)
125
126                 def _applypatch(self, patch, force = None, reverse = None):
127                         shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']]
128                         if reverse:
129                                 shellcmd.append('-R')
130
131                         if not force:
132                                 shellcmd.append('--dry-run')
133
134                         output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
135
136                         if force:
137                                 return
138
139                         shellcmd.pop(len(shellcmd) - 1)
140                         output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir)
141                         return output
142
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)
146                         if all:
147                                 for i in self.patches:
148                                         if self._current is not None:
149                                                 self._current = self._current + 1
150                                         else:
151                                                 self._current = 0
152                                         bb.note("applying patch %s" % i)
153                                         self._applypatch(i, force)
154                         else:
155                                 if self._current is not None:
156                                         self._current = self._current + 1
157                                 else:
158                                         self._current = 0
159                                 bb.note("applying patch %s" % self.patches[self._current])
160                                 self._applypatch(self.patches[self._current], force)
161
162
163                 def Pop(self, force = None, all = None):
164                         if all:
165                                 for i in self.patches:
166                                         self._applypatch(i, force, True)
167                         else:
168                                 self._applypatch(self.patches[self._current], force, True)
169
170                 def Clean(self):
171                         """"""
172
173         class QuiltTree(PatchSet):
174                 def _runcmd(self, args):
175                         runcmd(["quilt"] + args, self.dir)
176
177                 def _quiltpatchpath(self, file):
178                         return os.path.join(self.dir, "patches", os.path.basename(file))
179
180
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):
186                                 os.makedirs(p)
187
188                 def Clean(self):
189                         try:
190                                 self._runcmd(["pop", "-a", "-f"])
191                         except Exception:
192                                 pass
193                         self.initialized = True
194
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():
203                                         patch = {}
204                                         parts = line.strip().split()
205                                         patch["quiltfile"] = self._quiltpatchpath(parts[0])
206                                         patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
207                                         if len(parts) > 1:
208                                                 patch["strippath"] = parts[1][2:]
209                                         self.patches.append(patch)
210                                 series.close()
211
212                                 # determine which patches are applied -> self._current
213                                 try:
214                                         output = runcmd(["quilt", "applied"], self.dir)
215                                 except CmdError:
216                                         if sys.exc_value.output.strip() == "No patches applied":
217                                                 return
218                                         else:
219                                                 raise sys.exc_value
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
225
226                 def Import(self, patch, force = None):
227                         if not self.initialized:
228                                 self.InitFromDir()
229                         PatchSet.Import(self, patch, force)
230
231                         args = ["import", "-p", patch["strippath"]]
232                         if force:
233                                 args.append("-f")
234                                 args.append("-dn")
235                         args.append(patch["file"])
236
237                         self._runcmd(args)
238
239                         patch["quiltfile"] = self._quiltpatchpath(patch["file"])
240                         patch["quiltfilemd5"] = md5sum(patch["quiltfile"])
241
242                         # TODO: determine if the file being imported:
243                         #          1) is already imported, and is the same
244                         #          2) is already imported, but differs
245
246                         self.patches.insert(self._current or 0, patch)
247
248
249                 def Push(self, force = None, all = None):
250                         # quilt push [-f]
251
252                         args = ["push"]
253                         if force:
254                                 args.append("-f")
255                         if all:
256                                 args.append("-a")
257
258                         self._runcmd(args)
259
260                         if self._current is not None:
261                                 self._current = self._current + 1
262                         else:
263                                 self._current = 0
264
265                 def Pop(self, force = None, all = None):
266                         # quilt pop [-f]
267                         args = ["pop"]
268                         if force:
269                                 args.append("-f")
270                         if all:
271                                 args.append("-a")
272
273                         self._runcmd(args)
274
275                         if self._current == 0:
276                                 self._current = None
277
278                         if self._current is not None:
279                                 self._current = self._current - 1
280
281                 def Refresh(self, **kwargs):
282                         if kwargs.get("remote"):
283                                 patch = self.patches[kwargs["patch"]]
284                                 if not 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"])
287                                 if type == "file":
288                                         import shutil
289                                         if not patch.get("file") and patch.get("remote"):
290                                                 patch["file"] = bb.fetch.localpath(patch["remote"], self.d)
291
292                                         shutil.copyfile(patch["quiltfile"], patch["file"])
293                                 else:
294                                         raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type))
295                         else:
296                                 # quilt refresh
297                                 args = ["refresh"]
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"]))
302                                 self._runcmd(args)
303
304         class Resolver(object):
305                 def __init__(self, patchset):
306                         raise NotImplementedError()
307
308                 def Resolve(self):
309                         raise NotImplementedError()
310
311                 def Revert(self):
312                         raise NotImplementedError()
313
314                 def Finalize(self):
315                         raise NotImplementedError()
316
317         class NOOPResolver(Resolver):
318                 def __init__(self, patchset):
319                         self.patchset = patchset
320
321                 def Resolve(self):
322                         olddir = os.path.abspath(os.curdir)
323                         os.chdir(self.patchset.dir)
324                         try:
325                                 self.patchset.Push()
326                         except Exception:
327                                 os.chdir(olddir)
328                                 raise sys.exc_value
329
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
332         # files (the urls).
333         class UserResolver(Resolver):
334                 def __init__(self, patchset):
335                         self.patchset = patchset
336
337                 # Force a push in the patchset, then drop to a shell for the user to
338                 # resolve any rejected hunks
339                 def Resolve(self):
340
341                         olddir = os.path.abspath(os.curdir)
342                         os.chdir(self.patchset.dir)
343                         try:
344                                 self.patchset.Push(True)
345                         except CmdError, v:
346                                 # Patch application failed
347                                 if sys.exc_value.output.strip() == "No patches applied":
348                                         return
349                                 print(sys.exc_value)
350                                 print('NOTE: dropping user into a shell, so that patch rejects can be fixed manually.')
351
352                                 os.system('/bin/sh')
353
354                                 # Construct a new PatchSet after the user's changes, compare the
355                                 # sets, checking patches for modifications, and doing a remote
356                                 # refresh on each.
357                                 oldpatchset = self.patchset
358                                 self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d)
359
360                                 for patch in self.patchset.patches:
361                                         oldpatch = None
362                                         for opatch in oldpatchset.patches:
363                                                 if opatch["quiltfile"] == patch["quiltfile"]:
364                                                         oldpatch = opatch
365
366                                         if oldpatch:
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))
373                                                         else:
374                                                                 # User did not fix the problem.  Abort.
375                                                                 raise PatchError("Patch application failed, and user did not fix and refresh the patch.")
376                         except Exception:
377                                 os.chdir(olddir)
378                                 raise
379                         os.chdir(olddir)
380
381         g = globals()
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
390
391 addtask patch after do_unpack
392 do_patch[dirs] = "${WORKDIR}"
393 python patch_do_patch() {
394         import re
395         import bb.fetch
396
397         patch_init(d)
398
399         src_uri = (bb.data.getVar('SRC_URI', d, 1) or '').split()
400         if not src_uri:
401                 return
402
403         patchsetmap = {
404                 "patch": PatchTree,
405                 "quilt": QuiltTree,
406         }
407
408         cls = patchsetmap[bb.data.getVar('PATCHTOOL', d, 1) or 'quilt']
409
410         resolvermap = {
411                 "noop": NOOPResolver,
412                 "user": UserResolver,
413         }
414
415         rcls = resolvermap[bb.data.getVar('PATCHRESOLVE', d, 1) or 'user']
416
417         s = bb.data.getVar('S', d, 1)
418
419         path = os.getenv('PATH')
420         os.putenv('PATH', bb.data.getVar('PATH', d, 1))
421         patchset = cls(s, d)
422         patchset.Clean()
423
424         resolver = rcls(patchset)
425
426         workdir = bb.data.getVar('WORKDIR', d, 1)
427         for url in src_uri:
428                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
429                 if not "patch" in parm:
430                         continue
431
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))
435
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]))
440                 else:
441                         unpacked = local
442                 unpacked = bb.data.expand(unpacked, d)
443
444                 if "pnum" in parm:
445                         pnum = parm["pnum"]
446                 else:
447                         pnum = "1"
448
449                 if "pname" in parm:
450                         pname = parm["pname"]
451                 else:
452                         pname = os.path.basename(unpacked)
453
454                 if "mindate" in parm:
455                         mindate = parm["mindate"]
456                 else:
457                         mindate = 0
458
459                 if "maxdate" in parm:
460                         maxdate = parm["maxdate"]
461                 else:
462                         maxdate = "20711226"
463
464                 pn = bb.data.getVar('PN', d, 1)
465                 srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
466
467                 if not srcdate:
468                         srcdate = bb.data.getVar('SRCDATE', d, 1)
469
470                 if srcdate == "now":
471                         srcdate = bb.data.getVar('DATE', d, 1)
472
473                 if (maxdate < srcdate) or (mindate > srcdate):
474                         if (maxdate < srcdate):
475                                 bb.note("Patch '%s' is outdated" % pname)
476
477                         if (mindate > srcdate):
478                                 bb.note("Patch '%s' is predated" % pname)
479
480                         continue
481
482                 bb.note("Applying patch '%s'" % pname)
483                 try:
484                         patchset.Import({"file":unpacked, "remote":url, "strippath": pnum}, True)
485                 except NotFoundError:
486                         import sys
487                         raise bb.build.FuncFailed(str(sys.exc_value))
488                 resolver.Resolve()
489 }
490
491 EXPORT_FUNCTIONS do_patch