index.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # index.py -- File parser/write for the git index file
  2. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  3. # This program is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU General Public License
  5. # as published by the Free Software Foundation; version 2
  6. # of the License or (at your opinion) any later version of the license.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. # MA 02110-1301, USA.
  17. """Parser for the git index file format."""
  18. import os
  19. import stat
  20. import struct
  21. from dulwich.objects import (
  22. Tree,
  23. hex_to_sha,
  24. sha_to_hex,
  25. )
  26. from dulwich.pack import (
  27. SHA1Reader,
  28. SHA1Writer,
  29. )
  30. def read_cache_time(f):
  31. """Read a cache time."""
  32. return struct.unpack(">LL", f.read(8))
  33. def write_cache_time(f, t):
  34. """Write a cache time."""
  35. if isinstance(t, int):
  36. t = (t, 0)
  37. elif isinstance(t, float):
  38. (secs, nsecs) = divmod(t, 1.0)
  39. t = (int(secs), int(nsecs * 1000000000))
  40. elif not isinstance(t, tuple):
  41. raise TypeError(t)
  42. f.write(struct.pack(">LL", *t))
  43. def read_cache_entry(f):
  44. """Read an entry from a cache file.
  45. :param f: File-like object to read from
  46. :return: tuple with: device, inode, mode, uid, gid, size, sha, flags
  47. """
  48. beginoffset = f.tell()
  49. ctime = read_cache_time(f)
  50. mtime = read_cache_time(f)
  51. (dev, ino, mode, uid, gid, size, sha, flags, ) = \
  52. struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2))
  53. name = f.read((flags & 0x0fff))
  54. # Padding:
  55. real_size = ((f.tell() - beginoffset + 8) & ~7)
  56. data = f.read((beginoffset + real_size) - f.tell())
  57. return (name, ctime, mtime, dev, ino, mode, uid, gid, size,
  58. sha_to_hex(sha), flags & ~0x0fff)
  59. def write_cache_entry(f, entry):
  60. """Write an index entry to a file.
  61. :param f: File object
  62. :param entry: Entry to write, tuple with:
  63. (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags)
  64. """
  65. beginoffset = f.tell()
  66. (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = entry
  67. write_cache_time(f, ctime)
  68. write_cache_time(f, mtime)
  69. flags = len(name) | flags
  70. f.write(struct.pack(">LLLLLL20sH", dev, ino, mode, uid, gid, size, hex_to_sha(sha), flags))
  71. f.write(name)
  72. real_size = ((f.tell() - beginoffset + 8) & ~7)
  73. f.write("\0" * ((beginoffset + real_size) - f.tell()))
  74. def read_index(f):
  75. """Read an index file, yielding the individual entries."""
  76. header = f.read(4)
  77. if header != "DIRC":
  78. raise AssertionError("Invalid index file header: %r" % header)
  79. (version, num_entries) = struct.unpack(">LL", f.read(4 * 2))
  80. assert version in (1, 2)
  81. for i in range(num_entries):
  82. yield read_cache_entry(f)
  83. def read_index_dict(f):
  84. """Read an index file and return it as a dictionary.
  85. :param f: File object to read from
  86. """
  87. ret = {}
  88. for x in read_index(f):
  89. ret[x[0]] = tuple(x[1:])
  90. return ret
  91. def write_index(f, entries):
  92. """Write an index file.
  93. :param f: File-like object to write to
  94. :param entries: Iterable over the entries to write
  95. """
  96. f.write("DIRC")
  97. f.write(struct.pack(">LL", 2, len(entries)))
  98. for x in entries:
  99. write_cache_entry(f, x)
  100. def write_index_dict(f, entries):
  101. """Write an index file based on the contents of a dictionary.
  102. """
  103. entries_list = []
  104. for name in sorted(entries):
  105. entries_list.append((name,) + tuple(entries[name]))
  106. write_index(f, entries_list)
  107. def cleanup_mode(mode):
  108. if stat.S_ISLNK(fsmode):
  109. mode = stat.S_IFLNK
  110. else:
  111. mode = stat.S_IFREG
  112. mode |= (fsmode & 0111)
  113. return mode
  114. class Index(object):
  115. """A Git Index file."""
  116. def __init__(self, filename):
  117. """Open an index file.
  118. :param filename: Path to the index file
  119. """
  120. self._filename = filename
  121. self.clear()
  122. self.read()
  123. def write(self):
  124. """Write current contents of index to disk."""
  125. f = open(self._filename, 'wb')
  126. try:
  127. f = SHA1Writer(f)
  128. write_index_dict(f, self._byname)
  129. finally:
  130. f.close()
  131. def read(self):
  132. """Read current contents of index from disk."""
  133. f = open(self._filename, 'rb')
  134. try:
  135. f = SHA1Reader(f)
  136. for x in read_index(f):
  137. self[x[0]] = tuple(x[1:])
  138. f.check_sha()
  139. finally:
  140. f.close()
  141. def __len__(self):
  142. """Number of entries in this index file."""
  143. return len(self._byname)
  144. def __getitem__(self, name):
  145. """Retrieve entry by relative path."""
  146. return self._byname[name]
  147. def __iter__(self):
  148. """Iterate over the paths in this index."""
  149. return iter(self._byname)
  150. def get_sha1(self, path):
  151. """Return the (git object) SHA1 for the object at a path."""
  152. return self[path][-2]
  153. def iterblobs(self):
  154. """Iterate over path, sha, mode tuples for use with commit_tree."""
  155. for path, entry in self:
  156. yield path, entry[-2], cleanup_mode(entry[-6])
  157. def clear(self):
  158. """Remove all contents from this index."""
  159. self._byname = {}
  160. def __setitem__(self, name, x):
  161. assert isinstance(name, str)
  162. assert len(x) == 10
  163. # Remove the old entry if any
  164. self._byname[name] = x
  165. def iteritems(self):
  166. return self._byname.iteritems()
  167. def update(self, entries):
  168. for name, value in entries.iteritems():
  169. self[name] = value
  170. def commit_tree(object_store, blobs):
  171. """Commit a new tree.
  172. :param object_store: Object store to add trees to
  173. :param blobs: Iterable over blob path, sha, mode entries
  174. :return: SHA1 of the created tree.
  175. """
  176. trees = {"": {}}
  177. def add_tree(path):
  178. if path in trees:
  179. return trees[path]
  180. dirname, basename = os.path.split(path)
  181. t = add_tree(dirname)
  182. assert isinstance(basename, str)
  183. newtree = {}
  184. t[basename] = newtree
  185. trees[path] = newtree
  186. return newtree
  187. for path, sha, mode in blobs:
  188. tree_path, basename = os.path.split(path)
  189. tree = add_tree(tree_path)
  190. tree[basename] = (mode, sha)
  191. def build_tree(path):
  192. tree = Tree()
  193. for basename, entry in trees[path].iteritems():
  194. if type(entry) == dict:
  195. mode = stat.S_IFDIR
  196. sha = build_tree(os.path.join(path, basename))
  197. else:
  198. (mode, sha) = entry
  199. tree.add(mode, basename, sha)
  200. object_store.add_object(tree)
  201. return tree.id
  202. return build_tree("")
  203. def commit_index(object_store, index):
  204. return commit_tree(object_store, index.blobs())