|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright 2010 Max Battcher <me@worldmaker.net>. Licensed under the MS-PL. |
| 3 | +from diff_match_patch import diff_match_patch |
| 4 | +import argparse |
| 5 | +import sys |
| 6 | + |
| 7 | +""" |
| 8 | +This is a simple patch utility based upon diff-match-patch. |
| 9 | +""" |
| 10 | + |
| 11 | +if __name__ == "__main__": |
| 12 | + parser = argparse.ArgumentParser( |
| 13 | + description="Applies patches created by diff-match-patch and/or tokdiff.") |
| 14 | + parser.add_argument('input', type=argparse.FileType('r')) |
| 15 | + parser.add_argument('-p', '--patch', type=argparse.FileType('r'), |
| 16 | + default=sys.stdin) |
| 17 | + parser.add_argument('-o', '--out', type=argparse.FileType('w'), |
| 18 | + default=sys.stdout) |
| 19 | + group = parser.add_mutually_exclusive_group() |
| 20 | + group.add_argument('-u', '--unidiff', action='store_true', |
| 21 | + help='Char-based unidiff-like patch (default)') |
| 22 | + group.add_argument('-d', '--delta', action='store_true', |
| 23 | + help='Simplified intermediate delta (unstable)') |
| 24 | + data = parser.parse_args() |
| 25 | + |
| 26 | + dmp = diff_match_patch() |
| 27 | + |
| 28 | + data.unidiff = not data.delta |
| 29 | + |
| 30 | + if data.unidiff: |
| 31 | + patches = dmp.patch_fromText(data.patch.read()) |
| 32 | + result, successes = dmp.patch_apply(patches, data.input.read()) |
| 33 | + data.out.write(result) |
| 34 | + if not all(successes): |
| 35 | + sys.stderr.write('WARNING: One or more patches were not applied.') |
| 36 | + elif data.delta: |
| 37 | + inp = data.input.read() |
| 38 | + diffs = dmp.diff_fromDelta(inp, data.patch.read()) |
| 39 | + patches = dmp.patch_make(diffs) |
| 40 | + result, successes = dmp.patch_apply(patches, inp) |
| 41 | + data.out.write(result) |
| 42 | + if not all(successes): |
| 43 | + sys.stderr.write('WARNING: One or more patches were not applied.') |
| 44 | + |
| 45 | +# vim: ai et ts=4 sts=4 sw=4 |
0 commit comments