#!/usr/bin/env python
## @package branch_and_merge
#
# Branch or merge files.

import shutil
import git
import os
import io
from gitdb.util import hex_to_bin
from binascii import unhexlify
import shlex
import tempfile

"""
Example shas:
  205ec9a5d8d48aa36ab346e9d4e0d4ba29fe7a5f
  and
  0b3d63727ad5225c8e36909ceb3c9f3a01957caa
"""
test_dest_sha = '1ba8428cd8bfbde1d39497fe39abfe25717b85d7'
test_src_sha = 'b5b37816276147bff453b4357e79293aa8e28d1a'
test_repo = 'git@github.com:renfrowk/swchalkflow_demo.git'

def my_merge(repo, base_path, filename, dest, source):
  """Using diff_file, merge branch1 and branch2
  " repo Repository() object
  " filename The filename to overwrite
  " dest The destination SHA
  " source the source SHA
  """
  source_file = get_file(repo, source, filename)
  #dest_file = get_file(repo, dest, filename)
  if (base_path[-1] != '/'):
    base_path = basepath + '/'
  dest_file = file(base_path + filename)
  print os.path.getsize(source_file.name), "vs", os.path.getsize(dest_file.name)
  shutil.copyfile(source_file.name, dest_file.name)
  print "Copied", source_file, "to", dest_file

def get_file(orig_repo, the_sha, filename):
  copy_path = tempfile.mkdtemp(dir='/tmp/')
  new_repo = orig_repo.clone(copy_path)
  print "Created temporary repo in %s" % (copy_path)
  g = new_repo.git
  g.checkout(the_sha)
  print "Checked out", the_sha
  print "The file is ", file(copy_path + '/' + filename).name
  return file(copy_path + '/' + filename)

def my_branch(repo, branchName=None):
  """ Create a new branch.
  " If branchName isn't given, create a new branch name in the
  " format 'new_branch_{#}' where {#} is a number.
  """
  branches = repo.branches
  git = repo.git
  i = 0
  ## Choose a new branch name for convenience.
  newBranch = ''
  if (branchName == None):
    while ('new_branch_' + str(i)) in branches:
      i=i+1
    newBranch = 'new_branch_' + str(i)
  else:
    newBranch = branchName
  git.checkout('head', b=newBranch)
  repo.remote.push()

def test():
  global test_dest_sha
  global test_src_sha
  """ IMPORTANT !!!! CHANGE THIS !!!! """
  base_path = 'BASE PATH OF THE REPOSITORY'
  path = base_path + '.git'
  if git.repo.fun.is_git_dir(path):
    my_merge(git.repo.Repo(base_path), base_path, 'file1.txt', test_dest_sha, test_src_sha,)

if __name__=='__main__':
  print "Hello"
  test()