#!/usr/bin/env python3

import subprocess
import sys

def run_cmd(cmd, **kwargs):
    p = subprocess.Popen(cmd, stderr=sys.stderr, stdout=subprocess.PIPE, **kwargs)
    stdout, _ = p.communicate()
    return stdout

repo1 = sys.argv[1]
repo2 = sys.argv[2]
branch1 = sys.argv[3]
branch2 = sys.argv[4]

commits1 = run_cmd(['git', 'rev-list', branch1], cwd=repo1).decode().split()[::-1]
commits2 = run_cmd(['git', 'rev-list', branch2], cwd=repo2).decode().split()[::-1]

print('{} commits in {}'.format(len(commits1), repo1))
print('{} commits in {}'.format(len(commits2), repo2))

sharedlen = min(len(commits1), len(commits2))
matchC1 = 0
matchC2 = 0
nMatching = 0
for i in range(sharedlen):
    if commits1[matchC1] == commits2[matchC2]:
        matchC1 += 1
        matchC2 += 1
        nMatching += 1
    else:
        try:
            c2idx = next((n + matchC2 for n, c in enumerate(commits2[matchC2:]) if c == commits1[matchC1]))
        except StopIteration:
            break
        # Found this commit some commits above it
        matchC2 = c2idx + 1
        matchC1 += 1
        nMatching += 1

if nMatching != sharedlen:
    print('{} commits are missing from {}'.format(matchC2 - matchC1, repo1))
    print('Commit #{}/{} differs ({}/{})'.format(matchC1, matchC2, commits1[matchC1], commits2[matchC2]))
else:
    print('All {} commits of {} are present in {}!'.format(len(commits1), repo1, repo2))

