index.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. S_IFGITLINK,
  23. S_ISGITLINK,
  24. Tree,
  25. hex_to_sha,
  26. sha_to_hex,
  27. )
  28. from dulwich.pack import (
  29. SHA1Reader,
  30. SHA1Writer,
  31. )
  32. def read_cache_time(f):
  33. """Read a cache time.
  34. :param f: File-like object to read from
  35. :return: Tuple with seconds and nanoseconds
  36. """
  37. return struct.unpack(">LL", f.read(8))
  38. def write_cache_time(f, t):
  39. """Write a cache time.
  40. :param f: File-like object to write to
  41. :param t: Time to write (as int, float or tuple with secs and nsecs)
  42. """
  43. if isinstance(t, int):
  44. t = (t, 0)
  45. elif isinstance(t, float):
  46. (secs, nsecs) = divmod(t, 1.0)
  47. t = (int(secs), int(nsecs * 1000000000))
  48. elif not isinstance(t, tuple):
  49. raise TypeError(t)
  50. f.write(struct.pack(">LL", *t))
  51. def read_cache_entry(f):
  52. """Read an entry from a cache file.
  53. :param f: File-like object to read from
  54. :return: tuple with: device, inode, mode, uid, gid, size, sha, flags
  55. """
  56. beginoffset = f.tell()
  57. ctime = read_cache_time(f)
  58. mtime = read_cache_time(f)
  59. (dev, ino, mode, uid, gid, size, sha, flags, ) = \
  60. struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2))
  61. name = f.read((flags & 0x0fff))
  62. # Padding:
  63. real_size = ((f.tell() - beginoffset + 8) & ~7)
  64. data = f.read((beginoffset + real_size) - f.tell())
  65. return (name, ctime, mtime, dev, ino, mode, uid, gid, size,
  66. sha_to_hex(sha), flags & ~0x0fff)
  67. def write_cache_entry(f, entry):
  68. """Write an index entry to a file.
  69. :param f: File object
  70. :param entry: Entry to write, tuple with:
  71. (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags)
  72. """
  73. beginoffset = f.tell()
  74. (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = entry
  75. write_cache_time(f, ctime)
  76. write_cache_time(f, mtime)
  77. flags = len(name) | (flags &~ 0x0fff)
  78. f.write(struct.pack(">LLLLLL20sH", dev, ino, mode, uid, gid, size, hex_to_sha(sha), flags))
  79. f.write(name)
  80. real_size = ((f.tell() - beginoffset + 8) & ~7)
  81. f.write("\0" * ((beginoffset + real_size) - f.tell()))
  82. def read_index(f):
  83. """Read an index file, yielding the individual entries."""
  84. header = f.read(4)
  85. if header != "DIRC":
  86. raise AssertionError("Invalid index file header: %r" % header)
  87. (version, num_entries) = struct.unpack(">LL", f.read(4 * 2))
  88. assert version in (1, 2)
  89. for i in range(num_entries):
  90. yield read_cache_entry(f)
  91. def read_index_dict(f):
  92. """Read an index file and return it as a dictionary.
  93. :param f: File object to read from
  94. """
  95. ret = {}
  96. for x in read_index(f):
  97. ret[x[0]] = tuple(x[1:])
  98. return ret
  99. def write_index(f, entries):
  100. """Write an index file.
  101. :param f: File-like object to write to
  102. :param entries: Iterable over the entries to write
  103. """
  104. f.write("DIRC")
  105. f.write(struct.pack(">LL", 2, len(entries)))
  106. for x in entries:
  107. write_cache_entry(f, x)
  108. def write_index_dict(f, entries):
  109. """Write an index file based on the contents of a dictionary.
  110. """
  111. entries_list = []
  112. for name in sorted(entries):
  113. entries_list.append((name,) + tuple(entries[name]))
  114. write_index(f, entries_list)
  115. def cleanup_mode(mode):
  116. """Cleanup a mode value.
  117. This will return a mode that can be stored in a tree object.
  118. :param mode: Mode to clean up.
  119. """
  120. if stat.S_ISLNK(mode):
  121. return stat.S_IFLNK
  122. elif stat.S_ISDIR(mode):
  123. return stat.S_IFDIR
  124. elif S_ISGITLINK(mode):
  125. return S_IFGITLINK
  126. ret = stat.S_IFREG | 0644
  127. ret |= (mode & 0111)
  128. return ret
  129. class Index(object):
  130. """A Git Index file."""
  131. def __init__(self, filename):
  132. """Open an index file.
  133. :param filename: Path to the index file
  134. """
  135. self._filename = filename
  136. self.clear()
  137. self.read()
  138. def write(self):
  139. """Write current contents of index to disk."""
  140. f = open(self._filename, 'wb')
  141. try:
  142. f = SHA1Writer(f)
  143. write_index_dict(f, self._byname)
  144. finally:
  145. f.close()
  146. def read(self):
  147. """Read current contents of index from disk."""
  148. f = open(self._filename, 'rb')
  149. try:
  150. f = SHA1Reader(f)
  151. for x in read_index(f):
  152. self[x[0]] = tuple(x[1:])
  153. # FIXME: Additional data?
  154. f.read(os.path.getsize(self._filename)-f.tell()-20)
  155. f.check_sha()
  156. finally:
  157. f.close()
  158. def __len__(self):
  159. """Number of entries in this index file."""
  160. return len(self._byname)
  161. def __getitem__(self, name):
  162. """Retrieve entry by relative path.
  163. :return: tuple with (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags)
  164. """
  165. return self._byname[name]
  166. def __iter__(self):
  167. """Iterate over the paths in this index."""
  168. return iter(self._byname)
  169. def get_sha1(self, path):
  170. """Return the (git object) SHA1 for the object at a path."""
  171. return self[path][-2]
  172. def get_mode(self, path):
  173. """Return the POSIX file mode for the object at a path."""
  174. return self[path][-6]
  175. def iterblobs(self):
  176. """Iterate over path, sha, mode tuples for use with commit_tree."""
  177. for path in self:
  178. entry = self[path]
  179. yield path, entry[-2], cleanup_mode(entry[-6])
  180. def clear(self):
  181. """Remove all contents from this index."""
  182. self._byname = {}
  183. def __setitem__(self, name, x):
  184. assert isinstance(name, str)
  185. assert len(x) == 10
  186. # Remove the old entry if any
  187. self._byname[name] = x
  188. def iteritems(self):
  189. return self._byname.iteritems()
  190. def update(self, entries):
  191. for name, value in entries.iteritems():
  192. self[name] = value
  193. def changes_from_tree(self, object_store, tree, want_unchanged=False):
  194. """Find the differences between the contents of this index and a tree.
  195. :param object_store: Object store to use for retrieving tree contents
  196. :param tree: SHA1 of the root tree
  197. :param want_unchanged: Whether unchanged files should be reported
  198. :return: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  199. """
  200. mine = set(self._byname.keys())
  201. for (name, mode, sha) in object_store.iter_tree_contents(tree):
  202. if name in mine:
  203. if (want_unchanged or self.get_sha1(name) != sha or
  204. self.get_mode(name) != mode):
  205. yield ((name, name), (mode, self.get_mode(name)), (sha, self.get_sha1(name)))
  206. mine.remove(name)
  207. else:
  208. # Was removed
  209. yield ((name, None), (mode, None), (sha, None))
  210. # Mention added files
  211. for name in mine:
  212. yield ((None, name), (None, self.get_mode(name)), (None, self.get_sha1(name)))
  213. def commit_tree(object_store, blobs):
  214. """Commit a new tree.
  215. :param object_store: Object store to add trees to
  216. :param blobs: Iterable over blob path, sha, mode entries
  217. :return: SHA1 of the created tree.
  218. """
  219. trees = {"": {}}
  220. def add_tree(path):
  221. if path in trees:
  222. return trees[path]
  223. dirname, basename = os.path.split(path)
  224. t = add_tree(dirname)
  225. assert isinstance(basename, str)
  226. newtree = {}
  227. t[basename] = newtree
  228. trees[path] = newtree
  229. return newtree
  230. for path, sha, mode in blobs:
  231. tree_path, basename = os.path.split(path)
  232. tree = add_tree(tree_path)
  233. tree[basename] = (mode, sha)
  234. def build_tree(path):
  235. tree = Tree()
  236. for basename, entry in trees[path].iteritems():
  237. if type(entry) == dict:
  238. mode = stat.S_IFDIR
  239. sha = build_tree(os.path.join(path, basename))
  240. else:
  241. (mode, sha) = entry
  242. tree.add(mode, basename, sha)
  243. object_store.add_object(tree)
  244. return tree.id
  245. return build_tree("")
  246. def commit_index(object_store, index):
  247. """Create a new tree from an index.
  248. :param object_store: Object store to save the tree in
  249. :param index: Index file
  250. """
  251. return commit_tree(object_store, index.iterblobs())