index.py 34 KB

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