diff options
author | Luo Jinghua <sunmoon1997@gmail.com> | 2010-10-22 07:18:04 +0800 |
---|---|---|
committer | Luo Jinghua <sunmoon1997@gmail.com> | 2010-10-22 07:18:04 +0800 |
commit | 254eb765727f7a205724c0aa2ae83e981c009326 (patch) | |
tree | 43a91a0f7472fcbf43534a3f04cb004b6263bb2f | |
parent | bce5cfd226d4c6f6cab4aa0352b7f10c9fcc1e55 (diff) |
support -C and -p options
-rwxr-xr-x[-rw-r--r--] | patch.py | 25 |
1 files changed, 20 insertions, 5 deletions
@@ -1,3 +1,5 @@ +#!/bin/env python + """ Patch utility to apply unified diffs Brute-force line-by-line non-recursive parsing @@ -374,17 +376,26 @@ class Patch(object): debug("total files: %d total hunks: %d" % (len(self.source), sum(len(hset) for hset in self.hunks))) - def apply(self): + def apply(self, basedir = '.', strip = 0): """ apply parsed patch """ + def strippath(path, basedir, strip): + import os.path + path = os.path.normpath(path) + if strip: + path = os.path.sep.join(path.split(os.path.sep)[strip:]) + if basedir == '.': + return path + return os.path.join(basedir, path) + total = len(self.source) for fileno, filename in enumerate(self.source): - f2patch = filename + f2patch = strippath(filename, basedir, strip) if not exists(f2patch): - f2patch = self.target[fileno] + f2patch = strippath(self.target[fileno], basedir, strip) if not exists(f2patch): - warning("source/target file does not exist\n--- %s\n+++ %s" % (filename, f2patch)) + warning("source/target file does not exist\n--- %s\n+++ %s" % (filename, self.target[fileno])) continue if not isfile(f2patch): warning("not a file - %s" % f2patch) @@ -626,6 +637,10 @@ if __name__ == "__main__": const=0, help="print only warnings and errors", default=1) opt.add_option("-v", "--verbose", action="store_const", dest="verbosity", const=2, help="be verbose") + opt.add_option("-p", dest="strip", type="int", default=0, + help="trip NUM leading components from file names") + opt.add_option("-C", dest="basedir", default=".", + help="Change to specified directory before applying the patch") opt.add_option("--debug", action="store_true", dest="debugmode", help="debug mode") (options, args) = opt.parse_args() @@ -652,7 +667,7 @@ if __name__ == "__main__": patch = fromfile(patchfile) #pprint(patch) - patch.apply() + patch.apply(options.basedir, options.strip) # todo: document and test line ends handling logic - patch.py detects proper line-endings # for inserted hunks and issues a warning if patched file has incosistent line ends |