import random
import subprocess

import datasets

"""
git init
git remote add origin https://github.com/huggingface/evaluate.git
git fetch --depth 2 origin 9b056cdd5eb95459ae80142014865263e7dd75b8
# Get file after change
git checkout FETCH_HEAD -- README.md
# Get file before change
git checkout FETCH_HEAD^ -- README.md
"""

#Shell utils
def run_in_shell(cmd: str, cwd=None, timeout=10):
    # Default 10sec timeout (mostly for git fetch --depth 2 origin when the repo is private & GH asks for a username)
    completed = subprocess.run([cmd], capture_output=True, shell=True, cwd=cwd, timeout=timeout)
    return completed

def get_file_contents(commit, old_file, new_file, repo, cwd=None):

    completed = run_in_shell("git init", cwd=cwd)
    completed = run_in_shell("git remote add origin " + repo, cwd=cwd)
    completed = run_in_shell("git fetch --depth 2 origin " + commit, cwd=cwd)
    # If it times out as repo requires a username
    if completed.returncode != 0:
        return ""
    git_diff = run_in_shell(f"git diff {commit}^ {commit}", cwd=cwd).stdout.decode()
    return git_diff

def get_diff(ex):
    commit_id = ex["commit"]
    repos = list(set(ex["repos"].split(",")))
    old_file = ex["old_file"]
    new_file = ex["new_file"]
    for repo in repos:
        repo = "https://www.github.com/" + repo + ".git"
        # create a random directory to store the repo
        random_dir = random.randint(0, 1000000)
        run_in_shell("mkdir " + str(random_dir))
        try:
            git_diff = get_file_contents(commit_id, old_file, new_file, repo, cwd=str(random_dir))
        except Exception as e:
            print("ERROR", commit_id, old_file, new_file, repo, str(random_dir), e)
            run_in_shell("rm -rf " + str(random_dir))
            continue
        ex["diff"] = git_diff
        run_in_shell("rm -rf " + str(random_dir))
        return ex
    # If no repo worked
    ex["diff"] = ""
    return ex

if __name__ == "__main__":
    ds = datasets.load_dataset("bigcode/github-commits", use_auth_token=True).shuffle()

    diff_ds = ds["train"].select(range(128)).map(get_diff, num_proc=128)
    # diff_ds.push_to_hub("bigcode/commits", use_auth_token=True) # Not working
    diff_ds.to_json("gitdiffs.jsonl")