index.py 34 KB

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