1
# Copyright (C) 2005, 2006 Canonical Ltd
2
# Copyright (C) 2005, 2008 Aaron Bentley, 2006 Michael Ellerman
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
from __future__ import absolute_import
20
"""Diff and patch functionality"""
24
2
from subprocess import Popen, PIPE
28
from .errors import NoDiff3, BzrError
29
from .textfile import check_text_path
31
class PatchFailed(BzrError):
33
_fmt = """Patch application failed"""
36
class PatchInvokeError(BzrError):
38
_fmt = """Error invoking patch: %(errstr)s%(stderr)s"""
39
internal_error = False
41
def __init__(self, e, stderr=''):
43
self.errstr = os.strerror(e.errno)
44
self.stderr = '\n' + stderr
4
Diff and patch functionality
6
__docformat__ = "restructuredtext"
52
8
def write_to_cmd(args, input=""):
53
"""Spawn a process, and wait for the result
55
If the process is killed, an exception is raised
57
:param args: The command line, the first entry should be the program name
58
:param input: [optional] The text to send the process on stdin
59
:return: (stdout, stderr, status)
61
process = Popen(args, bufsize=len(input), stdin=PIPE, stdout=PIPE,
62
stderr=PIPE, close_fds=_do_close_fds)
10
process = Popen(args, bufsize=len(input), stdin=PIPE, stdout=PIPE,
11
stderr=PIPE, close_fds=True)
13
process = Popen(args, bufsize=len(input), stdin=PIPE, stdout=PIPE,
63
16
stdout, stderr = process.communicate(input)
64
17
status = process.wait()
66
raise Exception("%s killed by signal %i" % (args[0], -status))
19
raise Exception("%s killed by signal %i" (args[0], -status))
67
20
return stdout, stderr, status
70
23
def patch(patch_contents, filename, output_filename=None, reverse=False):
71
24
"""Apply a patch to a file, to produce another output file. This is should
89
42
args.extend(("-o", output_filename))
90
43
args.append(filename)
91
44
stdout, stderr, status = write_to_cmd(args, patch_contents)
95
48
def diff3(out_file, mine_path, older_path, yours_path):
96
49
def add_label(args, label):
97
50
args.extend(("-L", label))
98
check_text_path(mine_path)
99
check_text_path(older_path)
100
check_text_path(yours_path)
101
51
args = ['diff3', "-E", "--merge"]
102
52
add_label(args, "TREE")
103
53
add_label(args, "ANCESTOR")
104
54
add_label(args, "MERGE-SOURCE")
105
55
args.extend((mine_path, older_path, yours_path))
107
output, stderr, status = write_to_cmd(args)
109
if e.errno == errno.ENOENT:
56
output, stderr, status = write_to_cmd(args)
113
57
if status not in (0, 1):
114
58
raise Exception(stderr)
115
with open(out_file, 'wb') as f:
59
file(out_file, "wb").write(output)
120
def patch_tree(tree, patches, strip=0, reverse=False, dry_run=False,
121
quiet=False, out=None):
122
"""Apply a patch to a tree.
125
tree: A MutableTree object
126
patches: list of patches as bytes
127
strip: Strip X segments of paths
128
reverse: Apply reversal of patch
131
return run_patch(tree.basedir, patches, strip, reverse, dry_run,
135
def run_patch(directory, patches, strip=0, reverse=False, dry_run=False,
136
quiet=False, _patch_cmd='patch', target_file=None, out=None):
137
args = [_patch_cmd, '-d', directory, '-s', '-p%d' % strip, '-f']
139
args.append('--quiet')
141
if sys.platform == "win32":
142
args.append('--binary')
147
if sys.platform.startswith('freebsd'):
148
args.append('--check')
150
args.append('--dry-run')
154
if target_file is not None:
155
args.append(target_file)
158
process = Popen(args, stdin=PIPE, stdout=PIPE, stderr=stderr)
160
raise PatchInvokeError(e)
162
for patch in patches:
163
process.stdin.write(bytes(patch))
164
process.stdin.close()
167
raise PatchInvokeError(e, process.stderr.read())
169
result = process.wait()
172
out.write(process.stdout.read())
174
process.stdout.read()
181
def iter_patched_from_hunks(orig_lines, hunks):
182
"""Iterate through a series of lines with a patch applied.
183
This handles a single file, and does exact, not fuzzy patching.
185
:param orig_lines: The unpatched lines.
186
:param hunks: An iterable of Hunk instances.
188
This is different from breezy.patches in that it invokes the patch
191
with tempfile.NamedTemporaryFile() as f:
192
f.writelines(orig_lines)
194
# TODO(jelmer): Stream patch contents to command, rather than
195
# serializing the entire patch upfront.
196
serialized = b''.join([hunk.as_bytes() for hunk in hunks])
197
args = ["patch", "-f", "-s", "--posix", "--binary",
198
"-o", "-", f.name, "-r", "-"]
199
stdout, stderr, status = write_to_cmd(args, serialized)
202
raise PatchFailed(stderr)