index.py 25 KB

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