repository.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. Commit,
  21. Tree,
  22. Blob,
  23. )
  24. objectdir = 'objects'
  25. symref = 'ref: '
  26. class Repository(object):
  27. ref_locs = ['', 'refs', 'refs/tags', 'refs/heads', 'refs/remotes']
  28. def __init__(self, root):
  29. self._basedir = root
  30. def basedir(self):
  31. return self._basedir
  32. def object_dir(self):
  33. return os.path.join(self.basedir(), objectdir)
  34. def _get_ref(self, file):
  35. f = open(file, 'rb')
  36. try:
  37. contents = f.read()
  38. if contents.startswith(symref):
  39. ref = contents[len(symref):]
  40. if ref[-1] == '\n':
  41. ref = ref[:-1]
  42. return self.ref(ref)
  43. assert len(contents) == 41, 'Invalid ref'
  44. return contents[:-1]
  45. finally:
  46. f.close()
  47. def ref(self, name):
  48. for dir in self.ref_locs:
  49. file = os.path.join(self.basedir(), dir, name)
  50. if os.path.exists(file):
  51. return self._get_ref(file)
  52. def head(self):
  53. return self.ref('HEAD')
  54. def _get_object(self, sha, cls):
  55. assert len(sha) == 40, "Incorrect length sha: %s" % str(sha)
  56. dir = sha[:2]
  57. file = sha[2:]
  58. path = os.path.join(self.object_dir(), dir, file)
  59. if not os.path.exists(path):
  60. return None
  61. return cls.from_file(path)
  62. def get_object(self, sha):
  63. return self._get_object(sha, ShaFile)
  64. def get_commit(self, sha):
  65. return self._get_object(sha, Commit)
  66. def get_tree(self, sha):
  67. return self._get_object(sha, Tree)
  68. def get_blob(self, sha):
  69. return self._get_object(sha, Blob)