Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | import oe.path |
| 2 | |
| 3 | class NotFoundError(bb.BBHandledException): |
| 4 | def __init__(self, path): |
| 5 | self.path = path |
| 6 | |
| 7 | def __str__(self): |
| 8 | return "Error: %s not found." % self.path |
| 9 | |
| 10 | class CmdError(bb.BBHandledException): |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 11 | def __init__(self, command, exitstatus, output): |
| 12 | self.command = command |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 13 | self.status = exitstatus |
| 14 | self.output = output |
| 15 | |
| 16 | def __str__(self): |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 17 | return "Command Error: '%s' exited with %d Output:\n%s" % \ |
| 18 | (self.command, self.status, self.output) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 19 | |
| 20 | |
| 21 | def runcmd(args, dir = None): |
| 22 | import pipes |
| 23 | |
| 24 | if dir: |
| 25 | olddir = os.path.abspath(os.curdir) |
| 26 | if not os.path.exists(dir): |
| 27 | raise NotFoundError(dir) |
| 28 | os.chdir(dir) |
| 29 | # print("cwd: %s -> %s" % (olddir, dir)) |
| 30 | |
| 31 | try: |
| 32 | args = [ pipes.quote(str(arg)) for arg in args ] |
| 33 | cmd = " ".join(args) |
| 34 | # print("cmd: %s" % cmd) |
| 35 | (exitstatus, output) = oe.utils.getstatusoutput(cmd) |
| 36 | if exitstatus != 0: |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 37 | raise CmdError(cmd, exitstatus >> 8, output) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 38 | return output |
| 39 | |
| 40 | finally: |
| 41 | if dir: |
| 42 | os.chdir(olddir) |
| 43 | |
| 44 | class PatchError(Exception): |
| 45 | def __init__(self, msg): |
| 46 | self.msg = msg |
| 47 | |
| 48 | def __str__(self): |
| 49 | return "Patch Error: %s" % self.msg |
| 50 | |
| 51 | class PatchSet(object): |
| 52 | defaults = { |
| 53 | "strippath": 1 |
| 54 | } |
| 55 | |
| 56 | def __init__(self, dir, d): |
| 57 | self.dir = dir |
| 58 | self.d = d |
| 59 | self.patches = [] |
| 60 | self._current = None |
| 61 | |
| 62 | def current(self): |
| 63 | return self._current |
| 64 | |
| 65 | def Clean(self): |
| 66 | """ |
| 67 | Clean out the patch set. Generally includes unapplying all |
| 68 | patches and wiping out all associated metadata. |
| 69 | """ |
| 70 | raise NotImplementedError() |
| 71 | |
| 72 | def Import(self, patch, force): |
| 73 | if not patch.get("file"): |
| 74 | if not patch.get("remote"): |
| 75 | raise PatchError("Patch file must be specified in patch import.") |
| 76 | else: |
| 77 | patch["file"] = bb.fetch2.localpath(patch["remote"], self.d) |
| 78 | |
| 79 | for param in PatchSet.defaults: |
| 80 | if not patch.get(param): |
| 81 | patch[param] = PatchSet.defaults[param] |
| 82 | |
| 83 | if patch.get("remote"): |
| 84 | patch["file"] = bb.data.expand(bb.fetch2.localpath(patch["remote"], self.d), self.d) |
| 85 | |
| 86 | patch["filemd5"] = bb.utils.md5_file(patch["file"]) |
| 87 | |
| 88 | def Push(self, force): |
| 89 | raise NotImplementedError() |
| 90 | |
| 91 | def Pop(self, force): |
| 92 | raise NotImplementedError() |
| 93 | |
| 94 | def Refresh(self, remote = None, all = None): |
| 95 | raise NotImplementedError() |
| 96 | |
| 97 | @staticmethod |
| 98 | def getPatchedFiles(patchfile, striplevel, srcdir=None): |
| 99 | """ |
| 100 | Read a patch file and determine which files it will modify. |
| 101 | Params: |
| 102 | patchfile: the patch file to read |
| 103 | striplevel: the strip level at which the patch is going to be applied |
| 104 | srcdir: optional path to join onto the patched file paths |
| 105 | Returns: |
| 106 | A list of tuples of file path and change mode ('A' for add, |
| 107 | 'D' for delete or 'M' for modify) |
| 108 | """ |
| 109 | |
| 110 | def patchedpath(patchline): |
| 111 | filepth = patchline.split()[1] |
| 112 | if filepth.endswith('/dev/null'): |
| 113 | return '/dev/null' |
| 114 | filesplit = filepth.split(os.sep) |
| 115 | if striplevel > len(filesplit): |
| 116 | bb.error('Patch %s has invalid strip level %d' % (patchfile, striplevel)) |
| 117 | return None |
| 118 | return os.sep.join(filesplit[striplevel:]) |
| 119 | |
| 120 | copiedmode = False |
| 121 | filelist = [] |
| 122 | with open(patchfile) as f: |
| 123 | for line in f: |
| 124 | if line.startswith('--- '): |
| 125 | patchpth = patchedpath(line) |
| 126 | if not patchpth: |
| 127 | break |
| 128 | if copiedmode: |
| 129 | addedfile = patchpth |
| 130 | else: |
| 131 | removedfile = patchpth |
| 132 | elif line.startswith('+++ '): |
| 133 | addedfile = patchedpath(line) |
| 134 | if not addedfile: |
| 135 | break |
| 136 | elif line.startswith('*** '): |
| 137 | copiedmode = True |
| 138 | removedfile = patchedpath(line) |
| 139 | if not removedfile: |
| 140 | break |
| 141 | else: |
| 142 | removedfile = None |
| 143 | addedfile = None |
| 144 | |
| 145 | if addedfile and removedfile: |
| 146 | if removedfile == '/dev/null': |
| 147 | mode = 'A' |
| 148 | elif addedfile == '/dev/null': |
| 149 | mode = 'D' |
| 150 | else: |
| 151 | mode = 'M' |
| 152 | if srcdir: |
| 153 | fullpath = os.path.abspath(os.path.join(srcdir, addedfile)) |
| 154 | else: |
| 155 | fullpath = addedfile |
| 156 | filelist.append((fullpath, mode)) |
| 157 | |
| 158 | return filelist |
| 159 | |
| 160 | |
| 161 | class PatchTree(PatchSet): |
| 162 | def __init__(self, dir, d): |
| 163 | PatchSet.__init__(self, dir, d) |
| 164 | self.patchdir = os.path.join(self.dir, 'patches') |
| 165 | self.seriespath = os.path.join(self.dir, 'patches', 'series') |
| 166 | bb.utils.mkdirhier(self.patchdir) |
| 167 | |
| 168 | def _appendPatchFile(self, patch, strippath): |
| 169 | with open(self.seriespath, 'a') as f: |
| 170 | f.write(os.path.basename(patch) + "," + strippath + "\n") |
| 171 | shellcmd = ["cat", patch, ">" , self.patchdir + "/" + os.path.basename(patch)] |
| 172 | runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 173 | |
| 174 | def _removePatch(self, p): |
| 175 | patch = {} |
| 176 | patch['file'] = p.split(",")[0] |
| 177 | patch['strippath'] = p.split(",")[1] |
| 178 | self._applypatch(patch, False, True) |
| 179 | |
| 180 | def _removePatchFile(self, all = False): |
| 181 | if not os.path.exists(self.seriespath): |
| 182 | return |
| 183 | with open(self.seriespath, 'r+') as f: |
| 184 | patches = f.readlines() |
| 185 | if all: |
| 186 | for p in reversed(patches): |
| 187 | self._removePatch(os.path.join(self.patchdir, p.strip())) |
| 188 | patches = [] |
| 189 | else: |
| 190 | self._removePatch(os.path.join(self.patchdir, patches[-1].strip())) |
| 191 | patches.pop() |
| 192 | with open(self.seriespath, 'w') as f: |
| 193 | for p in patches: |
| 194 | f.write(p) |
| 195 | |
| 196 | def Import(self, patch, force = None): |
| 197 | """""" |
| 198 | PatchSet.Import(self, patch, force) |
| 199 | |
| 200 | if self._current is not None: |
| 201 | i = self._current + 1 |
| 202 | else: |
| 203 | i = 0 |
| 204 | self.patches.insert(i, patch) |
| 205 | |
| 206 | def _applypatch(self, patch, force = False, reverse = False, run = True): |
| 207 | shellcmd = ["cat", patch['file'], "|", "patch", "-p", patch['strippath']] |
| 208 | if reverse: |
| 209 | shellcmd.append('-R') |
| 210 | |
| 211 | if not run: |
| 212 | return "sh" + "-c" + " ".join(shellcmd) |
| 213 | |
| 214 | if not force: |
| 215 | shellcmd.append('--dry-run') |
| 216 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 217 | try: |
| 218 | output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 219 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 220 | if force: |
| 221 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 222 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 223 | shellcmd.pop(len(shellcmd) - 1) |
| 224 | output = runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 225 | except CmdError as err: |
| 226 | raise bb.BBHandledException("Applying '%s' failed:\n%s" % |
| 227 | (os.path.basename(patch['file']), err.output)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 228 | |
| 229 | if not reverse: |
| 230 | self._appendPatchFile(patch['file'], patch['strippath']) |
| 231 | |
| 232 | return output |
| 233 | |
| 234 | def Push(self, force = False, all = False, run = True): |
| 235 | bb.note("self._current is %s" % self._current) |
| 236 | bb.note("patches is %s" % self.patches) |
| 237 | if all: |
| 238 | for i in self.patches: |
| 239 | bb.note("applying patch %s" % i) |
| 240 | self._applypatch(i, force) |
| 241 | self._current = i |
| 242 | else: |
| 243 | if self._current is not None: |
| 244 | next = self._current + 1 |
| 245 | else: |
| 246 | next = 0 |
| 247 | |
| 248 | bb.note("applying patch %s" % self.patches[next]) |
| 249 | ret = self._applypatch(self.patches[next], force) |
| 250 | |
| 251 | self._current = next |
| 252 | return ret |
| 253 | |
| 254 | def Pop(self, force = None, all = None): |
| 255 | if all: |
| 256 | self._removePatchFile(True) |
| 257 | self._current = None |
| 258 | else: |
| 259 | self._removePatchFile(False) |
| 260 | |
| 261 | if self._current == 0: |
| 262 | self._current = None |
| 263 | |
| 264 | if self._current is not None: |
| 265 | self._current = self._current - 1 |
| 266 | |
| 267 | def Clean(self): |
| 268 | """""" |
| 269 | self.Pop(all=True) |
| 270 | |
| 271 | class GitApplyTree(PatchTree): |
| 272 | patch_line_prefix = '%% original patch' |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 273 | ignore_commit_prefix = '%% ignore' |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 274 | |
| 275 | def __init__(self, dir, d): |
| 276 | PatchTree.__init__(self, dir, d) |
| 277 | |
| 278 | @staticmethod |
| 279 | def extractPatchHeader(patchfile): |
| 280 | """ |
| 281 | Extract just the header lines from the top of a patch file |
| 282 | """ |
| 283 | lines = [] |
| 284 | with open(patchfile, 'r') as f: |
| 285 | for line in f.readlines(): |
| 286 | if line.startswith('Index: ') or line.startswith('diff -') or line.startswith('---'): |
| 287 | break |
| 288 | lines.append(line) |
| 289 | return lines |
| 290 | |
| 291 | @staticmethod |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 292 | def decodeAuthor(line): |
| 293 | from email.header import decode_header |
| 294 | authorval = line.split(':', 1)[1].strip().replace('"', '') |
| 295 | return decode_header(authorval)[0][0] |
| 296 | |
| 297 | @staticmethod |
| 298 | def interpretPatchHeader(headerlines): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 299 | import re |
| 300 | author_re = re.compile('[\S ]+ <\S+@\S+\.\S+>') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 301 | outlines = [] |
| 302 | author = None |
| 303 | date = None |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 304 | subject = None |
| 305 | for line in headerlines: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 306 | if line.startswith('Subject: '): |
| 307 | subject = line.split(':', 1)[1] |
| 308 | # Remove any [PATCH][oe-core] etc. |
| 309 | subject = re.sub(r'\[.+?\]\s*', '', subject) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 310 | continue |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 311 | elif line.startswith('From: ') or line.startswith('Author: '): |
| 312 | authorval = GitApplyTree.decodeAuthor(line) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 313 | # git is fussy about author formatting i.e. it must be Name <email@domain> |
| 314 | if author_re.match(authorval): |
| 315 | author = authorval |
| 316 | continue |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 317 | elif line.startswith('Date: '): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 318 | if date is None: |
| 319 | dateval = line.split(':', 1)[1].strip() |
| 320 | # Very crude check for date format, since git will blow up if it's not in the right |
| 321 | # format. Without e.g. a python-dateutils dependency we can't do a whole lot more |
| 322 | if len(dateval) > 12: |
| 323 | date = dateval |
| 324 | continue |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 325 | elif not author and line.lower().startswith('signed-off-by: '): |
| 326 | authorval = GitApplyTree.decodeAuthor(line) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 327 | # git is fussy about author formatting i.e. it must be Name <email@domain> |
| 328 | if author_re.match(authorval): |
| 329 | author = authorval |
| 330 | outlines.append(line) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 331 | return outlines, author, date, subject |
| 332 | |
| 333 | @staticmethod |
| 334 | def prepareCommit(patchfile): |
| 335 | """ |
| 336 | Prepare a git commit command line based on the header from a patch file |
| 337 | (typically this is useful for patches that cannot be applied with "git am" due to formatting) |
| 338 | """ |
| 339 | import tempfile |
| 340 | # Process patch header and extract useful information |
| 341 | lines = GitApplyTree.extractPatchHeader(patchfile) |
| 342 | outlines, author, date, subject = GitApplyTree.interpretPatchHeader(lines) |
| 343 | if not author or not subject: |
| 344 | try: |
| 345 | shellcmd = ["git", "log", "--format=email", "--diff-filter=A", "--", patchfile] |
| 346 | out = runcmd(["sh", "-c", " ".join(shellcmd)], os.path.dirname(patchfile)) |
| 347 | except CmdError: |
| 348 | out = None |
| 349 | if out: |
| 350 | _, newauthor, newdate, newsubject = GitApplyTree.interpretPatchHeader(out.splitlines()) |
| 351 | if not author or not date: |
| 352 | # These really need to go together |
| 353 | author = newauthor |
| 354 | date = newdate |
| 355 | if not subject: |
| 356 | subject = newsubject |
| 357 | if subject: |
| 358 | outlines.insert(0, '%s\n\n' % subject.strip()) |
| 359 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 360 | # Write out commit message to a file |
| 361 | with tempfile.NamedTemporaryFile('w', delete=False) as tf: |
| 362 | tmpfile = tf.name |
| 363 | for line in outlines: |
| 364 | tf.write(line) |
| 365 | # Prepare git command |
| 366 | cmd = ["git", "commit", "-F", tmpfile] |
| 367 | # git doesn't like plain email addresses as authors |
| 368 | if author and '<' in author: |
| 369 | cmd.append('--author="%s"' % author) |
| 370 | if date: |
| 371 | cmd.append('--date="%s"' % date) |
| 372 | return (tmpfile, cmd) |
| 373 | |
| 374 | @staticmethod |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 375 | def extractPatches(tree, startcommit, outdir, paths=None): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 376 | import tempfile |
| 377 | import shutil |
| 378 | tempdir = tempfile.mkdtemp(prefix='oepatch') |
| 379 | try: |
| 380 | shellcmd = ["git", "format-patch", startcommit, "-o", tempdir] |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 381 | if paths: |
| 382 | shellcmd.append('--') |
| 383 | shellcmd.extend(paths) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 384 | out = runcmd(["sh", "-c", " ".join(shellcmd)], tree) |
| 385 | if out: |
| 386 | for srcfile in out.split(): |
| 387 | patchlines = [] |
| 388 | outfile = None |
| 389 | with open(srcfile, 'r') as f: |
| 390 | for line in f: |
| 391 | if line.startswith(GitApplyTree.patch_line_prefix): |
| 392 | outfile = line.split()[-1].strip() |
| 393 | continue |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 394 | if line.startswith(GitApplyTree.ignore_commit_prefix): |
| 395 | continue |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 396 | patchlines.append(line) |
| 397 | if not outfile: |
| 398 | outfile = os.path.basename(srcfile) |
| 399 | with open(os.path.join(outdir, outfile), 'w') as of: |
| 400 | for line in patchlines: |
| 401 | of.write(line) |
| 402 | finally: |
| 403 | shutil.rmtree(tempdir) |
| 404 | |
| 405 | def _applypatch(self, patch, force = False, reverse = False, run = True): |
| 406 | import shutil |
| 407 | |
| 408 | def _applypatchhelper(shellcmd, patch, force = False, reverse = False, run = True): |
| 409 | if reverse: |
| 410 | shellcmd.append('-R') |
| 411 | |
| 412 | shellcmd.append(patch['file']) |
| 413 | |
| 414 | if not run: |
| 415 | return "sh" + "-c" + " ".join(shellcmd) |
| 416 | |
| 417 | return runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 418 | |
| 419 | # Add hooks which add a pointer to the original patch file name in the commit message |
| 420 | reporoot = (runcmd("git rev-parse --show-toplevel".split(), self.dir) or '').strip() |
| 421 | if not reporoot: |
| 422 | raise Exception("Cannot get repository root for directory %s" % self.dir) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 423 | hooks_dir = os.path.join(reporoot, '.git', 'hooks') |
| 424 | hooks_dir_backup = hooks_dir + '.devtool-orig' |
| 425 | if os.path.lexists(hooks_dir_backup): |
| 426 | raise Exception("Git hooks backup directory already exists: %s" % hooks_dir_backup) |
| 427 | if os.path.lexists(hooks_dir): |
| 428 | shutil.move(hooks_dir, hooks_dir_backup) |
| 429 | os.mkdir(hooks_dir) |
| 430 | commithook = os.path.join(hooks_dir, 'commit-msg') |
| 431 | applyhook = os.path.join(hooks_dir, 'applypatch-msg') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 432 | with open(commithook, 'w') as f: |
| 433 | # NOTE: the formatting here is significant; if you change it you'll also need to |
| 434 | # change other places which read it back |
| 435 | f.write('echo >> $1\n') |
| 436 | f.write('echo "%s: $PATCHFILE" >> $1\n' % GitApplyTree.patch_line_prefix) |
| 437 | os.chmod(commithook, 0755) |
| 438 | shutil.copy2(commithook, applyhook) |
| 439 | try: |
| 440 | patchfilevar = 'PATCHFILE="%s"' % os.path.basename(patch['file']) |
| 441 | try: |
| 442 | shellcmd = [patchfilevar, "git", "--work-tree=%s" % reporoot, "am", "-3", "--keep-cr", "-p%s" % patch['strippath']] |
| 443 | return _applypatchhelper(shellcmd, patch, force, reverse, run) |
| 444 | except CmdError: |
| 445 | # Need to abort the git am, or we'll still be within it at the end |
| 446 | try: |
| 447 | shellcmd = ["git", "--work-tree=%s" % reporoot, "am", "--abort"] |
| 448 | runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 449 | except CmdError: |
| 450 | pass |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 451 | # git am won't always clean up after itself, sadly, so... |
| 452 | shellcmd = ["git", "--work-tree=%s" % reporoot, "reset", "--hard", "HEAD"] |
| 453 | runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 454 | # Also need to take care of any stray untracked files |
| 455 | shellcmd = ["git", "--work-tree=%s" % reporoot, "clean", "-f"] |
| 456 | runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 457 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 458 | # Fall back to git apply |
| 459 | shellcmd = ["git", "--git-dir=%s" % reporoot, "apply", "-p%s" % patch['strippath']] |
| 460 | try: |
| 461 | output = _applypatchhelper(shellcmd, patch, force, reverse, run) |
| 462 | except CmdError: |
| 463 | # Fall back to patch |
| 464 | output = PatchTree._applypatch(self, patch, force, reverse, run) |
| 465 | # Add all files |
| 466 | shellcmd = ["git", "add", "-f", "-A", "."] |
| 467 | output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 468 | # Exclude the patches directory |
| 469 | shellcmd = ["git", "reset", "HEAD", self.patchdir] |
| 470 | output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 471 | # Commit the result |
| 472 | (tmpfile, shellcmd) = self.prepareCommit(patch['file']) |
| 473 | try: |
| 474 | shellcmd.insert(0, patchfilevar) |
| 475 | output += runcmd(["sh", "-c", " ".join(shellcmd)], self.dir) |
| 476 | finally: |
| 477 | os.remove(tmpfile) |
| 478 | return output |
| 479 | finally: |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 480 | shutil.rmtree(hooks_dir) |
| 481 | if os.path.lexists(hooks_dir_backup): |
| 482 | shutil.move(hooks_dir_backup, hooks_dir) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 483 | |
| 484 | |
| 485 | class QuiltTree(PatchSet): |
| 486 | def _runcmd(self, args, run = True): |
| 487 | quiltrc = self.d.getVar('QUILTRCFILE', True) |
| 488 | if not run: |
| 489 | return ["quilt"] + ["--quiltrc"] + [quiltrc] + args |
| 490 | runcmd(["quilt"] + ["--quiltrc"] + [quiltrc] + args, self.dir) |
| 491 | |
| 492 | def _quiltpatchpath(self, file): |
| 493 | return os.path.join(self.dir, "patches", os.path.basename(file)) |
| 494 | |
| 495 | |
| 496 | def __init__(self, dir, d): |
| 497 | PatchSet.__init__(self, dir, d) |
| 498 | self.initialized = False |
| 499 | p = os.path.join(self.dir, 'patches') |
| 500 | if not os.path.exists(p): |
| 501 | os.makedirs(p) |
| 502 | |
| 503 | def Clean(self): |
| 504 | try: |
| 505 | self._runcmd(["pop", "-a", "-f"]) |
| 506 | oe.path.remove(os.path.join(self.dir, "patches","series")) |
| 507 | except Exception: |
| 508 | pass |
| 509 | self.initialized = True |
| 510 | |
| 511 | def InitFromDir(self): |
| 512 | # read series -> self.patches |
| 513 | seriespath = os.path.join(self.dir, 'patches', 'series') |
| 514 | if not os.path.exists(self.dir): |
| 515 | raise NotFoundError(self.dir) |
| 516 | if os.path.exists(seriespath): |
| 517 | with open(seriespath, 'r') as f: |
| 518 | for line in f.readlines(): |
| 519 | patch = {} |
| 520 | parts = line.strip().split() |
| 521 | patch["quiltfile"] = self._quiltpatchpath(parts[0]) |
| 522 | patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"]) |
| 523 | if len(parts) > 1: |
| 524 | patch["strippath"] = parts[1][2:] |
| 525 | self.patches.append(patch) |
| 526 | |
| 527 | # determine which patches are applied -> self._current |
| 528 | try: |
| 529 | output = runcmd(["quilt", "applied"], self.dir) |
| 530 | except CmdError: |
| 531 | import sys |
| 532 | if sys.exc_value.output.strip() == "No patches applied": |
| 533 | return |
| 534 | else: |
| 535 | raise |
| 536 | output = [val for val in output.split('\n') if not val.startswith('#')] |
| 537 | for patch in self.patches: |
| 538 | if os.path.basename(patch["quiltfile"]) == output[-1]: |
| 539 | self._current = self.patches.index(patch) |
| 540 | self.initialized = True |
| 541 | |
| 542 | def Import(self, patch, force = None): |
| 543 | if not self.initialized: |
| 544 | self.InitFromDir() |
| 545 | PatchSet.Import(self, patch, force) |
| 546 | oe.path.symlink(patch["file"], self._quiltpatchpath(patch["file"]), force=True) |
| 547 | with open(os.path.join(self.dir, "patches", "series"), "a") as f: |
| 548 | f.write(os.path.basename(patch["file"]) + " -p" + patch["strippath"] + "\n") |
| 549 | patch["quiltfile"] = self._quiltpatchpath(patch["file"]) |
| 550 | patch["quiltfilemd5"] = bb.utils.md5_file(patch["quiltfile"]) |
| 551 | |
| 552 | # TODO: determine if the file being imported: |
| 553 | # 1) is already imported, and is the same |
| 554 | # 2) is already imported, but differs |
| 555 | |
| 556 | self.patches.insert(self._current or 0, patch) |
| 557 | |
| 558 | |
| 559 | def Push(self, force = False, all = False, run = True): |
| 560 | # quilt push [-f] |
| 561 | |
| 562 | args = ["push"] |
| 563 | if force: |
| 564 | args.append("-f") |
| 565 | if all: |
| 566 | args.append("-a") |
| 567 | if not run: |
| 568 | return self._runcmd(args, run) |
| 569 | |
| 570 | self._runcmd(args) |
| 571 | |
| 572 | if self._current is not None: |
| 573 | self._current = self._current + 1 |
| 574 | else: |
| 575 | self._current = 0 |
| 576 | |
| 577 | def Pop(self, force = None, all = None): |
| 578 | # quilt pop [-f] |
| 579 | args = ["pop"] |
| 580 | if force: |
| 581 | args.append("-f") |
| 582 | if all: |
| 583 | args.append("-a") |
| 584 | |
| 585 | self._runcmd(args) |
| 586 | |
| 587 | if self._current == 0: |
| 588 | self._current = None |
| 589 | |
| 590 | if self._current is not None: |
| 591 | self._current = self._current - 1 |
| 592 | |
| 593 | def Refresh(self, **kwargs): |
| 594 | if kwargs.get("remote"): |
| 595 | patch = self.patches[kwargs["patch"]] |
| 596 | if not patch: |
| 597 | raise PatchError("No patch found at index %s in patchset." % kwargs["patch"]) |
| 598 | (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(patch["remote"]) |
| 599 | if type == "file": |
| 600 | import shutil |
| 601 | if not patch.get("file") and patch.get("remote"): |
| 602 | patch["file"] = bb.fetch2.localpath(patch["remote"], self.d) |
| 603 | |
| 604 | shutil.copyfile(patch["quiltfile"], patch["file"]) |
| 605 | else: |
| 606 | raise PatchError("Unable to do a remote refresh of %s, unsupported remote url scheme %s." % (os.path.basename(patch["quiltfile"]), type)) |
| 607 | else: |
| 608 | # quilt refresh |
| 609 | args = ["refresh"] |
| 610 | if kwargs.get("quiltfile"): |
| 611 | args.append(os.path.basename(kwargs["quiltfile"])) |
| 612 | elif kwargs.get("patch"): |
| 613 | args.append(os.path.basename(self.patches[kwargs["patch"]]["quiltfile"])) |
| 614 | self._runcmd(args) |
| 615 | |
| 616 | class Resolver(object): |
| 617 | def __init__(self, patchset, terminal): |
| 618 | raise NotImplementedError() |
| 619 | |
| 620 | def Resolve(self): |
| 621 | raise NotImplementedError() |
| 622 | |
| 623 | def Revert(self): |
| 624 | raise NotImplementedError() |
| 625 | |
| 626 | def Finalize(self): |
| 627 | raise NotImplementedError() |
| 628 | |
| 629 | class NOOPResolver(Resolver): |
| 630 | def __init__(self, patchset, terminal): |
| 631 | self.patchset = patchset |
| 632 | self.terminal = terminal |
| 633 | |
| 634 | def Resolve(self): |
| 635 | olddir = os.path.abspath(os.curdir) |
| 636 | os.chdir(self.patchset.dir) |
| 637 | try: |
| 638 | self.patchset.Push() |
| 639 | except Exception: |
| 640 | import sys |
| 641 | os.chdir(olddir) |
| 642 | raise |
| 643 | |
| 644 | # Patch resolver which relies on the user doing all the work involved in the |
| 645 | # resolution, with the exception of refreshing the remote copy of the patch |
| 646 | # files (the urls). |
| 647 | class UserResolver(Resolver): |
| 648 | def __init__(self, patchset, terminal): |
| 649 | self.patchset = patchset |
| 650 | self.terminal = terminal |
| 651 | |
| 652 | # Force a push in the patchset, then drop to a shell for the user to |
| 653 | # resolve any rejected hunks |
| 654 | def Resolve(self): |
| 655 | olddir = os.path.abspath(os.curdir) |
| 656 | os.chdir(self.patchset.dir) |
| 657 | try: |
| 658 | self.patchset.Push(False) |
| 659 | except CmdError as v: |
| 660 | # Patch application failed |
| 661 | patchcmd = self.patchset.Push(True, False, False) |
| 662 | |
| 663 | t = self.patchset.d.getVar('T', True) |
| 664 | if not t: |
| 665 | bb.msg.fatal("Build", "T not set") |
| 666 | bb.utils.mkdirhier(t) |
| 667 | import random |
| 668 | rcfile = "%s/bashrc.%s.%s" % (t, str(os.getpid()), random.random()) |
| 669 | with open(rcfile, "w") as f: |
| 670 | f.write("echo '*** Manual patch resolution mode ***'\n") |
| 671 | f.write("echo 'Dropping to a shell, so patch rejects can be fixed manually.'\n") |
| 672 | f.write("echo 'Run \"quilt refresh\" when patch is corrected, press CTRL+D to exit.'\n") |
| 673 | f.write("echo ''\n") |
| 674 | f.write(" ".join(patchcmd) + "\n") |
| 675 | os.chmod(rcfile, 0775) |
| 676 | |
| 677 | self.terminal("bash --rcfile " + rcfile, 'Patch Rejects: Please fix patch rejects manually', self.patchset.d) |
| 678 | |
| 679 | # Construct a new PatchSet after the user's changes, compare the |
| 680 | # sets, checking patches for modifications, and doing a remote |
| 681 | # refresh on each. |
| 682 | oldpatchset = self.patchset |
| 683 | self.patchset = oldpatchset.__class__(self.patchset.dir, self.patchset.d) |
| 684 | |
| 685 | for patch in self.patchset.patches: |
| 686 | oldpatch = None |
| 687 | for opatch in oldpatchset.patches: |
| 688 | if opatch["quiltfile"] == patch["quiltfile"]: |
| 689 | oldpatch = opatch |
| 690 | |
| 691 | if oldpatch: |
| 692 | patch["remote"] = oldpatch["remote"] |
| 693 | if patch["quiltfile"] == oldpatch["quiltfile"]: |
| 694 | if patch["quiltfilemd5"] != oldpatch["quiltfilemd5"]: |
| 695 | bb.note("Patch %s has changed, updating remote url %s" % (os.path.basename(patch["quiltfile"]), patch["remote"])) |
| 696 | # user change? remote refresh |
| 697 | self.patchset.Refresh(remote=True, patch=self.patchset.patches.index(patch)) |
| 698 | else: |
| 699 | # User did not fix the problem. Abort. |
| 700 | raise PatchError("Patch application failed, and user did not fix and refresh the patch.") |
| 701 | except Exception: |
| 702 | os.chdir(olddir) |
| 703 | raise |
| 704 | os.chdir(olddir) |