index.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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) -> None:
  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. ) -> None:
  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) -> None:
  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) -> bool:
  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) -> None:
  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(
  443. self, entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]
  444. ) -> None:
  445. for key, value in entries.items():
  446. self[key] = value
  447. def paths(self):
  448. yield from self._byname.keys()
  449. def changes_from_tree(
  450. self, object_store, tree: ObjectID, want_unchanged: bool = False
  451. ):
  452. """Find the differences between the contents of this index and a tree.
  453. Args:
  454. object_store: Object store to use for retrieving tree contents
  455. tree: SHA1 of the root tree
  456. want_unchanged: Whether unchanged files should be reported
  457. Returns: Iterator over tuples with (oldpath, newpath), (oldmode,
  458. newmode), (oldsha, newsha)
  459. """
  460. def lookup_entry(path):
  461. entry = self[path]
  462. return entry.sha, cleanup_mode(entry.mode)
  463. yield from changes_from_tree(
  464. self.paths(),
  465. lookup_entry,
  466. object_store,
  467. tree,
  468. want_unchanged=want_unchanged,
  469. )
  470. def commit(self, object_store):
  471. """Create a new tree from an index.
  472. Args:
  473. object_store: Object store to save the tree in
  474. Returns:
  475. Root tree SHA
  476. """
  477. return commit_tree(object_store, self.iterobjects())
  478. def commit_tree(
  479. object_store: ObjectContainer, blobs: Iterable[tuple[bytes, bytes, int]]
  480. ) -> bytes:
  481. """Commit a new tree.
  482. Args:
  483. object_store: Object store to add trees to
  484. blobs: Iterable over blob path, sha, mode entries
  485. Returns:
  486. SHA1 of the created tree.
  487. """
  488. trees: dict[bytes, Any] = {b"": {}}
  489. def add_tree(path):
  490. if path in trees:
  491. return trees[path]
  492. dirname, basename = pathsplit(path)
  493. t = add_tree(dirname)
  494. assert isinstance(basename, bytes)
  495. newtree = {}
  496. t[basename] = newtree
  497. trees[path] = newtree
  498. return newtree
  499. for path, sha, mode in blobs:
  500. tree_path, basename = pathsplit(path)
  501. tree = add_tree(tree_path)
  502. tree[basename] = (mode, sha)
  503. def build_tree(path):
  504. tree = Tree()
  505. for basename, entry in trees[path].items():
  506. if isinstance(entry, dict):
  507. mode = stat.S_IFDIR
  508. sha = build_tree(pathjoin(path, basename))
  509. else:
  510. (mode, sha) = entry
  511. tree.add(basename, mode, sha)
  512. object_store.add_object(tree)
  513. return tree.id
  514. return build_tree(b"")
  515. def commit_index(object_store: ObjectContainer, index: Index) -> bytes:
  516. """Create a new tree from an index.
  517. Args:
  518. object_store: Object store to save the tree in
  519. index: Index file
  520. Note: This function is deprecated, use index.commit() instead.
  521. Returns: Root tree sha.
  522. """
  523. return commit_tree(object_store, index.iterobjects())
  524. def changes_from_tree(
  525. names: Iterable[bytes],
  526. lookup_entry: Callable[[bytes], tuple[bytes, int]],
  527. object_store: ObjectContainer,
  528. tree: Optional[bytes],
  529. want_unchanged=False,
  530. ) -> Iterable[
  531. tuple[
  532. tuple[Optional[bytes], Optional[bytes]],
  533. tuple[Optional[int], Optional[int]],
  534. tuple[Optional[bytes], Optional[bytes]],
  535. ]
  536. ]:
  537. """Find the differences between the contents of a tree and
  538. a working copy.
  539. Args:
  540. names: Iterable of names in the working copy
  541. lookup_entry: Function to lookup an entry in the working copy
  542. object_store: Object store to use for retrieving tree contents
  543. tree: SHA1 of the root tree, or None for an empty tree
  544. want_unchanged: Whether unchanged files should be reported
  545. Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode),
  546. (oldsha, newsha)
  547. """
  548. # TODO(jelmer): Support a include_trees option
  549. other_names = set(names)
  550. if tree is not None:
  551. for name, mode, sha in iter_tree_contents(object_store, tree):
  552. try:
  553. (other_sha, other_mode) = lookup_entry(name)
  554. except KeyError:
  555. # Was removed
  556. yield ((name, None), (mode, None), (sha, None))
  557. else:
  558. other_names.remove(name)
  559. if want_unchanged or other_sha != sha or other_mode != mode:
  560. yield ((name, name), (mode, other_mode), (sha, other_sha))
  561. # Mention added files
  562. for name in other_names:
  563. try:
  564. (other_sha, other_mode) = lookup_entry(name)
  565. except KeyError:
  566. pass
  567. else:
  568. yield ((None, name), (None, other_mode), (None, other_sha))
  569. def index_entry_from_stat(
  570. stat_val,
  571. hex_sha: bytes,
  572. mode: Optional[int] = None,
  573. ):
  574. """Create a new index entry from a stat value.
  575. Args:
  576. stat_val: POSIX stat_result instance
  577. hex_sha: Hex sha of the object
  578. """
  579. if mode is None:
  580. mode = cleanup_mode(stat_val.st_mode)
  581. return IndexEntry(
  582. stat_val.st_ctime,
  583. stat_val.st_mtime,
  584. stat_val.st_dev,
  585. stat_val.st_ino,
  586. mode,
  587. stat_val.st_uid,
  588. stat_val.st_gid,
  589. stat_val.st_size,
  590. hex_sha,
  591. )
  592. if sys.platform == "win32":
  593. # On Windows, creating symlinks either requires administrator privileges
  594. # or developer mode. Raise a more helpful error when we're unable to
  595. # create symlinks
  596. # https://github.com/jelmer/dulwich/issues/1005
  597. class WindowsSymlinkPermissionError(PermissionError):
  598. def __init__(self, errno, msg, filename) -> None:
  599. super(PermissionError, self).__init__(
  600. errno,
  601. "Unable to create symlink; "
  602. f"do you have developer mode enabled? {msg}",
  603. filename,
  604. )
  605. def symlink(src, dst, target_is_directory=False, *, dir_fd=None):
  606. try:
  607. return os.symlink(
  608. src, dst, target_is_directory=target_is_directory, dir_fd=dir_fd
  609. )
  610. except PermissionError as e:
  611. raise WindowsSymlinkPermissionError(e.errno, e.strerror, e.filename) from e
  612. else:
  613. symlink = os.symlink
  614. def build_file_from_blob(
  615. blob: Blob,
  616. mode: int,
  617. target_path: bytes,
  618. *,
  619. honor_filemode=True,
  620. tree_encoding="utf-8",
  621. symlink_fn=None,
  622. ):
  623. """Build a file or symlink on disk based on a Git object.
  624. Args:
  625. blob: The git object
  626. mode: File mode
  627. target_path: Path to write to
  628. honor_filemode: An optional flag to honor core.filemode setting in
  629. config file, default is core.filemode=True, change executable bit
  630. symlink: Function to use for creating symlinks
  631. Returns: stat object for the file
  632. """
  633. try:
  634. oldstat = os.lstat(target_path)
  635. except FileNotFoundError:
  636. oldstat = None
  637. contents = blob.as_raw_string()
  638. if stat.S_ISLNK(mode):
  639. if oldstat:
  640. os.unlink(target_path)
  641. if sys.platform == "win32":
  642. # os.readlink on Python3 on Windows requires a unicode string.
  643. contents = contents.decode(tree_encoding) # type: ignore
  644. target_path = target_path.decode(tree_encoding) # type: ignore
  645. (symlink_fn or symlink)(contents, target_path)
  646. else:
  647. if oldstat is not None and oldstat.st_size == len(contents):
  648. with open(target_path, "rb") as f:
  649. if f.read() == contents:
  650. return oldstat
  651. with open(target_path, "wb") as f:
  652. # Write out file
  653. f.write(contents)
  654. if honor_filemode:
  655. os.chmod(target_path, mode)
  656. return os.lstat(target_path)
  657. INVALID_DOTNAMES = (b".git", b".", b"..", b"")
  658. def validate_path_element_default(element: bytes) -> bool:
  659. return element.lower() not in INVALID_DOTNAMES
  660. def validate_path_element_ntfs(element: bytes) -> bool:
  661. stripped = element.rstrip(b". ").lower()
  662. if stripped in INVALID_DOTNAMES:
  663. return False
  664. if stripped == b"git~1":
  665. return False
  666. return True
  667. def validate_path(path: bytes, element_validator=validate_path_element_default) -> bool:
  668. """Default path validator that just checks for .git/."""
  669. parts = path.split(b"/")
  670. for p in parts:
  671. if not element_validator(p):
  672. return False
  673. else:
  674. return True
  675. def build_index_from_tree(
  676. root_path: Union[str, bytes],
  677. index_path: Union[str, bytes],
  678. object_store: ObjectContainer,
  679. tree_id: bytes,
  680. honor_filemode: bool = True,
  681. validate_path_element=validate_path_element_default,
  682. symlink_fn=None,
  683. ) -> None:
  684. """Generate and materialize index from a tree.
  685. Args:
  686. tree_id: Tree to materialize
  687. root_path: Target dir for materialized index files
  688. index_path: Target path for generated index
  689. object_store: Non-empty object store holding tree contents
  690. honor_filemode: An optional flag to honor core.filemode setting in
  691. config file, default is core.filemode=True, change executable bit
  692. validate_path_element: Function to validate path elements to check
  693. out; default just refuses .git and .. directories.
  694. Note: existing index is wiped and contents are not merged
  695. in a working dir. Suitable only for fresh clones.
  696. """
  697. index = Index(index_path, read=False)
  698. if not isinstance(root_path, bytes):
  699. root_path = os.fsencode(root_path)
  700. for entry in iter_tree_contents(object_store, tree_id):
  701. if not validate_path(entry.path, validate_path_element):
  702. continue
  703. full_path = _tree_to_fs_path(root_path, entry.path)
  704. if not os.path.exists(os.path.dirname(full_path)):
  705. os.makedirs(os.path.dirname(full_path))
  706. # TODO(jelmer): Merge new index into working tree
  707. if S_ISGITLINK(entry.mode):
  708. if not os.path.isdir(full_path):
  709. os.mkdir(full_path)
  710. st = os.lstat(full_path)
  711. # TODO(jelmer): record and return submodule paths
  712. else:
  713. obj = object_store[entry.sha]
  714. assert isinstance(obj, Blob)
  715. st = build_file_from_blob(
  716. obj,
  717. entry.mode,
  718. full_path,
  719. honor_filemode=honor_filemode,
  720. symlink_fn=symlink_fn,
  721. )
  722. # Add file to index
  723. if not honor_filemode or S_ISGITLINK(entry.mode):
  724. # we can not use tuple slicing to build a new tuple,
  725. # because on windows that will convert the times to
  726. # longs, which causes errors further along
  727. st_tuple = (
  728. entry.mode,
  729. st.st_ino,
  730. st.st_dev,
  731. st.st_nlink,
  732. st.st_uid,
  733. st.st_gid,
  734. st.st_size,
  735. st.st_atime,
  736. st.st_mtime,
  737. st.st_ctime,
  738. )
  739. st = st.__class__(st_tuple)
  740. # default to a stage 0 index entry (normal)
  741. # when reading from the filesystem
  742. index[entry.path] = index_entry_from_stat(st, entry.sha)
  743. index.write()
  744. def blob_from_path_and_mode(fs_path: bytes, mode: int, tree_encoding="utf-8"):
  745. """Create a blob from a path and a stat object.
  746. Args:
  747. fs_path: Full file system path to file
  748. mode: File mode
  749. Returns: A `Blob` object
  750. """
  751. assert isinstance(fs_path, bytes)
  752. blob = Blob()
  753. if stat.S_ISLNK(mode):
  754. if sys.platform == "win32":
  755. # os.readlink on Python3 on Windows requires a unicode string.
  756. blob.data = os.readlink(os.fsdecode(fs_path)).encode(tree_encoding)
  757. else:
  758. blob.data = os.readlink(fs_path)
  759. else:
  760. with open(fs_path, "rb") as f:
  761. blob.data = f.read()
  762. return blob
  763. def blob_from_path_and_stat(fs_path: bytes, st, tree_encoding="utf-8"):
  764. """Create a blob from a path and a stat object.
  765. Args:
  766. fs_path: Full file system path to file
  767. st: A stat object
  768. Returns: A `Blob` object
  769. """
  770. return blob_from_path_and_mode(fs_path, st.st_mode, tree_encoding)
  771. def read_submodule_head(path: Union[str, bytes]) -> Optional[bytes]:
  772. """Read the head commit of a submodule.
  773. Args:
  774. path: path to the submodule
  775. Returns: HEAD sha, None if not a valid head/repository
  776. """
  777. from .errors import NotGitRepository
  778. from .repo import Repo
  779. # Repo currently expects a "str", so decode if necessary.
  780. # TODO(jelmer): Perhaps move this into Repo() ?
  781. if not isinstance(path, str):
  782. path = os.fsdecode(path)
  783. try:
  784. repo = Repo(path)
  785. except NotGitRepository:
  786. return None
  787. try:
  788. return repo.head()
  789. except KeyError:
  790. return None
  791. def _has_directory_changed(tree_path: bytes, entry) -> bool:
  792. """Check if a directory has changed after getting an error.
  793. When handling an error trying to create a blob from a path, call this
  794. function. It will check if the path is a directory. If it's a directory
  795. and a submodule, check the submodule head to see if it's has changed. If
  796. not, consider the file as changed as Git tracked a file and not a
  797. directory.
  798. Return true if the given path should be considered as changed and False
  799. otherwise or if the path is not a directory.
  800. """
  801. # This is actually a directory
  802. if os.path.exists(os.path.join(tree_path, b".git")):
  803. # Submodule
  804. head = read_submodule_head(tree_path)
  805. if entry.sha != head:
  806. return True
  807. else:
  808. # The file was changed to a directory, so consider it removed.
  809. return True
  810. return False
  811. def get_unstaged_changes(
  812. index: Index, root_path: Union[str, bytes], filter_blob_callback=None
  813. ):
  814. """Walk through an index and check for differences against working tree.
  815. Args:
  816. index: index to check
  817. root_path: path in which to find files
  818. Returns: iterator over paths with unstaged changes
  819. """
  820. # For each entry in the index check the sha1 & ensure not staged
  821. if not isinstance(root_path, bytes):
  822. root_path = os.fsencode(root_path)
  823. for tree_path, entry in index.iteritems():
  824. full_path = _tree_to_fs_path(root_path, tree_path)
  825. if isinstance(entry, ConflictedIndexEntry):
  826. # Conflicted files are always unstaged
  827. yield tree_path
  828. continue
  829. try:
  830. st = os.lstat(full_path)
  831. if stat.S_ISDIR(st.st_mode):
  832. if _has_directory_changed(tree_path, entry):
  833. yield tree_path
  834. continue
  835. if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  836. continue
  837. blob = blob_from_path_and_stat(full_path, st)
  838. if filter_blob_callback is not None:
  839. blob = filter_blob_callback(blob, tree_path)
  840. except FileNotFoundError:
  841. # The file was removed, so we assume that counts as
  842. # different from whatever file used to exist.
  843. yield tree_path
  844. else:
  845. if blob.id != entry.sha:
  846. yield tree_path
  847. os_sep_bytes = os.sep.encode("ascii")
  848. def _tree_to_fs_path(root_path: bytes, tree_path: bytes):
  849. """Convert a git tree path to a file system path.
  850. Args:
  851. root_path: Root filesystem path
  852. tree_path: Git tree path as bytes
  853. Returns: File system path.
  854. """
  855. assert isinstance(tree_path, bytes)
  856. if os_sep_bytes != b"/":
  857. sep_corrected_path = tree_path.replace(b"/", os_sep_bytes)
  858. else:
  859. sep_corrected_path = tree_path
  860. return os.path.join(root_path, sep_corrected_path)
  861. def _fs_to_tree_path(fs_path: Union[str, bytes]) -> bytes:
  862. """Convert a file system path to a git tree path.
  863. Args:
  864. fs_path: File system path.
  865. Returns: Git tree path as bytes
  866. """
  867. if not isinstance(fs_path, bytes):
  868. fs_path_bytes = os.fsencode(fs_path)
  869. else:
  870. fs_path_bytes = fs_path
  871. if os_sep_bytes != b"/":
  872. tree_path = fs_path_bytes.replace(os_sep_bytes, b"/")
  873. else:
  874. tree_path = fs_path_bytes
  875. return tree_path
  876. def index_entry_from_directory(st, path: bytes) -> Optional[IndexEntry]:
  877. if os.path.exists(os.path.join(path, b".git")):
  878. head = read_submodule_head(path)
  879. if head is None:
  880. return None
  881. return index_entry_from_stat(st, head, mode=S_IFGITLINK)
  882. return None
  883. def index_entry_from_path(
  884. path: bytes, object_store: Optional[ObjectContainer] = None
  885. ) -> Optional[IndexEntry]:
  886. """Create an index from a filesystem path.
  887. This returns an index value for files, symlinks
  888. and tree references. for directories and
  889. non-existent files it returns None
  890. Args:
  891. path: Path to create an index entry for
  892. object_store: Optional object store to
  893. save new blobs in
  894. Returns: An index entry; None for directories
  895. """
  896. assert isinstance(path, bytes)
  897. st = os.lstat(path)
  898. if stat.S_ISDIR(st.st_mode):
  899. return index_entry_from_directory(st, path)
  900. if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
  901. blob = blob_from_path_and_stat(path, st)
  902. if object_store is not None:
  903. object_store.add_object(blob)
  904. return index_entry_from_stat(st, blob.id)
  905. return None
  906. def iter_fresh_entries(
  907. paths: Iterable[bytes],
  908. root_path: bytes,
  909. object_store: Optional[ObjectContainer] = None,
  910. ) -> Iterator[tuple[bytes, Optional[IndexEntry]]]:
  911. """Iterate over current versions of index entries on disk.
  912. Args:
  913. paths: Paths to iterate over
  914. root_path: Root path to access from
  915. object_store: Optional store to save new blobs in
  916. Returns: Iterator over path, index_entry
  917. """
  918. for path in paths:
  919. p = _tree_to_fs_path(root_path, path)
  920. try:
  921. entry = index_entry_from_path(p, object_store=object_store)
  922. except (FileNotFoundError, IsADirectoryError):
  923. entry = None
  924. yield path, entry
  925. def iter_fresh_objects(
  926. paths: Iterable[bytes], root_path: bytes, include_deleted=False, object_store=None
  927. ) -> Iterator[tuple[bytes, Optional[bytes], Optional[int]]]:
  928. """Iterate over versions of objects on disk referenced by index.
  929. Args:
  930. root_path: Root path to access from
  931. include_deleted: Include deleted entries with sha and
  932. mode set to None
  933. object_store: Optional object store to report new items to
  934. Returns: Iterator over path, sha, mode
  935. """
  936. for path, entry in iter_fresh_entries(paths, root_path, object_store=object_store):
  937. if entry is None:
  938. if include_deleted:
  939. yield path, None, None
  940. else:
  941. yield path, entry.sha, cleanup_mode(entry.mode)
  942. def refresh_index(index: Index, root_path: bytes) -> None:
  943. """Refresh the contents of an index.
  944. This is the equivalent to running 'git commit -a'.
  945. Args:
  946. index: Index to update
  947. root_path: Root filesystem path
  948. """
  949. for path, entry in iter_fresh_entries(index, root_path):
  950. if entry:
  951. index[path] = entry
  952. class locked_index:
  953. """Lock the index while making modifications.
  954. Works as a context manager.
  955. """
  956. def __init__(self, path: Union[bytes, str]) -> None:
  957. self._path = path
  958. def __enter__(self):
  959. self._file = GitFile(self._path, "wb")
  960. self._index = Index(self._path)
  961. return self._index
  962. def __exit__(self, exc_type, exc_value, traceback):
  963. if exc_type is not None:
  964. self._file.abort()
  965. return
  966. try:
  967. f = SHA1Writer(self._file)
  968. write_index_dict(f, self._index._byname)
  969. except BaseException:
  970. self._file.abort()
  971. else:
  972. f.close()