repository.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # repository.py -- For dealing wih git repositories.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. import os
  19. from objects import ShaFile
  20. objectdir = 'objects'
  21. symref = 'ref: '
  22. class Repository(object):
  23. ref_locs = ['', 'refs', 'refs/tags', 'refs/heads', 'refs/remotes']
  24. def __init__(self, root):
  25. self._basedir = root
  26. def basedir(self):
  27. return self._basedir
  28. def object_dir(self):
  29. return os.path.join(self.basedir(), objectdir)
  30. def _get_ref(self, file):
  31. f = open(file, 'rb')
  32. try:
  33. contents = f.read()
  34. if contents.startswith(symref):
  35. ref = contents[len(symref):]
  36. if ref[-1] == '\n':
  37. ref = ref[:-1]
  38. return self.ref(ref)
  39. assert len(contents) == 41, 'Invalid ref'
  40. return contents[:-1]
  41. finally:
  42. f.close()
  43. def ref(self, name):
  44. for dir in self.ref_locs:
  45. file = os.path.join(self.basedir(), dir, name)
  46. if os.path.exists(file):
  47. return self._get_ref(file)
  48. def head(self):
  49. return self.ref('HEAD')
  50. def get_object(self, sha):
  51. assert len(sha) == 40, "Incorrect sha length"
  52. dir = sha[:2]
  53. file = sha[2:]
  54. path = os.path.join(self.object_dir(), dir, file)
  55. if not os.path.exists(path):
  56. return None
  57. return ShaFile.from_file(path)