Doruk
Doruk

Reputation: 203

Python how to diff3 using difflib

I am building a git system as a learning project . I want to do the same operation (which is diff3) as the following code but since I am on windows I cannot call sub process diff3.

def merge_blobs (o_base, o_HEAD, o_other):
    with Temp () as f_base, Temp () as f_HEAD, Temp () as f_other:

        # Write blobs to files
        for oid, f in ((o_base, f_base), (o_HEAD, f_HEAD), (o_other, f_other)):
            if oid:
                f.write (data.get_object (oid))
                f.flush ()

        with subprocess.Popen (
            ['diff3', '-m',
             '-L', 'HEAD', f_HEAD.name,
             '-L', 'BASE', f_base.name,
             '-L', 'MERGE_HEAD', f_other.name,
            ], stdout=subprocess.PIPE) as proc:
            output, _ = proc.communicate ()
            assert proc.returncode in (0, 1)

        return output

Until now I have used difflib.unified_diff() for diffing two files but I cant figure out how to do diff3.

For context this is the code I have used so far to merge to files

def merge_blobs(o_HEAD, o_other):
   data_HEAD = data.get_object(o_HEAD) if o_HEAD else b""
   data_other = data.get_object(o_other) if o_other else b""

   # Decode bytes to strings
   data_HEAD_str = data_HEAD.decode("utf-8")
   data_other_str = data_other.decode("utf-8")

   # Compute the unified diff
   diff_ite = difflib.unified_diff(data_HEAD_str.splitlines(), data_other_str.splitlines())
    
   # Skip over the header in the diff
   for i,c in enumerate(diff_ite):
      if i == 2:
         break
   diff = [i.removeprefix("-").removeprefix("+").removeprefix(" ") for i in diff_ite]
   return "\n".join(diff).encode("utf-8")

Upvotes: 2

Views: 111

Answers (0)

Related Questions