2
from subprocess import Popen, PIPE
4
Diff and patch functionality
6
__docformat__ = "restructuredtext"
8
def write_to_cmd(args, input=""):
9
process = Popen(args, bufsize=len(input), stdin=PIPE, stdout=PIPE,
10
stderr=PIPE, close_fds=True)
11
stdout, stderr = process.communicate(input)
12
status = process.wait()
14
raise Exception("%s killed by signal %i" (args[0], -status))
15
return stdout, stderr, status
18
def patch(patch_contents, filename, output_filename=None, reverse=False):
19
"""Apply a patch to a file, to produce another output file. This is should
20
be suitable for our limited purposes.
22
:param patch_contents: The contents of the patch to apply
23
:type patch_contents: str
24
:param filename: the name of the file to apply the patch to
26
:param output_filename: The filename to produce. If None, file is \
28
:type output_filename: str or NoneType
29
:param reverse: If true, apply the patch in reverse
31
:return: 0 on success, 1 if some hunks failed
33
args = ["patch", "-f", "-s", "--posix", "--binary"]
35
args.append("--reverse")
36
if output_filename is not None:
37
args.extend(("-o", output_filename))
39
stdout, stderr, status = write_to_cmd(args, patch_contents)
43
def diff3(out_file, mine_path, older_path, yours_path):
44
def add_label(args, label):
45
args.extend(("-L", label))
46
args = ['diff3', "-E", "--merge"]
47
add_label(args, "TREE")
48
add_label(args, "ANCESTOR")
49
add_label(args, "MERGE-SOURCE")
50
args.extend((mine_path, older_path, yours_path))
51
output, stderr, status = write_to_cmd(args)
52
if status not in (0, 1):
53
raise Exception(stderr)
54
file(out_file, "wb").write(output)