3
from subprocess import Popen, PIPE
5
from bzrlib.errors import NoDiff3
7
Diff and patch functionality
9
__docformat__ = "restructuredtext"
11
def write_to_cmd(args, input=""):
13
process = Popen(args, bufsize=len(input), stdin=PIPE, stdout=PIPE,
14
stderr=PIPE, close_fds=True)
16
process = Popen(args, bufsize=len(input), stdin=PIPE, stdout=PIPE,
19
stdout, stderr = process.communicate(input)
20
status = process.wait()
22
raise Exception("%s killed by signal %i" (args[0], -status))
23
return stdout, stderr, status
26
def patch(patch_contents, filename, output_filename=None, reverse=False):
27
"""Apply a patch to a file, to produce another output file. This is should
28
be suitable for our limited purposes.
30
:param patch_contents: The contents of the patch to apply
31
:type patch_contents: str
32
:param filename: the name of the file to apply the patch to
34
:param output_filename: The filename to produce. If None, file is \
36
:type output_filename: str or NoneType
37
:param reverse: If true, apply the patch in reverse
39
:return: 0 on success, 1 if some hunks failed
41
args = ["patch", "-f", "-s", "--posix", "--binary"]
43
args.append("--reverse")
44
if output_filename is not None:
45
args.extend(("-o", output_filename))
47
stdout, stderr, status = write_to_cmd(args, patch_contents)
51
def diff3(out_file, mine_path, older_path, yours_path):
52
def add_label(args, label):
53
args.extend(("-L", label))
54
args = ['diff3', "-E", "--merge"]
55
add_label(args, "TREE")
56
add_label(args, "ANCESTOR")
57
add_label(args, "MERGE-SOURCE")
58
args.extend((mine_path, older_path, yours_path))
60
output, stderr, status = write_to_cmd(args)
62
if e.errno == errno.ENOENT:
66
if status not in (0, 1):
67
raise Exception(stderr)
68
file(out_file, "wb").write(output)