2
0

index.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. # index.py -- File parser/writer for the git index file
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Parser for the git index file format."""
  22. import os
  23. import stat
  24. import struct
  25. import sys
  26. from collections.abc import Iterable, Iterator
  27. from dataclasses import dataclass
  28. from enum import Enum
  29. from typing import (
  30. Any,
  31. BinaryIO,
  32. Callable,
  33. Optional,
  34. Union,
  35. )
  36. from .file import GitFile
  37. from .object_store import iter_tree_contents
  38. from .objects import (
  39. S_IFGITLINK,
  40. S_ISGITLINK,
  41. Blob,
  42. ObjectID,
  43. Tree,
  44. hex_to_sha,
  45. sha_to_hex,
  46. )
  47. from .pack import ObjectContainer, SHA1Reader, SHA1Writer
  48. # 2-bit stage (during merge)
  49. FLAG_STAGEMASK = 0x3000
  50. FLAG_STAGESHIFT = 12
  51. FLAG_NAMEMASK = 0x0FFF
  52. # assume-valid
  53. FLAG_VALID = 0x8000
  54. # extended flag (must be zero in version 2)
  55. FLAG_EXTENDED = 0x4000
  56. # used by sparse checkout
  57. EXTENDED_FLAG_SKIP_WORKTREE = 0x4000
  58. # used by "git add -N"
  59. EXTENDED_FLAG_INTEND_TO_ADD = 0x2000
  60. DEFAULT_VERSION = 2
  61. class Stage(Enum):
  62. NORMAL = 0
  63. MERGE_CONFLICT_ANCESTOR = 1
  64. MERGE_CONFLICT_THIS = 2
  65. MERGE_CONFLICT_OTHER = 3
  66. @dataclass
  67. class SerializedIndexEntry:
  68. name: bytes
  69. ctime: Union[int, float, tuple[int, int]]
  70. mtime: Union[int, float, tuple[int, int]]
  71. dev: int
  72. ino: int
  73. mode: int
  74. uid: int
  75. gid: int
  76. size: int
  77. sha: bytes
  78. flags: int
  79. extended_flags: int
  80. def stage(self) -> Stage:
  81. return Stage((self.flags & FLAG_STAGEMASK) >> FLAG_STAGESHIFT)
  82. @dataclass
  83. class IndexEntry:
  84. ctime: Union[int, float, tuple[int, int]]
  85. mtime: Union[int, float, tuple[int, int]]
  86. dev: int
  87. ino: int
  88. mode: int
  89. uid: int
  90. gid: int
  91. size: int
  92. sha: bytes
  93. @classmethod
  94. def from_serialized(cls, serialized: SerializedIndexEntry) -> "IndexEntry":
  95. return cls(
  96. ctime=serialized.ctime,
  97. mtime=serialized.mtime,
  98. dev=serialized.dev,
  99. ino=serialized.ino,
  100. mode=serialized.mode,
  101. uid=serialized.uid,
  102. gid=serialized.gid,
  103. size=serialized.size,
  104. sha=serialized.sha,
  105. )
  106. def serialize(self, name: bytes, stage: Stage) -> SerializedIndexEntry:
  107. return SerializedIndexEntry(
  108. name=name,
  109. ctime=self.ctime,
  110. mtime=self.mtime,
  111. dev=self.dev,
  112. ino=self.ino,
  113. mode=self.mode,
  114. uid=self.uid,
  115. gid=self.gid,
  116. size=self.size,
  117. sha=self.sha,
  118. flags=stage.value << FLAG_STAGESHIFT,
  119. extended_flags=0,
  120. )
  121. class ConflictedIndexEntry:
  122. """Index entry that represents a conflict."""
  123. ancestor: Optional[IndexEntry]
  124. this: Optional[IndexEntry]
  125. other: Optional[IndexEntry]
  126. def __init__(
  127. self,
  128. ancestor: Optional[IndexEntry] = None,
  129. this: Optional[IndexEntry] = None,
  130. other: Optional[IndexEntry] = None,
  131. ) -> None:
  132. self.ancestor = ancestor
  133. self.this = this
  134. self.other = other
  135. class UnmergedEntries(Exception):
  136. """Unmerged entries exist in the index."""
  137. def pathsplit(path: bytes) -> tuple[bytes, bytes]:
  138. """Split a /-delimited path into a directory part and a basename.
  139. Args:
  140. path: The path to split.
  141. Returns:
  142. Tuple with directory name and basename
  143. """
  144. try:
  145. (dirname, basename) = path.rsplit(b"/", 1)
  146. except ValueError:
  147. return (b"", path)
  148. else:
  149. return (dirname, basename)
  150. def pathjoin(*args):
  151. """Join a /-delimited path."""
  152. return b"/".join([p for p in args if p])
  153. def read_cache_time(f):
  154. """Read a cache time.
  155. Args:
  156. f: File-like object to read from
  157. Returns:
  158. Tuple with seconds and nanoseconds
  159. """
  160. return struct.unpack(">LL", f.read(8))
  161. def write_cache_time(f, t) -> None:
  162. """Write a cache time.
  163. Args:
  164. f: File-like object to write to
  165. t: Time to write (as int, float or tuple with secs and nsecs)
  166. """
  167. if isinstance(t, int):
  168. t = (t, 0)
  169. elif isinstance(t, float):
  170. (secs, nsecs) = divmod(t, 1.0)
  171. t = (int(secs), int(nsecs * 1000000000))
  172. elif not isinstance(t, tuple):
  173. raise TypeError(t)
  174. f.write(struct.pack(">LL", *t))
  175. def read_cache_entry(f, version: int) -> SerializedIndexEntry:
  176. """Read an entry from a cache file.
  177. Args:
  178. f: File-like object to read from
  179. """
  180. beginoffset = f.tell()
  181. ctime = read_cache_time(f)
  182. mtime = read_cache_time(f)
  183. (
  184. dev,
  185. ino,
  186. mode,
  187. uid,
  188. gid,
  189. size,
  190. sha,
  191. flags,
  192. ) = struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2))
  193. if flags & FLAG_EXTENDED:
  194. if version < 3:
  195. raise AssertionError("extended flag set in index with version < 3")
  196. (extended_flags,) = struct.unpack(">H", f.read(2))
  197. else:
  198. extended_flags = 0
  199. name = f.read(flags & FLAG_NAMEMASK)
  200. # Padding:
  201. if version < 4:
  202. real_size = (f.tell() - beginoffset + 8) & ~7
  203. f.read((beginoffset + real_size) - f.tell())
  204. return SerializedIndexEntry(
  205. name,
  206. ctime,
  207. mtime,
  208. dev,
  209. ino,
  210. mode,
  211. uid,
  212. gid,
  213. size,
  214. sha_to_hex(sha),
  215. flags & ~FLAG_NAMEMASK,
  216. extended_flags,
  217. )
  218. def write_cache_entry(f, entry: SerializedIndexEntry, version: int) -> None:
  219. """Write an index entry to a file.
  220. Args:
  221. f: File object
  222. entry: IndexEntry to write, tuple with:
  223. """
  224. beginoffset = f.tell()
  225. write_cache_time(f, entry.ctime)
  226. write_cache_time(f, entry.mtime)
  227. flags = len(entry.name) | (entry.flags & ~FLAG_NAMEMASK)
  228. if entry.extended_flags:
  229. flags |= FLAG_EXTENDED
  230. if flags & FLAG_EXTENDED and version is not None and version < 3:
  231. raise AssertionError("unable to use extended flags in version < 3")
  232. f.write(
  233. struct.pack(
  234. b">LLLLLL20sH",
  235. entry.dev & 0xFFFFFFFF,
  236. entry.ino & 0xFFFFFFFF,
  237. entry.mode,
  238. entry.uid,
  239. entry.gid,
  240. entry.size,
  241. hex_to_sha(entry.sha),
  242. flags,
  243. )
  244. )
  245. if flags & FLAG_EXTENDED:
  246. f.write(struct.pack(b">H", entry.extended_flags))
  247. f.write(entry.name)
  248. if version < 4:
  249. real_size = (f.tell() - beginoffset + 8) & ~7
  250. f.write(b"\0" * ((beginoffset + real_size) - f.tell()))
  251. class UnsupportedIndexFormat(Exception):
  252. """An unsupported index format was encountered."""
  253. def __init__(self, version) -> None:
  254. self.index_format_version = version
  255. def read_index(f: BinaryIO) -> Iterator[SerializedIndexEntry]:
  256. """Read an index file, yielding the individual entries."""
  257. header = f.read(4)
  258. if header != b"DIRC":
  259. raise AssertionError(f"Invalid index file header: {header!r}")
  260. (version, num_entries) = struct.unpack(b">LL", f.read(4 * 2))
  261. if version not in (1, 2, 3):
  262. raise UnsupportedIndexFormat(version)
  263. for i in range(num_entries):
  264. yield read_cache_entry(f, version)
  265. def read_index_dict(f) -> dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]:
  266. """Read an index file and return it as a dictionary.
  267. Dict Key is tuple of path and stage number, as
  268. path alone is not unique
  269. Args:
  270. f: File object to read fromls.
  271. """
  272. ret: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] = {}
  273. for entry in read_index(f):
  274. stage = entry.stage()
  275. if stage == Stage.NORMAL:
  276. ret[entry.name] = IndexEntry.from_serialized(entry)
  277. else:
  278. existing = ret.setdefault(entry.name, ConflictedIndexEntry())
  279. if isinstance(existing, IndexEntry):
  280. raise AssertionError(f"Non-conflicted entry for {entry.name!r} exists")
  281. if stage == Stage.MERGE_CONFLICT_ANCESTOR:
  282. existing.ancestor = IndexEntry.from_serialized(entry)
  283. elif stage == Stage.MERGE_CONFLICT_THIS:
  284. existing.this = IndexEntry.from_serialized(entry)
  285. elif stage == Stage.MERGE_CONFLICT_OTHER:
  286. existing.other = IndexEntry.from_serialized(entry)
  287. return ret
  288. def write_index(
  289. f: BinaryIO, entries: list[SerializedIndexEntry], version: Optional[int] = None
  290. ) -> None:
  291. """Write an index file.
  292. Args:
  293. f: File-like object to write to
  294. version: Version number to write
  295. entries: Iterable over the entries to write
  296. """
  297. if version is None:
  298. version = DEFAULT_VERSION
  299. f.write(b"DIRC")
  300. f.write(struct.pack(b">LL", version, len(entries)))
  301. for entry in entries:
  302. write_cache_entry(f, entry, version)
  303. def write_index_dict(
  304. f: BinaryIO,
  305. entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]],
  306. version: Optional[int] = None,
  307. ) -> None:
  308. """Write an index file based on the contents of a dictionary.
  309. being careful to sort by path and then by stage.
  310. """
  311. entries_list = []
  312. for key in sorted(entries):
  313. value = entries[key]
  314. if isinstance(value, ConflictedIndexEntry):
  315. if value.ancestor is not None:
  316. entries_list.append(
  317. value.ancestor.serialize(key, Stage.MERGE_CONFLICT_ANCESTOR)
  318. )
  319. if value.this is not None:
  320. entries_list.append(
  321. value.this.serialize(key, Stage.MERGE_CONFLICT_THIS)
  322. )
  323. if value.other is not None:
  324. entries_list.append(
  325. value.other.serialize(key, Stage.MERGE_CONFLICT_OTHER)
  326. )
  327. else:
  328. entries_list.append(value.serialize(key, Stage.NORMAL))
  329. write_index(f, entries_list, version=version)
  330. def cleanup_mode(mode: int) -> int:
  331. """Cleanup a mode value.
  332. This will return a mode that can be stored in a tree object.
  333. Args:
  334. mode: Mode to clean up.
  335. Returns:
  336. mode
  337. """
  338. if stat.S_ISLNK(mode):
  339. return stat.S_IFLNK
  340. elif stat.S_ISDIR(mode):
  341. return stat.S_IFDIR
  342. elif S_ISGITLINK(mode):
  343. return S_IFGITLINK
  344. ret = stat.S_IFREG | 0o644
  345. if mode & 0o100:
  346. ret |= 0o111
  347. return ret
  348. class Index:
  349. """A Git Index file."""
  350. _byname: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]
  351. def __init__(self, filename: Union[bytes, str], read=True) -> None:
  352. """Create an index object associated with the given filename.
  353. Args:
  354. filename: Path to the index file
  355. read: Whether to initialize the index from the given file, should it exist.
  356. """
  357. self._filename = filename
  358. # TODO(jelmer): Store the version returned by read_index
  359. self._version = None
  360. self.clear()
  361. if read:
  362. self.read()
  363. @property
  364. def path(self):
  365. return self._filename
  366. def __repr__(self) -> str:
  367. return f"{self.__class__.__name__}({self._filename!r})"
  368. def write(self) -> None:
  369. """Write current contents of index to disk."""
  370. f = GitFile(self._filename, "wb")
  371. try:
  372. f = SHA1Writer(f)
  373. write_index_dict(f, self._byname, version=self._version)
  374. finally:
  375. f.close()
  376. def read(self) -> None:
  377. """Read current contents of index from disk."""
  378. if not os.path.exists(self._filename):
  379. return
  380. f = GitFile(self._filename, "rb")
  381. try:
  382. f = SHA1Reader(f)
  383. self.update(read_index_dict(f))
  384. # FIXME: Additional data?
  385. f.read(os.path.getsize(self._filename) - f.tell() - 20)
  386. f.check_sha()
  387. finally:
  388. f.close()
  389. def __len__(self) -> int:
  390. """Number of entries in this index file."""
  391. return len(self._byname)
  392. def __getitem__(self, key: bytes) -> Union[IndexEntry, ConflictedIndexEntry]:
  393. """Retrieve entry by relative path and stage.
  394. Returns: Either a IndexEntry or a ConflictedIndexEntry
  395. Raises KeyError: if the entry does not exist
  396. """
  397. return self._byname[key]
  398. def __iter__(self) -> Iterator[bytes]:
  399. """Iterate over the paths and stages in this index."""
  400. return iter(self._byname)
  401. def __contains__(self, key) -> bool:
  402. return key in self._byname
  403. def get_sha1(self, path: bytes) -> bytes:
  404. """Return the (git object) SHA1 for the object at a path."""
  405. value = self[path]
  406. if isinstance(value, ConflictedIndexEntry):
  407. raise UnmergedEntries
  408. return value.sha
  409. def get_mode(self, path: bytes) -> int:
  410. """Return the POSIX file mode for the object at a path."""
  411. value = self[path]
  412. if isinstance(value, ConflictedIndexEntry):
  413. raise UnmergedEntries
  414. return value.mode
  415. def iterobjects(self) -> Iterable[tuple[bytes, bytes, int]]:
  416. """Iterate over path, sha, mode tuples for use with commit_tree."""
  417. for path in self:
  418. entry = self[path]
  419. if isinstance(entry, ConflictedIndexEntry):
  420. raise UnmergedEntries
  421. yield path, entry.sha, cleanup_mode(entry.mode)
  422. def has_conflicts(self) -> bool:
  423. for value in self._byname.values():
  424. if isinstance(value, ConflictedIndexEntry):
  425. return True
  426. return False
  427. def clear(self) -> None:
  428. """Remove all contents from this index."""
  429. self._byname = {}
  430. def __setitem__(
  431. self, name: bytes, value: Union[IndexEntry, ConflictedIndexEntry]
  432. ) -> None:
  433. assert isinstance(name, bytes)
  434. self._byname[name] = value
  435. def __delitem__(self, name: bytes) -> None:
  436. del self._byname[name]
  437. def iteritems(
  438. self,
  439. ) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]:
  440. return iter(self._byname.items())
  441. def items(self) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]:
  442. return iter(self._byname.items())
  443. def update(
  444. self, entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]
  445. ) -> None:
  446. for key, value in entries.items():
  447. self[key] = value
  448. def paths(self):
  449. yield from self._byname.keys()
  450. def changes_from_tree(
  451. self, object_store, tree: ObjectID, want_unchanged: bool = False
  452. ):
  453. """Find the differences between the contents of this index and a tree.
  454. Args:
  455. object_store: Object store to use for retrieving tree contents
  456. tree: SHA1 of the root tree
  457. want_unchanged: Whether unchanged files should be reported
  458. Returns: Iterator over tuples with (oldpath, newpath), (oldmode,
  459. newmode), (oldsha, newsha)
  460. """
  461. def lookup_entry(path):
  462. entry = self[path]
  463. return entry.sha, cleanup_mode(entry.mode)
  464. yield from changes_from_tree(
  465. self.paths(),
  466. lookup_entry,
  467. object_store,
  468. tree,
  469. want_unchanged=want_unchanged,
  470. )
  471. def commit(self, object_store):
  472. """Create a new tree from an index.
  473. Args:
  474. object_store: Object store to save the tree in
  475. Returns:
  476. Root tree SHA
  477. """
  478. return commit_tree(object_store, self.iterobjects())
  479. def commit_tree(
  480. object_store: ObjectContainer, blobs: Iterable[tuple[bytes, bytes, int]]
  481. ) -> bytes:
  482. """Commit a new tree.
  483. Args:
  484. object_store: Object store to add trees to
  485. blobs: Iterable over blob path, sha, mode entries
  486. Returns:
  487. SHA1 of the created tree.
  488. """
  489. trees: dict[bytes, Any] = {b"": {}}
  490. def add_tree(path):
  491. if path in trees:
  492. return trees[path]
  493. dirname, basename = pathsplit(path)
  494. t = add_tree(dirname)
  495. assert isinstance(basename, bytes)
  496. newtree = {}
  497. t[basename] = newtree
  498. trees[path] = newtree
  499. return newtree
  500. for path, sha, mode in blobs:
  501. tree_path, basename = pathsplit(path)
  502. tree = add_tree(tree_path)
  503. tree[basename] = (mode, sha)
  504. def build_tree(path):
  505. tree = Tree()
  506. for basename, entry in trees[path].items():
  507. if isinstance(entry, dict):
  508. mode = stat.S_IFDIR
  509. sha = build_tree(pathjoin(path, basename))
  510. else:
  511. (mode, sha) = entry
  512. tree.add(basename, mode, sha)
  513. object_store.add_object(tree)
  514. return tree.id
  515. return build_tree(b"")
  516. def commit_index(object_store: ObjectContainer, index: Index) -> bytes:
  517. """Create a new tree from an index.
  518. Args:
  519. object_store: Object store to save the tree in
  520. index: Index file
  521. Note: This function is deprecated, use index.commit() instead.
  522. Returns: Root tree sha.
  523. """
  524. return commit_tree(object_store, index.iterobjects())
  525. def changes_from_tree(
  526. names: Iterable[bytes],
  527. lookup_entry: Callable[[bytes], tuple[bytes, int]],
  528. object_store: ObjectContainer,
  529. tree: Optional[bytes],
  530. want_unchanged=False,
  531. ) -> Iterable[
  532. tuple[
  533. tuple[Optional[bytes], Optional[bytes]],
  534. tuple[Optional[int], Optional[int]],
  535. tuple[Optional[bytes], Optional[bytes]],
  536. ]
  537. ]:
  538. """Find the differences between the contents of a tree and
  539. a working copy.
  540. Args:
  541. names: Iterable of names in the working copy
  542. lookup_entry: Function to lookup an entry in the working copy
  543. object_store: Object store to use for retrieving tree contents
  544. tree: SHA1 of the root tree, or None for an empty tree
  545. want_unchanged: Whether unchanged files should be reported
  546. Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode),
  547. (oldsha, newsha)
  548. """
  549. # TODO(jelmer): Support a include_trees option
  550. other_names = set(names)
  551. if tree is not None:
  552. for name, mode, sha in iter_tree_contents(object_store, tree):
  553. try:
  554. (other_sha, other_mode) = lookup_entry(name)
  555. except KeyError:
  556. # Was removed
  557. yield ((name, None), (mode, None), (sha, None))
  558. else:
  559. other_names.remove(name)
  560. if want_unchanged or other_sha != sha or other_mode != mode:
  561. yield ((name, name), (mode, other_mode), (sha, other_sha))
  562. # Mention added files
  563. for name in other_names:
  564. try:
  565. (other_sha, other_mode) = lookup_entry(name)
  566. except KeyError:
  567. pass
  568. else:
  569. yield ((None, name), (None, other_mode), (None, other_sha))
  570. def index_entry_from_stat(
  571. stat_val,
  572. hex_sha: bytes,
  573. mode: Optional[int] = None,
  574. ):
  575. """Create a new index entry from a stat value.
  576. Args:
  577. stat_val: POSIX stat_result instance
  578. hex_sha: Hex sha of the object
  579. """
  580. if mode is None:
  581. mode = cleanup_mode(stat_val.st_mode)
  582. return IndexEntry(
  583. stat_val.st_ctime,
  584. stat_val.st_mtime,
  585. stat_val.st_dev,
  586. stat_val.st_ino,
  587. mode,
  588. stat_val.st_uid,
  589. stat_val.st_gid,
  590. stat_val.st_size,
  591. hex_sha,
  592. )
  593. if sys.platform == "win32":
  594. # On Windows, creating symlinks either requires administrator privileges
  595. # or developer mode. Raise a more helpful error when we're unable to
  596. # create symlinks
  597. # https://github.com/jelmer/dulwich/issues/1005
  598. class WindowsSymlinkPermissionError(PermissionError):
  599. def __init__(self, errno, msg, filename) -> None:
  600. super(PermissionError, self).__init__(
  601. errno,
  602. "Unable to create symlink; "
  603. f"do you have developer mode enabled? {msg}",
  604. filename,
  605. )
  606. def symlink(src, dst, target_is_directory=False, *, dir_fd=None):
  607. try:
  608. return os.symlink(
  609. src, dst, target_is_directory=target_is_directory, dir_fd=dir_fd
  610. )
  611. except PermissionError as e:
  612. raise WindowsSymlinkPermissionError(e.errno, e.strerror, e.filename) from e
  613. else:
  614. symlink = os.symlink
  615. def build_file_from_blob(
  616. blob: Blob,
  617. mode: int,
  618. target_path: bytes,
  619. *,
  620. honor_filemode=True,
  621. tree_encoding="utf-8",
  622. symlink_fn=None,
  623. ):
  624. """Build a file or symlink on disk based on a Git object.
  625. Args:
  626. blob: The git object
  627. mode: File mode
  628. target_path: Path to write to
  629. honor_filemode: An optional flag to honor core.filemode setting in
  630. config file, default is core.filemode=True, change executable bit
  631. symlink: Function to use for creating symlinks
  632. Returns: stat object for the file
  633. """
  634. try:
  635. oldstat = os.lstat(target_path)
  636. except FileNotFoundError:
  637. oldstat = None
  638. contents = blob.as_raw_string()
  639. if stat.S_ISLNK(mode):
  640. if oldstat:
  641. os.unlink(target_path)
  642. if sys.platform == "win32":
  643. # os.readlink on Python3 on Windows requires a unicode string.
  644. contents = contents.decode(tree_encoding) # type: ignore
  645. target_path = target_path.decode(tree_encoding) # type: ignore
  646. (symlink_fn or symlink)(contents, target_path)
  647. else:
  648. if oldstat is not None and oldstat.st_size == len(contents):
  649. with open(target_path, "rb") as f:
  650. if f.read() == contents:
  651. return oldstat
  652. with open(target_path, "wb") as f:
  653. # Write out file
  654. f.write(contents)
  655. if honor_filemode:
  656. os.chmod(target_path, mode)
  657. return os.lstat(target_path)
  658. INVALID_DOTNAMES = (b".git", b".", b"..", b"")
  659. def validate_path_element_default(element: bytes) -> bool:
  660. return element.lower() not in INVALID_DOTNAMES
  661. def validate_path_element_ntfs(element: bytes) -> bool:
  662. stripped = element.rstrip(b". ").lower()
  663. if stripped in INVALID_DOTNAMES:
  664. return False
  665. if stripped == b"git~1":
  666. return False
  667. return True
  668. def validate_path(path: bytes, element_validator=validate_path_element_default) -> bool:
  669. """Default path validator that just checks for .git/."""
  670. parts = path.split(b"/")
  671. for p in parts:
  672. if not element_validator(p):
  673. return False
  674. else:
  675. return True
  676. def build_index_from_tree(
  677. root_path: Union[str, bytes],
  678. index_path: Union[str, bytes],
  679. object_store: ObjectContainer,
  680. tree_id: bytes,
  681. honor_filemode: bool = True,
  682. validate_path_element=validate_path_element_default,
  683. symlink_fn=None,
  684. ) -> None:
  685. """Generate and materialize index from a tree.
  686. Args:
  687. tree_id: Tree to materialize
  688. root_path: Target dir for materialized index files
  689. index_path: Target path for generated index
  690. object_store: Non-empty object store holding tree contents
  691. honor_filemode: An optional flag to honor core.filemode setting in
  692. config file, default is core.filemode=True, change executable bit
  693. validate_path_element: Function to validate path elements to check
  694. out; default just refuses .git and .. directories.
  695. Note: existing index is wiped and contents are not merged
  696. in a working dir. Suitable only for fresh clones.
  697. """
  698. index = Index(index_path, read=False)
  699. if not isinstance(root_path, bytes):
  700. root_path = os.fsencode(root_path)
  701. for entry in iter_tree_contents(object_store, tree_id):
  702. if not validate_path(entry.path, validate_path_element):
  703. continue
  704. full_path = _tree_to_fs_path(root_path, entry.path)
  705. if not os.path.exists(os.path.dirname(full_path)):
  706. os.makedirs(os.path.dirname(full_path))
  707. # TODO(jelmer): Merge new index into working tree
  708. if S_ISGITLINK(entry.mode):
  709. if not os.path.isdir(full_path):
  710. os.mkdir(full_path)
  711. st = os.lstat(full_path)
  712. # TODO(jelmer): record and return submodule paths
  713. else:
  714. obj = object_store[entry.sha]
  715. assert isinstance(obj, Blob)
  716. st = build_file_from_blob(
  717. obj,
  718. entry.mode,
  719. full_path,
  720. honor_filemode=honor_filemode,
  721. symlink_fn=symlink_fn,
  722. )
  723. # Add file to index
  724. if not honor_filemode or S_ISGITLINK(entry.mode):
  725. # we can not use tuple slicing to build a new tuple,
  726. # because on windows that will convert the times to
  727. # longs, which causes errors further along
  728. st_tuple = (
  729. entry.mode,
  730. st.st_ino,
  731. st.st_dev,
  732. st.st_nlink,
  733. st.st_uid,
  734. st.st_gid,
  735. st.st_size,
  736. st.st_atime,
  737. st.st_mtime,
  738. st.st_ctime,
  739. )
  740. st = st.__class__(st_tuple)
  741. # default to a stage 0 index entry (normal)
  742. # when reading from the filesystem
  743. index[entry.path] = index_entry_from_stat(st, entry.sha)
  744. index.write()
  745. def blob_from_path_and_mode(fs_path: bytes, mode: int, tree_encoding="utf-8"):
  746. """Create a blob from a path and a stat object.
  747. Args:
  748. fs_path: Full file system path to file
  749. mode: File mode
  750. Returns: A `Blob` object
  751. """
  752. assert isinstance(fs_path, bytes)
  753. blob = Blob()
  754. if stat.S_ISLNK(mode):
  755. if sys.platform == "win32":
  756. # os.readlink on Python3 on Windows requires a unicode string.
  757. blob.data = os.readlink(os.fsdecode(fs_path)).encode(tree_encoding)
  758. else:
  759. blob.data = os.readlink(fs_path)
  760. else:
  761. with open(fs_path, "rb") as f:
  762. blob.data = f.read()
  763. return blob
  764. def blob_from_path_and_stat(fs_path: bytes, st, tree_encoding="utf-8"):
  765. """Create a blob from a path and a stat object.
  766. Args:
  767. fs_path: Full file system path to file
  768. st: A stat object
  769. Returns: A `Blob` object
  770. """
  771. return blob_from_path_and_mode(fs_path, st.st_mode, tree_encoding)
  772. def read_submodule_head(path: Union[str, bytes]) -> Optional[bytes]:
  773. """Read the head commit of a submodule.
  774. Args:
  775. path: path to the submodule
  776. Returns: HEAD sha, None if not a valid head/repository
  777. """
  778. from .errors import NotGitRepository
  779. from .repo import Repo
  780. # Repo currently expects a "str", so decode if necessary.
  781. # TODO(jelmer): Perhaps move this into Repo() ?
  782. if not isinstance(path, str):
  783. path = os.fsdecode(path)
  784. try:
  785. repo = Repo(path)
  786. except NotGitRepository:
  787. return None
  788. try:
  789. return repo.head()
  790. except KeyError:
  791. return None
  792. def _has_directory_changed(tree_path: bytes, entry) -> bool:
  793. """Check if a directory has changed after getting an error.
  794. When handling an error trying to create a blob from a path, call this
  795. function. It will check if the path is a directory. If it's a directory
  796. and a submodule, check the submodule head to see if it's has changed. If
  797. not, consider the file as changed as Git tracked a file and not a
  798. directory.
  799. Return true if the given path should be considered as changed and False
  800. otherwise or if the path is not a directory.
  801. """
  802. # This is actually a directory
  803. if os.path.exists(os.path.join(tree_path, b".git")):
  804. # Submodule
  805. head = read_submodule_head(tree_path)
  806. if entry.sha != head:
  807. return True
  808. else:
  809. # The file was changed to a directory, so consider it removed.
  810. return True
  811. return False
  812. def get_unstaged_changes(
  813. index: Index, root_path: Union[str, bytes], filter_blob_callback=None
  814. ):
  815. """Walk through an index and check for differences against working tree.
  816. Args:
  817. index: index to check
  818. root_path: path in which to find files
  819. Returns: iterator over paths with unstaged changes
  820. """
  821. # For each entry in the index check the sha1 & ensure not staged
  822. if not isinstance(root_path, bytes):
  823. root_path = os.fsencode(root_path)
  824. for tree_path, entry in index.iteritems():
  825. full_path = _tree_to_fs_path(root_path, tree_path)
  826. if isinstance(entry, ConflictedIndexEntry):
  827. # Conflicted files are always unstaged
  828. yield tree_path
  829. continue
  830. try:
  831. st = os.lstat(full_path)
  832. if stat.S_ISDIR(st.st_mode):
  833. if _has_directory_changed(tree_path, entry):
  834. yield tree_path
  835. continue
  836. if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  837. continue
  838. blob = blob_from_path_and_stat(full_path, st)
  839. if filter_blob_callback is not None:
  840. blob = filter_blob_callback(blob, tree_path)
  841. except FileNotFoundError:
  842. # The file was removed, so we assume that counts as
  843. # different from whatever file used to exist.
  844. yield tree_path
  845. else:
  846. if blob.id != entry.sha:
  847. yield tree_path
  848. os_sep_bytes = os.sep.encode("ascii")
  849. def _tree_to_fs_path(root_path: bytes, tree_path: bytes):
  850. """Convert a git tree path to a file system path.
  851. Args:
  852. root_path: Root filesystem path
  853. tree_path: Git tree path as bytes
  854. Returns: File system path.
  855. """
  856. assert isinstance(tree_path, bytes)
  857. if os_sep_bytes != b"/":
  858. sep_corrected_path = tree_path.replace(b"/", os_sep_bytes)
  859. else:
  860. sep_corrected_path = tree_path
  861. return os.path.join(root_path, sep_corrected_path)
  862. def _fs_to_tree_path(fs_path: Union[str, bytes]) -> bytes:
  863. """Convert a file system path to a git tree path.
  864. Args:
  865. fs_path: File system path.
  866. Returns: Git tree path as bytes
  867. """
  868. if not isinstance(fs_path, bytes):
  869. fs_path_bytes = os.fsencode(fs_path)
  870. else:
  871. fs_path_bytes = fs_path
  872. if os_sep_bytes != b"/":
  873. tree_path = fs_path_bytes.replace(os_sep_bytes, b"/")
  874. else:
  875. tree_path = fs_path_bytes
  876. return tree_path
  877. def index_entry_from_directory(st, path: bytes) -> Optional[IndexEntry]:
  878. if os.path.exists(os.path.join(path, b".git")):
  879. head = read_submodule_head(path)
  880. if head is None:
  881. return None
  882. return index_entry_from_stat(st, head, mode=S_IFGITLINK)
  883. return None
  884. def index_entry_from_path(
  885. path: bytes, object_store: Optional[ObjectContainer] = None
  886. ) -> Optional[IndexEntry]:
  887. """Create an index from a filesystem path.
  888. This returns an index value for files, symlinks
  889. and tree references. for directories and
  890. non-existent files it returns None
  891. Args:
  892. path: Path to create an index entry for
  893. object_store: Optional object store to
  894. save new blobs in
  895. Returns: An index entry; None for directories
  896. """
  897. assert isinstance(path, bytes)
  898. st = os.lstat(path)
  899. if stat.S_ISDIR(st.st_mode):
  900. return index_entry_from_directory(st, path)
  901. if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
  902. blob = blob_from_path_and_stat(path, st)
  903. if object_store is not None:
  904. object_store.add_object(blob)
  905. return index_entry_from_stat(st, blob.id)
  906. return None
  907. def iter_fresh_entries(
  908. paths: Iterable[bytes],
  909. root_path: bytes,
  910. object_store: Optional[ObjectContainer] = None,
  911. ) -> Iterator[tuple[bytes, Optional[IndexEntry]]]:
  912. """Iterate over current versions of index entries on disk.
  913. Args:
  914. paths: Paths to iterate over
  915. root_path: Root path to access from
  916. object_store: Optional store to save new blobs in
  917. Returns: Iterator over path, index_entry
  918. """
  919. for path in paths:
  920. p = _tree_to_fs_path(root_path, path)
  921. try:
  922. entry = index_entry_from_path(p, object_store=object_store)
  923. except (FileNotFoundError, IsADirectoryError):
  924. entry = None
  925. yield path, entry
  926. def iter_fresh_objects(
  927. paths: Iterable[bytes], root_path: bytes, include_deleted=False, object_store=None
  928. ) -> Iterator[tuple[bytes, Optional[bytes], Optional[int]]]:
  929. """Iterate over versions of objects on disk referenced by index.
  930. Args:
  931. root_path: Root path to access from
  932. include_deleted: Include deleted entries with sha and
  933. mode set to None
  934. object_store: Optional object store to report new items to
  935. Returns: Iterator over path, sha, mode
  936. """
  937. for path, entry in iter_fresh_entries(paths, root_path, object_store=object_store):
  938. if entry is None:
  939. if include_deleted:
  940. yield path, None, None
  941. else:
  942. yield path, entry.sha, cleanup_mode(entry.mode)
  943. def refresh_index(index: Index, root_path: bytes) -> None:
  944. """Refresh the contents of an index.
  945. This is the equivalent to running 'git commit -a'.
  946. Args:
  947. index: Index to update
  948. root_path: Root filesystem path
  949. """
  950. for path, entry in iter_fresh_entries(index, root_path):
  951. if entry:
  952. index[path] = entry
  953. class locked_index:
  954. """Lock the index while making modifications.
  955. Works as a context manager.
  956. """
  957. def __init__(self, path: Union[bytes, str]) -> None:
  958. self._path = path
  959. def __enter__(self):
  960. self._file = GitFile(self._path, "wb")
  961. self._index = Index(self._path)
  962. return self._index
  963. def __exit__(self, exc_type, exc_value, traceback):
  964. if exc_type is not None:
  965. self._file.abort()
  966. return
  967. try:
  968. f = SHA1Writer(self._file)
  969. write_index_dict(f, self._index._byname)
  970. except BaseException:
  971. self._file.abort()
  972. else:
  973. f.close()