~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to patch.py

  • Committer: Aaron Bentley
  • Date: 2008-02-13 04:15:48 UTC
  • Revision ID: aaron@aaronbentley.com-20080213041548-r35d4icm9kblej3u
Unify patch invocation

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
#    along with this program; if not, write to the Free Software
16
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
17
import sys
18
 
from subprocess import Popen, PIPE
 
18
import subprocess
19
19
 
20
20
from bzrlib.workingtree import WorkingTree
21
21
import bzrlib.add
22
22
 
23
23
from bzrlib.plugins.bzrtools.bzrtools import open_from_url
 
24
from errors import CommandError, PatchFailed, PatchInvokeError
24
25
 
25
26
def patch(tree, location, strip, quiet=False):
26
27
    """Apply a patch to a branch, using patch(1).  URLs may be used."""
29
30
        my_file = sys.stdin
30
31
    else:
31
32
        my_file = open_from_url(location)
32
 
    cmd = ['patch', '--directory', tree.basedir, '--strip', str(strip)]
 
33
    patches = [my_file.read()]
 
34
    return run_patch(tree.basedir, patches, strip, quiet=quiet)
 
35
 
 
36
 
 
37
def run_patch(directory, patches, strip=0, reverse=False, dry_run=False,
 
38
              quiet=False):
 
39
    args = ['patch', '-d', directory, '-s', '-p%d' % strip, '-f']
33
40
    if quiet:
34
 
        cmd.append('--quiet')
35
 
    r = 0
36
 
    child_proc = Popen(cmd, stdin=PIPE)
37
 
    for line in my_file:
38
 
        child_proc.stdin.write(line)
39
 
    child_proc.stdin.close()
40
 
    r = child_proc.wait()
41
 
    return r
 
41
        args.append('--quiet')
 
42
 
 
43
    if sys.platform == "win32":
 
44
        args.append('--binary')
 
45
 
 
46
    if reverse:
 
47
        args.append('-R')
 
48
    if dry_run:
 
49
        if sys.platform.startswith('freebsd'):
 
50
            args.append('--check')
 
51
        else:
 
52
            args.append('--dry-run')
 
53
        stderr = subprocess.PIPE
 
54
    else:
 
55
        stderr = None
 
56
 
 
57
    try:
 
58
        process = subprocess.Popen(args, stdin=subprocess.PIPE,
 
59
                                   stdout=subprocess.PIPE, stderr=stderr)
 
60
        for patch in patches:
 
61
            process.stdin.write(str(patch))
 
62
        process.stdin.close()
 
63
 
 
64
    except IOError, e:
 
65
        raise PatchInvokeError(e, process.stderr.read())
 
66
 
 
67
    result = process.wait()
 
68
    if not dry_run:
 
69
        sys.stdout.write(process.stdout.read())
 
70
    if result != 0:
 
71
        raise PatchFailed()
 
72
 
 
73
    return result