git.py 2.0 KB

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