git.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import tempfile
  2. import logging
  3. from dulwich import index
  4. from dulwich.client import get_transport_and_path
  5. from dulwich.repo import Repo
  6. logger = logging.getLogger(__name__)
  7. def clone_branch(repo_url, branch="master", folder=None):
  8. return clone(repo_url, 'refs/heads/' + branch, folder)
  9. def clone_tag(repo_url, tag, folder=None):
  10. return clone(repo_url, 'refs/tags/' + tag, folder)
  11. def checkout(rep, ref=None):
  12. is_commit = False
  13. if ref is None:
  14. ref = 'refs/heads/master'
  15. elif not ref.startswith('refs/'):
  16. is_commit = True
  17. elif ref.startswith('refs/tags'):
  18. ref = rep.ref(ref)
  19. is_commit = True
  20. if is_commit:
  21. rep['HEAD'] = rep.commit(ref)
  22. else:
  23. rep['HEAD'] = rep.refs[ref]
  24. indexfile = rep.index_path()
  25. tree = rep["HEAD"].tree
  26. index.build_index_from_tree(rep.path, indexfile, rep.object_store, tree)
  27. return rep.path
  28. def pull(origin, rep, ref=None):
  29. clone(origin, ref, None, rep)
  30. return rep, rep.path
  31. def clone(repo_url, ref=None, folder=None, rep=None):
  32. is_commit = False
  33. if ref is None:
  34. ref = 'refs/heads/master'
  35. elif not ref.startswith('refs/'):
  36. is_commit = True
  37. logger.debug("clone repo_url={0}, ref={1}".format(repo_url, ref))
  38. if not rep:
  39. if folder is None:
  40. folder = tempfile.mkdtemp()
  41. logger.debug("folder = {0}".format(folder))
  42. rep = Repo.init(folder)
  43. client, relative_path = get_transport_and_path(repo_url)
  44. logger.debug("client={0}".format(client))
  45. remote_refs = client.fetch(relative_path, rep)
  46. for k, v in remote_refs.iteritems():
  47. try:
  48. rep.refs.add_if_new(k, v)
  49. except:
  50. pass
  51. if ref.startswith('refs/tags'):
  52. ref = rep.ref(ref)
  53. is_commit = True
  54. if is_commit:
  55. rep['HEAD'] = rep.commit(ref)
  56. else:
  57. rep['HEAD'] = remote_refs[ref]
  58. indexfile = rep.index_path()
  59. tree = rep["HEAD"].tree
  60. index.build_index_from_tree(rep.path, indexfile, rep.object_store, tree)
  61. logger.debug("done")
  62. return rep, folder