index.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. # index.py -- File parser/writer for the git index file
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Parser for the git index file format."""
  21. import collections
  22. import errno
  23. import os
  24. import stat
  25. import struct
  26. import sys
  27. from dulwich.file import GitFile
  28. from dulwich.objects import (
  29. Blob,
  30. S_IFGITLINK,
  31. S_ISGITLINK,
  32. Tree,
  33. hex_to_sha,
  34. sha_to_hex,
  35. )
  36. from dulwich.pack import (
  37. SHA1Reader,
  38. SHA1Writer,
  39. )
  40. IndexEntry = collections.namedtuple(
  41. 'IndexEntry', [
  42. 'ctime', 'mtime', 'dev', 'ino', 'mode', 'uid', 'gid', 'size', 'sha',
  43. 'flags'])
  44. FLAG_STAGEMASK = 0x3000
  45. FLAG_VALID = 0x8000
  46. FLAG_EXTENDED = 0x4000
  47. def pathsplit(path):
  48. """Split a /-delimited path into a directory part and a basename.
  49. :param path: The path to split.
  50. :return: Tuple with directory name and basename
  51. """
  52. try:
  53. (dirname, basename) = path.rsplit(b"/", 1)
  54. except ValueError:
  55. return (b"", path)
  56. else:
  57. return (dirname, basename)
  58. def pathjoin(*args):
  59. """Join a /-delimited path.
  60. """
  61. return b"/".join([p for p in args if p])
  62. def read_cache_time(f):
  63. """Read a cache time.
  64. :param f: File-like object to read from
  65. :return: Tuple with seconds and nanoseconds
  66. """
  67. return struct.unpack(">LL", f.read(8))
  68. def write_cache_time(f, t):
  69. """Write a cache time.
  70. :param f: File-like object to write to
  71. :param t: Time to write (as int, float or tuple with secs and nsecs)
  72. """
  73. if isinstance(t, int):
  74. t = (t, 0)
  75. elif isinstance(t, float):
  76. (secs, nsecs) = divmod(t, 1.0)
  77. t = (int(secs), int(nsecs * 1000000000))
  78. elif not isinstance(t, tuple):
  79. raise TypeError(t)
  80. f.write(struct.pack(">LL", *t))
  81. def read_cache_entry(f):
  82. """Read an entry from a cache file.
  83. :param f: File-like object to read from
  84. :return: tuple with: device, inode, mode, uid, gid, size, sha, flags
  85. """
  86. beginoffset = f.tell()
  87. ctime = read_cache_time(f)
  88. mtime = read_cache_time(f)
  89. (dev, ino, mode, uid, gid, size, sha, flags, ) = \
  90. struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2))
  91. name = f.read((flags & 0x0fff))
  92. # Padding:
  93. real_size = ((f.tell() - beginoffset + 8) & ~7)
  94. f.read((beginoffset + real_size) - f.tell())
  95. return (name, ctime, mtime, dev, ino, mode, uid, gid, size,
  96. sha_to_hex(sha), flags & ~0x0fff)
  97. def write_cache_entry(f, entry):
  98. """Write an index entry to a file.
  99. :param f: File object
  100. :param entry: Entry to write, tuple with:
  101. (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags)
  102. """
  103. beginoffset = f.tell()
  104. (name, ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = entry
  105. write_cache_time(f, ctime)
  106. write_cache_time(f, mtime)
  107. flags = len(name) | (flags & ~0x0fff)
  108. f.write(struct.pack(
  109. b'>LLLLLL20sH', dev & 0xFFFFFFFF, ino & 0xFFFFFFFF,
  110. mode, uid, gid, size, hex_to_sha(sha), flags))
  111. f.write(name)
  112. real_size = ((f.tell() - beginoffset + 8) & ~7)
  113. f.write(b'\0' * ((beginoffset + real_size) - f.tell()))
  114. def read_index(f):
  115. """Read an index file, yielding the individual entries."""
  116. header = f.read(4)
  117. if header != b'DIRC':
  118. raise AssertionError("Invalid index file header: %r" % header)
  119. (version, num_entries) = struct.unpack(b'>LL', f.read(4 * 2))
  120. assert version in (1, 2)
  121. for i in range(num_entries):
  122. yield read_cache_entry(f)
  123. def read_index_dict(f):
  124. """Read an index file and return it as a dictionary.
  125. :param f: File object to read from
  126. """
  127. ret = {}
  128. for x in read_index(f):
  129. ret[x[0]] = IndexEntry(*x[1:])
  130. return ret
  131. def write_index(f, entries):
  132. """Write an index file.
  133. :param f: File-like object to write to
  134. :param entries: Iterable over the entries to write
  135. """
  136. f.write(b'DIRC')
  137. f.write(struct.pack(b'>LL', 2, len(entries)))
  138. for x in entries:
  139. write_cache_entry(f, x)
  140. def write_index_dict(f, entries):
  141. """Write an index file based on the contents of a dictionary.
  142. """
  143. entries_list = []
  144. for name in sorted(entries):
  145. entries_list.append((name,) + tuple(entries[name]))
  146. write_index(f, entries_list)
  147. def cleanup_mode(mode):
  148. """Cleanup a mode value.
  149. This will return a mode that can be stored in a tree object.
  150. :param mode: Mode to clean up.
  151. """
  152. if stat.S_ISLNK(mode):
  153. return stat.S_IFLNK
  154. elif stat.S_ISDIR(mode):
  155. return stat.S_IFDIR
  156. elif S_ISGITLINK(mode):
  157. return S_IFGITLINK
  158. ret = stat.S_IFREG | 0o644
  159. ret |= (mode & 0o111)
  160. return ret
  161. class Index(object):
  162. """A Git Index file."""
  163. def __init__(self, filename):
  164. """Open an index file.
  165. :param filename: Path to the index file
  166. """
  167. self._filename = filename
  168. self.clear()
  169. self.read()
  170. @property
  171. def path(self):
  172. return self._filename
  173. def __repr__(self):
  174. return "%s(%r)" % (self.__class__.__name__, self._filename)
  175. def write(self):
  176. """Write current contents of index to disk."""
  177. f = GitFile(self._filename, 'wb')
  178. try:
  179. f = SHA1Writer(f)
  180. write_index_dict(f, self._byname)
  181. finally:
  182. f.close()
  183. def read(self):
  184. """Read current contents of index from disk."""
  185. if not os.path.exists(self._filename):
  186. return
  187. f = GitFile(self._filename, 'rb')
  188. try:
  189. f = SHA1Reader(f)
  190. for x in read_index(f):
  191. self[x[0]] = IndexEntry(*x[1:])
  192. # FIXME: Additional data?
  193. f.read(os.path.getsize(self._filename)-f.tell()-20)
  194. f.check_sha()
  195. finally:
  196. f.close()
  197. def __len__(self):
  198. """Number of entries in this index file."""
  199. return len(self._byname)
  200. def __getitem__(self, name):
  201. """Retrieve entry by relative path.
  202. :return: tuple with (ctime, mtime, dev, ino, mode, uid, gid, size, sha,
  203. flags)
  204. """
  205. return self._byname[name]
  206. def __iter__(self):
  207. """Iterate over the paths in this index."""
  208. return iter(self._byname)
  209. def get_sha1(self, path):
  210. """Return the (git object) SHA1 for the object at a path."""
  211. return self[path].sha
  212. def get_mode(self, path):
  213. """Return the POSIX file mode for the object at a path."""
  214. return self[path].mode
  215. def iterobjects(self):
  216. """Iterate over path, sha, mode tuples for use with commit_tree."""
  217. for path in self:
  218. entry = self[path]
  219. yield path, entry.sha, cleanup_mode(entry.mode)
  220. def iterblobs(self):
  221. import warnings
  222. warnings.warn('Use iterobjects() instead.', PendingDeprecationWarning)
  223. return self.iterobjects()
  224. def clear(self):
  225. """Remove all contents from this index."""
  226. self._byname = {}
  227. def __setitem__(self, name, x):
  228. assert isinstance(name, bytes)
  229. assert len(x) == 10
  230. # Remove the old entry if any
  231. self._byname[name] = IndexEntry(*x)
  232. def __delitem__(self, name):
  233. assert isinstance(name, bytes)
  234. del self._byname[name]
  235. def iteritems(self):
  236. return self._byname.items()
  237. def update(self, entries):
  238. for name, value in entries.items():
  239. self[name] = value
  240. def changes_from_tree(self, object_store, tree, want_unchanged=False):
  241. """Find the differences between the contents of this index and a tree.
  242. :param object_store: Object store to use for retrieving tree contents
  243. :param tree: SHA1 of the root tree
  244. :param want_unchanged: Whether unchanged files should be reported
  245. :return: Iterator over tuples with (oldpath, newpath), (oldmode,
  246. newmode), (oldsha, newsha)
  247. """
  248. def lookup_entry(path):
  249. entry = self[path]
  250. return entry.sha, entry.mode
  251. for (name, mode, sha) in changes_from_tree(
  252. self._byname.keys(), lookup_entry, object_store, tree,
  253. want_unchanged=want_unchanged):
  254. yield (name, mode, sha)
  255. def commit(self, object_store):
  256. """Create a new tree from an index.
  257. :param object_store: Object store to save the tree in
  258. :return: Root tree SHA
  259. """
  260. return commit_tree(object_store, self.iterobjects())
  261. def commit_tree(object_store, blobs):
  262. """Commit a new tree.
  263. :param object_store: Object store to add trees to
  264. :param blobs: Iterable over blob path, sha, mode entries
  265. :return: SHA1 of the created tree.
  266. """
  267. trees = {b'': {}}
  268. def add_tree(path):
  269. if path in trees:
  270. return trees[path]
  271. dirname, basename = pathsplit(path)
  272. t = add_tree(dirname)
  273. assert isinstance(basename, bytes)
  274. newtree = {}
  275. t[basename] = newtree
  276. trees[path] = newtree
  277. return newtree
  278. for path, sha, mode in blobs:
  279. tree_path, basename = pathsplit(path)
  280. tree = add_tree(tree_path)
  281. tree[basename] = (mode, sha)
  282. def build_tree(path):
  283. tree = Tree()
  284. for basename, entry in trees[path].items():
  285. if isinstance(entry, dict):
  286. mode = stat.S_IFDIR
  287. sha = build_tree(pathjoin(path, basename))
  288. else:
  289. (mode, sha) = entry
  290. tree.add(basename, mode, sha)
  291. object_store.add_object(tree)
  292. return tree.id
  293. return build_tree(b'')
  294. def commit_index(object_store, index):
  295. """Create a new tree from an index.
  296. :param object_store: Object store to save the tree in
  297. :param index: Index file
  298. :note: This function is deprecated, use index.commit() instead.
  299. :return: Root tree sha.
  300. """
  301. return commit_tree(object_store, index.iterobjects())
  302. def changes_from_tree(names, lookup_entry, object_store, tree,
  303. want_unchanged=False):
  304. """Find the differences between the contents of a tree and
  305. a working copy.
  306. :param names: Iterable of names in the working copy
  307. :param lookup_entry: Function to lookup an entry in the working copy
  308. :param object_store: Object store to use for retrieving tree contents
  309. :param tree: SHA1 of the root tree, or None for an empty tree
  310. :param want_unchanged: Whether unchanged files should be reported
  311. :return: Iterator over tuples with (oldpath, newpath), (oldmode, newmode),
  312. (oldsha, newsha)
  313. """
  314. # TODO(jelmer): Support a include_trees option
  315. other_names = set(names)
  316. if tree is not None:
  317. for (name, mode, sha) in object_store.iter_tree_contents(tree):
  318. try:
  319. (other_sha, other_mode) = lookup_entry(name)
  320. except KeyError:
  321. # Was removed
  322. yield ((name, None), (mode, None), (sha, None))
  323. else:
  324. other_names.remove(name)
  325. if (want_unchanged or other_sha != sha or other_mode != mode):
  326. yield ((name, name), (mode, other_mode), (sha, other_sha))
  327. # Mention added files
  328. for name in other_names:
  329. try:
  330. (other_sha, other_mode) = lookup_entry(name)
  331. except KeyError:
  332. pass
  333. else:
  334. yield ((None, name), (None, other_mode), (None, other_sha))
  335. def index_entry_from_stat(stat_val, hex_sha, flags, mode=None):
  336. """Create a new index entry from a stat value.
  337. :param stat_val: POSIX stat_result instance
  338. :param hex_sha: Hex sha of the object
  339. :param flags: Index flags
  340. """
  341. if mode is None:
  342. mode = cleanup_mode(stat_val.st_mode)
  343. return IndexEntry(
  344. stat_val.st_ctime, stat_val.st_mtime, stat_val.st_dev,
  345. stat_val.st_ino, mode, stat_val.st_uid,
  346. stat_val.st_gid, stat_val.st_size, hex_sha, flags)
  347. def build_file_from_blob(blob, mode, target_path, honor_filemode=True):
  348. """Build a file or symlink on disk based on a Git object.
  349. :param obj: The git object
  350. :param mode: File mode
  351. :param target_path: Path to write to
  352. :param honor_filemode: An optional flag to honor core.filemode setting in
  353. config file, default is core.filemode=True, change executable bit
  354. :return: stat object for the file
  355. """
  356. try:
  357. oldstat = os.lstat(target_path)
  358. except OSError as e:
  359. if e.errno == errno.ENOENT:
  360. oldstat = None
  361. else:
  362. raise
  363. contents = blob.as_raw_string()
  364. if stat.S_ISLNK(mode):
  365. # FIXME: This will fail on Windows. What should we do instead?
  366. if oldstat:
  367. os.unlink(target_path)
  368. if sys.platform == 'win32' and sys.version_info[0] == 3:
  369. # os.readlink on Python3 on Windows requires a unicode string.
  370. # TODO(jelmer): Don't assume tree_encoding == fs_encoding
  371. tree_encoding = sys.getfilesystemencoding()
  372. contents = contents.decode(tree_encoding)
  373. target_path = target_path.decode(tree_encoding)
  374. os.symlink(contents, target_path)
  375. else:
  376. if oldstat is not None and oldstat.st_size == len(contents):
  377. with open(target_path, 'rb') as f:
  378. if f.read() == contents:
  379. return oldstat
  380. with open(target_path, 'wb') as f:
  381. # Write out file
  382. f.write(contents)
  383. if honor_filemode:
  384. os.chmod(target_path, mode)
  385. return os.lstat(target_path)
  386. INVALID_DOTNAMES = (b".git", b".", b"..", b"")
  387. def validate_path_element_default(element):
  388. return element.lower() not in INVALID_DOTNAMES
  389. def validate_path_element_ntfs(element):
  390. stripped = element.rstrip(b". ").lower()
  391. if stripped in INVALID_DOTNAMES:
  392. return False
  393. if stripped == b"git~1":
  394. return False
  395. return True
  396. def validate_path(path, element_validator=validate_path_element_default):
  397. """Default path validator that just checks for .git/."""
  398. parts = path.split(b"/")
  399. for p in parts:
  400. if not element_validator(p):
  401. return False
  402. else:
  403. return True
  404. def build_index_from_tree(root_path, index_path, object_store, tree_id,
  405. honor_filemode=True,
  406. validate_path_element=validate_path_element_default):
  407. """Generate and materialize index from a tree
  408. :param tree_id: Tree to materialize
  409. :param root_path: Target dir for materialized index files
  410. :param index_path: Target path for generated index
  411. :param object_store: Non-empty object store holding tree contents
  412. :param honor_filemode: An optional flag to honor core.filemode setting in
  413. config file, default is core.filemode=True, change executable bit
  414. :param validate_path_element: Function to validate path elements to check
  415. out; default just refuses .git and .. directories.
  416. :note:: existing index is wiped and contents are not merged
  417. in a working dir. Suitable only for fresh clones.
  418. """
  419. index = Index(index_path)
  420. if not isinstance(root_path, bytes):
  421. root_path = root_path.encode(sys.getfilesystemencoding())
  422. for entry in object_store.iter_tree_contents(tree_id):
  423. if not validate_path(entry.path, validate_path_element):
  424. continue
  425. full_path = _tree_to_fs_path(root_path, entry.path)
  426. if not os.path.exists(os.path.dirname(full_path)):
  427. os.makedirs(os.path.dirname(full_path))
  428. # TODO(jelmer): Merge new index into working tree
  429. if S_ISGITLINK(entry.mode):
  430. if not os.path.isdir(full_path):
  431. os.mkdir(full_path)
  432. st = os.lstat(full_path)
  433. # TODO(jelmer): record and return submodule paths
  434. else:
  435. obj = object_store[entry.sha]
  436. st = build_file_from_blob(
  437. obj, entry.mode, full_path, honor_filemode=honor_filemode)
  438. # Add file to index
  439. if not honor_filemode or S_ISGITLINK(entry.mode):
  440. # we can not use tuple slicing to build a new tuple,
  441. # because on windows that will convert the times to
  442. # longs, which causes errors further along
  443. st_tuple = (entry.mode, st.st_ino, st.st_dev, st.st_nlink,
  444. st.st_uid, st.st_gid, st.st_size, st.st_atime,
  445. st.st_mtime, st.st_ctime)
  446. st = st.__class__(st_tuple)
  447. index[entry.path] = index_entry_from_stat(st, entry.sha, 0)
  448. index.write()
  449. def blob_from_path_and_stat(fs_path, st):
  450. """Create a blob from a path and a stat object.
  451. :param fs_path: Full file system path to file
  452. :param st: A stat object
  453. :return: A `Blob` object
  454. """
  455. assert isinstance(fs_path, bytes)
  456. blob = Blob()
  457. if not stat.S_ISLNK(st.st_mode):
  458. with open(fs_path, 'rb') as f:
  459. blob.data = f.read()
  460. else:
  461. if sys.platform == 'win32' and sys.version_info[0] == 3:
  462. # os.readlink on Python3 on Windows requires a unicode string.
  463. # TODO(jelmer): Don't assume tree_encoding == fs_encoding
  464. tree_encoding = sys.getfilesystemencoding()
  465. fs_path = fs_path.decode(tree_encoding)
  466. blob.data = os.readlink(fs_path).encode(tree_encoding)
  467. else:
  468. blob.data = os.readlink(fs_path)
  469. return blob
  470. def read_submodule_head(path):
  471. """Read the head commit of a submodule.
  472. :param path: path to the submodule
  473. :return: HEAD sha, None if not a valid head/repository
  474. """
  475. from dulwich.errors import NotGitRepository
  476. from dulwich.repo import Repo
  477. try:
  478. repo = Repo(path)
  479. except NotGitRepository:
  480. return None
  481. try:
  482. return repo.head()
  483. except KeyError:
  484. return None
  485. def get_unstaged_changes(index, root_path):
  486. """Walk through an index and check for differences against working tree.
  487. :param index: index to check
  488. :param root_path: path in which to find files
  489. :return: iterator over paths with unstaged changes
  490. """
  491. # For each entry in the index check the sha1 & ensure not staged
  492. if not isinstance(root_path, bytes):
  493. root_path = root_path.encode(sys.getfilesystemencoding())
  494. for tree_path, entry in index.iteritems():
  495. full_path = _tree_to_fs_path(root_path, tree_path)
  496. try:
  497. blob = blob_from_path_and_stat(full_path, os.lstat(full_path))
  498. except OSError as e:
  499. if e.errno != errno.ENOENT:
  500. raise
  501. # The file was removed, so we assume that counts as
  502. # different from whatever file used to exist.
  503. yield tree_path
  504. except IOError as e:
  505. if e.errno != errno.EISDIR:
  506. raise
  507. # This is actually a directory
  508. if os.path.exists(os.path.join(tree_path, '.git')):
  509. # Submodule
  510. head = read_submodule_head(tree_path)
  511. if entry.sha != head:
  512. yield tree_path
  513. else:
  514. # The file was changed to a directory, so consider it removed.
  515. yield tree_path
  516. else:
  517. if blob.id != entry.sha:
  518. yield tree_path
  519. os_sep_bytes = os.sep.encode('ascii')
  520. def _tree_to_fs_path(root_path, tree_path):
  521. """Convert a git tree path to a file system path.
  522. :param root_path: Root filesystem path
  523. :param tree_path: Git tree path as bytes
  524. :return: File system path.
  525. """
  526. assert isinstance(tree_path, bytes)
  527. if os_sep_bytes != b'/':
  528. sep_corrected_path = tree_path.replace(b'/', os_sep_bytes)
  529. else:
  530. sep_corrected_path = tree_path
  531. return os.path.join(root_path, sep_corrected_path)
  532. def _fs_to_tree_path(fs_path, fs_encoding=None):
  533. """Convert a file system path to a git tree path.
  534. :param fs_path: File system path.
  535. :param fs_encoding: File system encoding
  536. :return: Git tree path as bytes
  537. """
  538. if fs_encoding is None:
  539. fs_encoding = sys.getfilesystemencoding()
  540. if not isinstance(fs_path, bytes):
  541. fs_path_bytes = fs_path.encode(fs_encoding)
  542. else:
  543. fs_path_bytes = fs_path
  544. if os_sep_bytes != b'/':
  545. tree_path = fs_path_bytes.replace(os_sep_bytes, b'/')
  546. else:
  547. tree_path = fs_path_bytes
  548. return tree_path
  549. def index_entry_from_path(path, object_store=None):
  550. """Create an index from a filesystem path.
  551. This returns an index value for files, symlinks
  552. and tree references. for directories and
  553. non-existant files it returns None
  554. :param path: Path to create an index entry for
  555. :param object_store: Optional object store to
  556. save new blobs in
  557. :return: An index entry
  558. """
  559. try:
  560. st = os.lstat(path)
  561. blob = blob_from_path_and_stat(path, st)
  562. except EnvironmentError as e:
  563. if e.errno == errno.EISDIR:
  564. if os.path.exists(os.path.join(path, '.git')):
  565. head = read_submodule_head(path)
  566. if head is None:
  567. return None
  568. return index_entry_from_stat(
  569. st, head, 0, mode=S_IFGITLINK)
  570. else:
  571. raise
  572. else:
  573. raise
  574. else:
  575. if object_store is not None:
  576. object_store.add_object(blob)
  577. return index_entry_from_stat(st, blob.id, 0)
  578. def iter_fresh_entries(paths, root_path, object_store=None):
  579. """Iterate over current versions of index entries on disk.
  580. :param paths: Paths to iterate over
  581. :param root_path: Root path to access from
  582. :param store: Optional store to save new blobs in
  583. :return: Iterator over path, index_entry
  584. """
  585. for path in paths:
  586. p = _tree_to_fs_path(root_path, path)
  587. try:
  588. entry = index_entry_from_path(p, object_store=object_store)
  589. except EnvironmentError as e:
  590. if e.errno in (errno.ENOENT, errno.EISDIR):
  591. entry = None
  592. else:
  593. raise
  594. yield path, entry
  595. def iter_fresh_blobs(index, root_path):
  596. """Iterate over versions of blobs on disk referenced by index.
  597. Don't use this function; it removes missing entries from index.
  598. :param index: Index file
  599. :param root_path: Root path to access from
  600. :param include_deleted: Include deleted entries with sha and
  601. mode set to None
  602. :return: Iterator over path, sha, mode
  603. """
  604. import warnings
  605. warnings.warn(PendingDeprecationWarning,
  606. "Use iter_fresh_objects instead.")
  607. for entry in iter_fresh_objects(
  608. index, root_path, include_deleted=True):
  609. if entry[1] is None:
  610. del index[entry[0]]
  611. else:
  612. yield entry
  613. def iter_fresh_objects(paths, root_path, include_deleted=False,
  614. object_store=None):
  615. """Iterate over versions of objecs on disk referenced by index.
  616. :param index: Index file
  617. :param root_path: Root path to access from
  618. :param include_deleted: Include deleted entries with sha and
  619. mode set to None
  620. :param object_store: Optional object store to report new items to
  621. :return: Iterator over path, sha, mode
  622. """
  623. for path, entry in iter_fresh_entries(paths, root_path,
  624. object_store=object_store):
  625. if entry is None:
  626. if include_deleted:
  627. yield path, None, None
  628. else:
  629. entry = IndexEntry(*entry)
  630. yield path, entry.sha, cleanup_mode(entry.mode)
  631. def refresh_index(index, root_path):
  632. """Refresh the contents of an index.
  633. This is the equivalent to running 'git commit -a'.
  634. :param index: Index to update
  635. :param root_path: Root filesystem path
  636. """
  637. for path, entry in iter_fresh_entries(index, root_path):
  638. index[path] = path