base.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  2. #
  3. # This module is part of GitPython and is released under the
  4. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  5. """Module containing :class:`IndexFile`, an Index implementation facilitating all kinds
  6. of index manipulations such as querying and merging."""
  7. __all__ = ["IndexFile", "CheckoutError", "StageType"]
  8. import contextlib
  9. import datetime
  10. import glob
  11. from io import BytesIO
  12. import os
  13. import os.path as osp
  14. from stat import S_ISLNK
  15. import subprocess
  16. import sys
  17. import tempfile
  18. from gitdb.base import IStream
  19. from gitdb.db import MemoryDB
  20. from git.compat import defenc, force_bytes
  21. import git.diff as git_diff
  22. from git.exc import CheckoutError, GitCommandError, GitError, InvalidGitRepositoryError
  23. from git.objects import Blob, Commit, Object, Submodule, Tree
  24. from git.objects.util import Serializable
  25. from git.util import (
  26. Actor,
  27. LazyMixin,
  28. LockedFD,
  29. join_path_native,
  30. file_contents_ro,
  31. to_native_path_linux,
  32. unbare_repo,
  33. to_bin_sha,
  34. )
  35. from .fun import (
  36. S_IFGITLINK,
  37. aggressive_tree_merge,
  38. entry_key,
  39. read_cache,
  40. run_commit_hook,
  41. stat_mode_to_index_mode,
  42. write_cache,
  43. write_tree_from_cache,
  44. )
  45. from .typ import BaseIndexEntry, IndexEntry, StageType
  46. from .util import TemporaryFileSwap, post_clear_cache, default_index, git_working_dir
  47. # typing -----------------------------------------------------------------------------
  48. from typing import (
  49. Any,
  50. BinaryIO,
  51. Callable,
  52. Dict,
  53. Generator,
  54. IO,
  55. Iterable,
  56. Iterator,
  57. List,
  58. NoReturn,
  59. Sequence,
  60. TYPE_CHECKING,
  61. Tuple,
  62. Union,
  63. )
  64. from git.types import Literal, PathLike
  65. if TYPE_CHECKING:
  66. from subprocess import Popen
  67. from git.refs.reference import Reference
  68. from git.repo import Repo
  69. Treeish = Union[Tree, Commit, str, bytes]
  70. # ------------------------------------------------------------------------------------
  71. @contextlib.contextmanager
  72. def _named_temporary_file_for_subprocess(directory: PathLike) -> Generator[str, None, None]:
  73. """Create a named temporary file git subprocesses can open, deleting it afterward.
  74. :param directory:
  75. The directory in which the file is created.
  76. :return:
  77. A context manager object that creates the file and provides its name on entry,
  78. and deletes it on exit.
  79. """
  80. if sys.platform == "win32":
  81. fd, name = tempfile.mkstemp(dir=directory)
  82. os.close(fd)
  83. try:
  84. yield name
  85. finally:
  86. os.remove(name)
  87. else:
  88. with tempfile.NamedTemporaryFile(dir=directory) as ctx:
  89. yield ctx.name
  90. class IndexFile(LazyMixin, git_diff.Diffable, Serializable):
  91. """An Index that can be manipulated using a native implementation in order to save
  92. git command function calls wherever possible.
  93. This provides custom merging facilities allowing to merge without actually changing
  94. your index or your working tree. This way you can perform your own test merges based
  95. on the index only without having to deal with the working copy. This is useful in
  96. case of partial working trees.
  97. Entries:
  98. The index contains an entries dict whose keys are tuples of type
  99. :class:`~git.index.typ.IndexEntry` to facilitate access.
  100. You may read the entries dict or manipulate it using IndexEntry instance, i.e.::
  101. index.entries[index.entry_key(index_entry_instance)] = index_entry_instance
  102. Make sure you use :meth:`index.write() <write>` once you are done manipulating the
  103. index directly before operating on it using the git command.
  104. """
  105. __slots__ = ("repo", "version", "entries", "_extension_data", "_file_path")
  106. _VERSION = 2
  107. """The latest version we support."""
  108. S_IFGITLINK = S_IFGITLINK
  109. """Flags for a submodule."""
  110. def __init__(self, repo: "Repo", file_path: Union[PathLike, None] = None) -> None:
  111. """Initialize this Index instance, optionally from the given `file_path`.
  112. If no `file_path` is given, we will be created from the current index file.
  113. If a stream is not given, the stream will be initialized from the current
  114. repository's index on demand.
  115. """
  116. self.repo = repo
  117. self.version = self._VERSION
  118. self._extension_data = b""
  119. self._file_path: PathLike = file_path or self._index_path()
  120. def _set_cache_(self, attr: str) -> None:
  121. if attr == "entries":
  122. try:
  123. fd = os.open(self._file_path, os.O_RDONLY)
  124. except OSError:
  125. # In new repositories, there may be no index, which means we are empty.
  126. self.entries: Dict[Tuple[PathLike, StageType], IndexEntry] = {}
  127. return
  128. # END exception handling
  129. try:
  130. stream = file_contents_ro(fd, stream=True, allow_mmap=True)
  131. finally:
  132. os.close(fd)
  133. self._deserialize(stream)
  134. else:
  135. super()._set_cache_(attr)
  136. def _index_path(self) -> PathLike:
  137. if self.repo.git_dir:
  138. return join_path_native(self.repo.git_dir, "index")
  139. else:
  140. raise GitCommandError("No git directory given to join index path")
  141. @property
  142. def path(self) -> PathLike:
  143. """:return: Path to the index file we are representing"""
  144. return self._file_path
  145. def _delete_entries_cache(self) -> None:
  146. """Safely clear the entries cache so it can be recreated."""
  147. try:
  148. del self.entries
  149. except AttributeError:
  150. # It failed in Python 2.6.5 with AttributeError.
  151. # FIXME: Look into whether we can just remove this except clause now.
  152. pass
  153. # END exception handling
  154. # { Serializable Interface
  155. def _deserialize(self, stream: IO) -> "IndexFile":
  156. """Initialize this instance with index values read from the given stream."""
  157. self.version, self.entries, self._extension_data, _conten_sha = read_cache(stream)
  158. return self
  159. def _entries_sorted(self) -> List[IndexEntry]:
  160. """:return: List of entries, in a sorted fashion, first by path, then by stage"""
  161. return sorted(self.entries.values(), key=lambda e: (e.path, e.stage))
  162. def _serialize(self, stream: IO, ignore_extension_data: bool = False) -> "IndexFile":
  163. entries = self._entries_sorted()
  164. extension_data = self._extension_data # type: Union[None, bytes]
  165. if ignore_extension_data:
  166. extension_data = None
  167. write_cache(entries, stream, extension_data)
  168. return self
  169. # } END serializable interface
  170. def write(
  171. self,
  172. file_path: Union[None, PathLike] = None,
  173. ignore_extension_data: bool = False,
  174. ) -> None:
  175. """Write the current state to our file path or to the given one.
  176. :param file_path:
  177. If ``None``, we will write to our stored file path from which we have been
  178. initialized. Otherwise we write to the given file path. Please note that
  179. this will change the `file_path` of this index to the one you gave.
  180. :param ignore_extension_data:
  181. If ``True``, the TREE type extension data read in the index will not be
  182. written to disk. NOTE that no extension data is actually written. Use this
  183. if you have altered the index and would like to use
  184. :manpage:`git-write-tree(1)` afterwards to create a tree representing your
  185. written changes. If this data is present in the written index,
  186. :manpage:`git-write-tree(1)` will instead write the stored/cached tree.
  187. Alternatively, use :meth:`write_tree` to handle this case automatically.
  188. """
  189. # Make sure we have our entries read before getting a write lock.
  190. # Otherwise it would be done when streaming.
  191. # This can happen if one doesn't change the index, but writes it right away.
  192. self.entries # noqa: B018
  193. lfd = LockedFD(file_path or self._file_path)
  194. stream = lfd.open(write=True, stream=True)
  195. try:
  196. self._serialize(stream, ignore_extension_data)
  197. except BaseException:
  198. lfd.rollback()
  199. raise
  200. lfd.commit()
  201. # Make sure we represent what we have written.
  202. if file_path is not None:
  203. self._file_path = file_path
  204. @post_clear_cache
  205. @default_index
  206. def merge_tree(self, rhs: Treeish, base: Union[None, Treeish] = None) -> "IndexFile":
  207. """Merge the given `rhs` treeish into the current index, possibly taking
  208. a common base treeish into account.
  209. As opposed to the :func:`from_tree` method, this allows you to use an already
  210. existing tree as the left side of the merge.
  211. :param rhs:
  212. Treeish reference pointing to the 'other' side of the merge.
  213. :param base:
  214. Optional treeish reference pointing to the common base of `rhs` and this
  215. index which equals lhs.
  216. :return:
  217. self (containing the merge and possibly unmerged entries in case of
  218. conflicts)
  219. :raise git.exc.GitCommandError:
  220. If there is a merge conflict. The error will be raised at the first
  221. conflicting path. If you want to have proper merge resolution to be done by
  222. yourself, you have to commit the changed index (or make a valid tree from
  223. it) and retry with a three-way :meth:`index.from_tree <from_tree>` call.
  224. """
  225. # -i : ignore working tree status
  226. # --aggressive : handle more merge cases
  227. # -m : do an actual merge
  228. args: List[Union[Treeish, str]] = ["--aggressive", "-i", "-m"]
  229. if base is not None:
  230. args.append(base)
  231. args.append(rhs)
  232. self.repo.git.read_tree(args)
  233. return self
  234. @classmethod
  235. def new(cls, repo: "Repo", *tree_sha: Union[str, Tree]) -> "IndexFile":
  236. """Merge the given treeish revisions into a new index which is returned.
  237. This method behaves like ``git-read-tree --aggressive`` when doing the merge.
  238. :param repo:
  239. The repository treeish are located in.
  240. :param tree_sha:
  241. 20 byte or 40 byte tree sha or tree objects.
  242. :return:
  243. New :class:`IndexFile` instance. Its path will be undefined.
  244. If you intend to write such a merged Index, supply an alternate
  245. ``file_path`` to its :meth:`write` method.
  246. """
  247. tree_sha_bytes: List[bytes] = [to_bin_sha(str(t)) for t in tree_sha]
  248. base_entries = aggressive_tree_merge(repo.odb, tree_sha_bytes)
  249. inst = cls(repo)
  250. # Convert to entries dict.
  251. entries: Dict[Tuple[PathLike, int], IndexEntry] = dict(
  252. zip(
  253. ((e.path, e.stage) for e in base_entries),
  254. (IndexEntry.from_base(e) for e in base_entries),
  255. )
  256. )
  257. inst.entries = entries
  258. return inst
  259. @classmethod
  260. def from_tree(cls, repo: "Repo", *treeish: Treeish, **kwargs: Any) -> "IndexFile":
  261. R"""Merge the given treeish revisions into a new index which is returned.
  262. The original index will remain unaltered.
  263. :param repo:
  264. The repository treeish are located in.
  265. :param treeish:
  266. One, two or three :class:`~git.objects.tree.Tree` objects,
  267. :class:`~git.objects.commit.Commit`\s or 40 byte hexshas.
  268. The result changes according to the amount of trees:
  269. 1. If 1 Tree is given, it will just be read into a new index.
  270. 2. If 2 Trees are given, they will be merged into a new index using a two
  271. way merge algorithm. Tree 1 is the 'current' tree, tree 2 is the 'other'
  272. one. It behaves like a fast-forward.
  273. 3. If 3 Trees are given, a 3-way merge will be performed with the first tree
  274. being the common ancestor of tree 2 and tree 3. Tree 2 is the 'current'
  275. tree, tree 3 is the 'other' one.
  276. :param kwargs:
  277. Additional arguments passed to :manpage:`git-read-tree(1)`.
  278. :return:
  279. New :class:`IndexFile` instance. It will point to a temporary index location
  280. which does not exist anymore. If you intend to write such a merged Index,
  281. supply an alternate ``file_path`` to its :meth:`write` method.
  282. :note:
  283. In the three-way merge case, ``--aggressive`` will be specified to
  284. automatically resolve more cases in a commonly correct manner. Specify
  285. ``trivial=True`` as a keyword argument to override that.
  286. As the underlying :manpage:`git-read-tree(1)` command takes into account the
  287. current index, it will be temporarily moved out of the way to prevent any
  288. unexpected interference.
  289. """
  290. if len(treeish) == 0 or len(treeish) > 3:
  291. raise ValueError("Please specify between 1 and 3 treeish, got %i" % len(treeish))
  292. arg_list: List[Union[Treeish, str]] = []
  293. # Ignore that the working tree and index possibly are out of date.
  294. if len(treeish) > 1:
  295. # Drop unmerged entries when reading our index and merging.
  296. arg_list.append("--reset")
  297. # Handle non-trivial cases the way a real merge does.
  298. arg_list.append("--aggressive")
  299. # END merge handling
  300. # Create the temporary file in the .git directory to be sure renaming
  301. # works - /tmp/ directories could be on another device.
  302. with _named_temporary_file_for_subprocess(repo.git_dir) as tmp_index:
  303. arg_list.append("--index-output=%s" % tmp_index)
  304. arg_list.extend(treeish)
  305. # Move the current index out of the way - otherwise the merge may fail as it
  306. # considers existing entries. Moving it essentially clears the index.
  307. # Unfortunately there is no 'soft' way to do it.
  308. # The TemporaryFileSwap ensures the original file gets put back.
  309. with TemporaryFileSwap(join_path_native(repo.git_dir, "index")):
  310. repo.git.read_tree(*arg_list, **kwargs)
  311. index = cls(repo, tmp_index)
  312. index.entries # noqa: B018 # Force it to read the file as we will delete the temp-file.
  313. return index
  314. # END index merge handling
  315. # UTILITIES
  316. @unbare_repo
  317. def _iter_expand_paths(self: "IndexFile", paths: Sequence[PathLike]) -> Iterator[PathLike]:
  318. """Expand the directories in list of paths to the corresponding paths
  319. accordingly.
  320. :note:
  321. git will add items multiple times even if a glob overlapped with manually
  322. specified paths or if paths where specified multiple times - we respect that
  323. and do not prune.
  324. """
  325. def raise_exc(e: Exception) -> NoReturn:
  326. raise e
  327. r = str(self.repo.working_tree_dir)
  328. rs = r + os.sep
  329. for path in paths:
  330. abs_path = os.fspath(path)
  331. if not osp.isabs(abs_path):
  332. abs_path = osp.join(r, path)
  333. # END make absolute path
  334. try:
  335. st = os.lstat(abs_path) # Handles non-symlinks as well.
  336. except OSError:
  337. # The lstat call may fail as the path may contain globs as well.
  338. pass
  339. else:
  340. if S_ISLNK(st.st_mode):
  341. yield abs_path.replace(rs, "")
  342. continue
  343. # END check symlink
  344. # If the path is not already pointing to an existing file, resolve globs if possible.
  345. if not os.path.exists(abs_path) and ("?" in abs_path or "*" in abs_path or "[" in abs_path):
  346. resolved_paths = glob.glob(abs_path)
  347. # not abs_path in resolved_paths:
  348. # A glob() resolving to the same path we are feeding it with is a
  349. # glob() that failed to resolve. If we continued calling ourselves
  350. # we'd endlessly recurse. If the condition below evaluates to true
  351. # then we are likely dealing with a file whose name contains wildcard
  352. # characters.
  353. if abs_path not in resolved_paths:
  354. for f in self._iter_expand_paths(glob.glob(abs_path)):
  355. yield str(f).replace(rs, "")
  356. continue
  357. # END glob handling
  358. try:
  359. for root, _dirs, files in os.walk(abs_path, onerror=raise_exc):
  360. for rela_file in files:
  361. # Add relative paths only.
  362. yield osp.join(root.replace(rs, ""), rela_file)
  363. # END for each file in subdir
  364. # END for each subdirectory
  365. except OSError:
  366. # It was a file or something that could not be iterated.
  367. yield abs_path.replace(rs, "")
  368. # END path exception handling
  369. # END for each path
  370. def _write_path_to_stdin(
  371. self,
  372. proc: "Popen",
  373. filepath: PathLike,
  374. item: PathLike,
  375. fmakeexc: Callable[..., GitError],
  376. fprogress: Callable[[PathLike, bool, PathLike], None],
  377. read_from_stdout: bool = True,
  378. ) -> Union[None, str]:
  379. """Write path to ``proc.stdin`` and make sure it processes the item, including
  380. progress.
  381. :return:
  382. stdout string
  383. :param read_from_stdout:
  384. If ``True``, ``proc.stdout`` will be read after the item was sent to stdin.
  385. In that case, it will return ``None``.
  386. :note:
  387. There is a bug in :manpage:`git-update-index(1)` that prevents it from
  388. sending reports just in time. This is why we have a version that tries to
  389. read stdout and one which doesn't. In fact, the stdout is not important as
  390. the piped-in files are processed anyway and just in time.
  391. :note:
  392. Newlines are essential here, git's behaviour is somewhat inconsistent on
  393. this depending on the version, hence we try our best to deal with newlines
  394. carefully. Usually the last newline will not be sent, instead we will close
  395. stdin to break the pipe.
  396. """
  397. fprogress(filepath, False, item)
  398. rval: Union[None, str] = None
  399. if proc.stdin is not None:
  400. try:
  401. proc.stdin.write(("%s\n" % filepath).encode(defenc))
  402. except IOError as e:
  403. # Pipe broke, usually because some error happened.
  404. raise fmakeexc() from e
  405. # END write exception handling
  406. proc.stdin.flush()
  407. if read_from_stdout and proc.stdout is not None:
  408. rval = proc.stdout.readline().strip()
  409. fprogress(filepath, True, item)
  410. return rval
  411. def iter_blobs(
  412. self, predicate: Callable[[Tuple[StageType, Blob]], bool] = lambda t: True
  413. ) -> Iterator[Tuple[StageType, Blob]]:
  414. """
  415. :return:
  416. Iterator yielding tuples of :class:`~git.objects.blob.Blob` objects and
  417. stages, tuple(stage, Blob).
  418. :param predicate:
  419. Function(t) returning ``True`` if tuple(stage, Blob) should be yielded by
  420. the iterator. A default filter, the :class:`~git.index.typ.BlobFilter`, allows you
  421. to yield blobs only if they match a given list of paths.
  422. """
  423. for entry in self.entries.values():
  424. blob = entry.to_blob(self.repo)
  425. blob.size = entry.size
  426. output = (entry.stage, blob)
  427. if predicate(output):
  428. yield output
  429. # END for each entry
  430. def unmerged_blobs(self) -> Dict[PathLike, List[Tuple[StageType, Blob]]]:
  431. """
  432. :return:
  433. Dict(path : list(tuple(stage, Blob, ...))), being a dictionary associating a
  434. path in the index with a list containing sorted stage/blob pairs.
  435. :note:
  436. Blobs that have been removed in one side simply do not exist in the given
  437. stage. That is, a file removed on the 'other' branch whose entries are at
  438. stage 3 will not have a stage 3 entry.
  439. """
  440. def is_unmerged_blob(t: Tuple[StageType, Blob]) -> bool:
  441. return t[0] != 0
  442. path_map: Dict[PathLike, List[Tuple[StageType, Blob]]] = {}
  443. for stage, blob in self.iter_blobs(is_unmerged_blob):
  444. path_map.setdefault(blob.path, []).append((stage, blob))
  445. # END for each unmerged blob
  446. for line in path_map.values():
  447. line.sort()
  448. return path_map
  449. @classmethod
  450. def entry_key(cls, *entry: Union[BaseIndexEntry, PathLike, StageType]) -> Tuple[PathLike, StageType]:
  451. return entry_key(*entry)
  452. def resolve_blobs(self, iter_blobs: Iterator[Blob]) -> "IndexFile":
  453. """Resolve the blobs given in blob iterator.
  454. This will effectively remove the index entries of the respective path at all
  455. non-null stages and add the given blob as new stage null blob.
  456. For each path there may only be one blob, otherwise a :exc:`ValueError` will be
  457. raised claiming the path is already at stage 0.
  458. :raise ValueError:
  459. If one of the blobs already existed at stage 0.
  460. :return:
  461. self
  462. :note:
  463. You will have to write the index manually once you are done, i.e.
  464. ``index.resolve_blobs(blobs).write()``.
  465. """
  466. for blob in iter_blobs:
  467. stage_null_key = (blob.path, 0)
  468. if stage_null_key in self.entries:
  469. raise ValueError("Path %r already exists at stage 0" % str(blob.path))
  470. # END assert blob is not stage 0 already
  471. # Delete all possible stages.
  472. for stage in (1, 2, 3):
  473. try:
  474. del self.entries[(blob.path, stage)]
  475. except KeyError:
  476. pass
  477. # END ignore key errors
  478. # END for each possible stage
  479. self.entries[stage_null_key] = IndexEntry.from_blob(blob)
  480. # END for each blob
  481. return self
  482. def update(self) -> "IndexFile":
  483. """Reread the contents of our index file, discarding all cached information
  484. we might have.
  485. :note:
  486. This is a possibly dangerous operations as it will discard your changes to
  487. :attr:`index.entries <entries>`.
  488. :return:
  489. self
  490. """
  491. self._delete_entries_cache()
  492. # Allows to lazily reread on demand.
  493. return self
  494. def write_tree(self) -> Tree:
  495. """Write this index to a corresponding :class:`~git.objects.tree.Tree` object
  496. into the repository's object database and return it.
  497. :return:
  498. :class:`~git.objects.tree.Tree` object representing this index.
  499. :note:
  500. The tree will be written even if one or more objects the tree refers to does
  501. not yet exist in the object database. This could happen if you added entries
  502. to the index directly.
  503. :raise ValueError:
  504. If there are no entries in the cache.
  505. :raise git.exc.UnmergedEntriesError:
  506. """
  507. # We obtain no lock as we just flush our contents to disk as tree.
  508. # If we are a new index, the entries access will load our data accordingly.
  509. mdb = MemoryDB()
  510. entries = self._entries_sorted()
  511. binsha, tree_items = write_tree_from_cache(entries, mdb, slice(0, len(entries)))
  512. # Copy changed trees only.
  513. mdb.stream_copy(mdb.sha_iter(), self.repo.odb)
  514. # Note: Additional deserialization could be saved if write_tree_from_cache would
  515. # return sorted tree entries.
  516. root_tree = Tree(self.repo, binsha, path="")
  517. root_tree._cache = tree_items
  518. return root_tree
  519. def _process_diff_args(
  520. self,
  521. args: List[Union[PathLike, "git_diff.Diffable"]],
  522. ) -> List[Union[PathLike, "git_diff.Diffable"]]:
  523. try:
  524. args.pop(args.index(self))
  525. except IndexError:
  526. pass
  527. # END remove self
  528. return args
  529. def _to_relative_path(self, path: PathLike) -> PathLike:
  530. """
  531. :return:
  532. Version of path relative to our git directory or raise :exc:`ValueError` if
  533. it is not within our git directory.
  534. :raise ValueError:
  535. """
  536. if not osp.isabs(path):
  537. return path
  538. if self.repo.bare:
  539. raise InvalidGitRepositoryError("require non-bare repository")
  540. if not osp.normpath(path).startswith(str(self.repo.working_tree_dir)):
  541. raise ValueError("Absolute path %r is not in git repository at %r" % (path, self.repo.working_tree_dir))
  542. result = os.path.relpath(path, self.repo.working_tree_dir)
  543. if os.fspath(path).endswith(os.sep) and not result.endswith(os.sep):
  544. result += os.sep
  545. return result
  546. def _preprocess_add_items(
  547. self, items: Union[PathLike, Sequence[Union[PathLike, Blob, BaseIndexEntry, "Submodule"]]]
  548. ) -> Tuple[List[PathLike], List[BaseIndexEntry]]:
  549. """Split the items into two lists of path strings and BaseEntries."""
  550. paths = []
  551. entries = []
  552. # if it is a string put in list
  553. if isinstance(items, (str, os.PathLike)):
  554. items = [items]
  555. for item in items:
  556. if isinstance(item, (str, os.PathLike)):
  557. paths.append(self._to_relative_path(item))
  558. elif isinstance(item, (Blob, Submodule)):
  559. entries.append(BaseIndexEntry.from_blob(item))
  560. elif isinstance(item, BaseIndexEntry):
  561. entries.append(item)
  562. else:
  563. raise TypeError("Invalid Type: %r" % item)
  564. # END for each item
  565. return paths, entries
  566. def _store_path(self, filepath: PathLike, fprogress: Callable) -> BaseIndexEntry:
  567. """Store file at filepath in the database and return the base index entry.
  568. :note:
  569. This needs the :func:`~git.index.util.git_working_dir` decorator active!
  570. This must be ensured in the calling code.
  571. """
  572. st = os.lstat(filepath) # Handles non-symlinks as well.
  573. if S_ISLNK(st.st_mode):
  574. # In PY3, readlink is a string, but we need bytes.
  575. # In PY2, it was just OS encoded bytes, we assumed UTF-8.
  576. def open_stream() -> BinaryIO:
  577. return BytesIO(force_bytes(os.readlink(filepath), encoding=defenc))
  578. else:
  579. def open_stream() -> BinaryIO:
  580. return open(filepath, "rb")
  581. with open_stream() as stream:
  582. fprogress(filepath, False, filepath)
  583. istream = self.repo.odb.store(IStream(Blob.type, st.st_size, stream))
  584. fprogress(filepath, True, filepath)
  585. return BaseIndexEntry(
  586. (
  587. stat_mode_to_index_mode(st.st_mode),
  588. istream.binsha,
  589. 0,
  590. to_native_path_linux(filepath),
  591. )
  592. )
  593. @unbare_repo
  594. @git_working_dir
  595. def _entries_for_paths(
  596. self,
  597. paths: List[str],
  598. path_rewriter: Union[Callable, None],
  599. fprogress: Callable,
  600. entries: List[BaseIndexEntry],
  601. ) -> List[BaseIndexEntry]:
  602. entries_added: List[BaseIndexEntry] = []
  603. if path_rewriter:
  604. for path in paths:
  605. if osp.isabs(path):
  606. abspath = path
  607. gitrelative_path = path[len(str(self.repo.working_tree_dir)) + 1 :]
  608. else:
  609. gitrelative_path = path
  610. if self.repo.working_tree_dir:
  611. abspath = osp.join(self.repo.working_tree_dir, gitrelative_path)
  612. # END obtain relative and absolute paths
  613. blob = Blob(
  614. self.repo,
  615. Blob.NULL_BIN_SHA,
  616. stat_mode_to_index_mode(os.stat(abspath).st_mode),
  617. to_native_path_linux(gitrelative_path),
  618. )
  619. # TODO: variable undefined
  620. entries.append(BaseIndexEntry.from_blob(blob))
  621. # END for each path
  622. del paths[:]
  623. # END rewrite paths
  624. # HANDLE PATHS
  625. assert len(entries_added) == 0
  626. for filepath in self._iter_expand_paths(paths):
  627. entries_added.append(self._store_path(filepath, fprogress))
  628. # END for each filepath
  629. # END path handling
  630. return entries_added
  631. def add(
  632. self,
  633. items: Union[PathLike, Sequence[Union[PathLike, Blob, BaseIndexEntry, "Submodule"]]],
  634. force: bool = True,
  635. fprogress: Callable = lambda *args: None,
  636. path_rewriter: Union[Callable[..., PathLike], None] = None,
  637. write: bool = True,
  638. write_extension_data: bool = False,
  639. ) -> List[BaseIndexEntry]:
  640. R"""Add files from the working tree, specific blobs, or
  641. :class:`~git.index.typ.BaseIndexEntry`\s to the index.
  642. :param items:
  643. Multiple types of items are supported, types can be mixed within one call.
  644. Different types imply a different handling. File paths may generally be
  645. relative or absolute.
  646. - path string
  647. Strings denote a relative or absolute path into the repository pointing
  648. to an existing file, e.g., ``CHANGES``, ``lib/myfile.ext``,
  649. ``/home/gitrepo/lib/myfile.ext``.
  650. Absolute paths must start with working tree directory of this index's
  651. repository to be considered valid. For example, if it was initialized
  652. with a non-normalized path, like ``/root/repo/../repo``, absolute paths
  653. to be added must start with ``/root/repo/../repo``.
  654. Paths provided like this must exist. When added, they will be written
  655. into the object database.
  656. PathStrings may contain globs, such as ``lib/__init__*``. Or they can be
  657. directories like ``lib``, which will add all the files within the
  658. directory and subdirectories.
  659. This equals a straight :manpage:`git-add(1)`.
  660. They are added at stage 0.
  661. - :class:`~git.objects.blob.Blob` or
  662. :class:`~git.objects.submodule.base.Submodule` object
  663. Blobs are added as they are assuming a valid mode is set.
  664. The file they refer to may or may not exist in the file system, but must
  665. be a path relative to our repository.
  666. If their sha is null (40*0), their path must exist in the file system
  667. relative to the git repository as an object will be created from the
  668. data at the path.
  669. The handling now very much equals the way string paths are processed,
  670. except that the mode you have set will be kept. This allows you to
  671. create symlinks by settings the mode respectively and writing the target
  672. of the symlink directly into the file. This equals a default Linux
  673. symlink which is not dereferenced automatically, except that it can be
  674. created on filesystems not supporting it as well.
  675. Please note that globs or directories are not allowed in
  676. :class:`~git.objects.blob.Blob` objects.
  677. They are added at stage 0.
  678. - :class:`~git.index.typ.BaseIndexEntry` or type
  679. Handling equals the one of :class:`~git.objects.blob.Blob` objects, but
  680. the stage may be explicitly set. Please note that Index Entries require
  681. binary sha's.
  682. :param force:
  683. **CURRENTLY INEFFECTIVE**
  684. If ``True``, otherwise ignored or excluded files will be added anyway. As
  685. opposed to the :manpage:`git-add(1)` command, we enable this flag by default
  686. as the API user usually wants the item to be added even though they might be
  687. excluded.
  688. :param fprogress:
  689. Function with signature ``f(path, done=False, item=item)`` called for each
  690. path to be added, one time once it is about to be added where ``done=False``
  691. and once after it was added where ``done=True``.
  692. ``item`` is set to the actual item we handle, either a path or a
  693. :class:`~git.index.typ.BaseIndexEntry`.
  694. Please note that the processed path is not guaranteed to be present in the
  695. index already as the index is currently being processed.
  696. :param path_rewriter:
  697. Function, with signature ``(string) func(BaseIndexEntry)``, returning a path
  698. for each passed entry which is the path to be actually recorded for the
  699. object created from :attr:`entry.path <git.index.typ.BaseIndexEntry.path>`.
  700. This allows you to write an index which is not identical to the layout of
  701. the actual files on your hard-disk. If not ``None`` and `items` contain
  702. plain paths, these paths will be converted to Entries beforehand and passed
  703. to the path_rewriter. Please note that ``entry.path`` is relative to the git
  704. repository.
  705. :param write:
  706. If ``True``, the index will be written once it was altered. Otherwise the
  707. changes only exist in memory and are not available to git commands.
  708. :param write_extension_data:
  709. If ``True``, extension data will be written back to the index. This can lead
  710. to issues in case it is containing the 'TREE' extension, which will cause
  711. the :manpage:`git-commit(1)` command to write an old tree, instead of a new
  712. one representing the now changed index.
  713. This doesn't matter if you use :meth:`IndexFile.commit`, which ignores the
  714. 'TREE' extension altogether. You should set it to ``True`` if you intend to
  715. use :meth:`IndexFile.commit` exclusively while maintaining support for
  716. third-party extensions. Besides that, you can usually safely ignore the
  717. built-in extensions when using GitPython on repositories that are not
  718. handled manually at all.
  719. All current built-in extensions are listed here:
  720. https://git-scm.com/docs/index-format
  721. :return:
  722. List of :class:`~git.index.typ.BaseIndexEntry`\s representing the entries
  723. just actually added.
  724. :raise OSError:
  725. If a supplied path did not exist. Please note that
  726. :class:`~git.index.typ.BaseIndexEntry` objects that do not have a null sha
  727. will be added even if their paths do not exist.
  728. """
  729. # Sort the entries into strings and Entries.
  730. # Blobs are converted to entries automatically.
  731. # Paths can be git-added. For everything else we use git-update-index.
  732. paths, entries = self._preprocess_add_items(items)
  733. entries_added: List[BaseIndexEntry] = []
  734. # This code needs a working tree, so we try not to run it unless required.
  735. # That way, we are OK on a bare repository as well.
  736. # If there are no paths, the rewriter has nothing to do either.
  737. if paths:
  738. entries_added.extend(self._entries_for_paths(paths, path_rewriter, fprogress, entries))
  739. # HANDLE ENTRIES
  740. if entries:
  741. null_mode_entries = [e for e in entries if e.mode == 0]
  742. if null_mode_entries:
  743. raise ValueError(
  744. "At least one Entry has a null-mode - please use index.remove to remove files for clarity"
  745. )
  746. # END null mode should be remove
  747. # HANDLE ENTRY OBJECT CREATION
  748. # Create objects if required, otherwise go with the existing shas.
  749. null_entries_indices = [i for i, e in enumerate(entries) if e.binsha == Object.NULL_BIN_SHA]
  750. if null_entries_indices:
  751. @git_working_dir
  752. def handle_null_entries(self: "IndexFile") -> None:
  753. for ei in null_entries_indices:
  754. null_entry = entries[ei]
  755. new_entry = self._store_path(null_entry.path, fprogress)
  756. # Update null entry.
  757. entries[ei] = BaseIndexEntry(
  758. (
  759. null_entry.mode,
  760. new_entry.binsha,
  761. null_entry.stage,
  762. null_entry.path,
  763. )
  764. )
  765. # END for each entry index
  766. # END closure
  767. handle_null_entries(self)
  768. # END null_entry handling
  769. # REWRITE PATHS
  770. # If we have to rewrite the entries, do so now, after we have generated all
  771. # object sha's.
  772. if path_rewriter:
  773. for i, e in enumerate(entries):
  774. entries[i] = BaseIndexEntry((e.mode, e.binsha, e.stage, path_rewriter(e)))
  775. # END for each entry
  776. # END handle path rewriting
  777. # Just go through the remaining entries and provide progress info.
  778. for i, entry in enumerate(entries):
  779. progress_sent = i in null_entries_indices
  780. if not progress_sent:
  781. fprogress(entry.path, False, entry)
  782. fprogress(entry.path, True, entry)
  783. # END handle progress
  784. # END for each entry
  785. entries_added.extend(entries)
  786. # END if there are base entries
  787. # FINALIZE
  788. # Add the new entries to this instance.
  789. for entry in entries_added:
  790. self.entries[(entry.path, 0)] = IndexEntry.from_base(entry)
  791. if write:
  792. self.write(ignore_extension_data=not write_extension_data)
  793. # END handle write
  794. return entries_added
  795. def _items_to_rela_paths(
  796. self,
  797. items: Union[PathLike, Sequence[Union[PathLike, BaseIndexEntry, Blob, Submodule]]],
  798. ) -> List[PathLike]:
  799. """Returns a list of repo-relative paths from the given items which
  800. may be absolute or relative paths, entries or blobs."""
  801. paths = []
  802. # If string, put in list.
  803. if isinstance(items, (str, os.PathLike)):
  804. items = [items]
  805. for item in items:
  806. if isinstance(item, (BaseIndexEntry, (Blob, Submodule))):
  807. paths.append(self._to_relative_path(item.path))
  808. elif isinstance(item, (str, os.PathLike)):
  809. paths.append(self._to_relative_path(item))
  810. else:
  811. raise TypeError("Invalid item type: %r" % item)
  812. # END for each item
  813. return paths
  814. @post_clear_cache
  815. @default_index
  816. def remove(
  817. self,
  818. items: Union[PathLike, Sequence[Union[PathLike, Blob, BaseIndexEntry, "Submodule"]]],
  819. working_tree: bool = False,
  820. **kwargs: Any,
  821. ) -> List[str]:
  822. R"""Remove the given items from the index and optionally from the working tree
  823. as well.
  824. :param items:
  825. Multiple types of items are supported which may be be freely mixed.
  826. - path string
  827. Remove the given path at all stages. If it is a directory, you must
  828. specify the ``r=True`` keyword argument to remove all file entries below
  829. it. If absolute paths are given, they will be converted to a path
  830. relative to the git repository directory containing the working tree
  831. The path string may include globs, such as ``*.c``.
  832. - :class:`~git.objects.blob.Blob` object
  833. Only the path portion is used in this case.
  834. - :class:`~git.index.typ.BaseIndexEntry` or compatible type
  835. The only relevant information here is the path. The stage is ignored.
  836. :param working_tree:
  837. If ``True``, the entry will also be removed from the working tree,
  838. physically removing the respective file. This may fail if there are
  839. uncommitted changes in it.
  840. :param kwargs:
  841. Additional keyword arguments to be passed to :manpage:`git-rm(1)`, such as
  842. ``r`` to allow recursive removal.
  843. :return:
  844. List(path_string, ...) list of repository relative paths that have been
  845. removed effectively.
  846. This is interesting to know in case you have provided a directory or globs.
  847. Paths are relative to the repository.
  848. """
  849. args = []
  850. if not working_tree:
  851. args.append("--cached")
  852. args.append("--")
  853. # Preprocess paths.
  854. paths = list(map(os.fspath, self._items_to_rela_paths(items))) # type: ignore[arg-type]
  855. removed_paths = self.repo.git.rm(args, paths, **kwargs).splitlines()
  856. # Process output to gain proper paths.
  857. # rm 'path'
  858. return [p[4:-1] for p in removed_paths]
  859. @post_clear_cache
  860. @default_index
  861. def move(
  862. self,
  863. items: Union[PathLike, Sequence[Union[PathLike, Blob, BaseIndexEntry, "Submodule"]]],
  864. skip_errors: bool = False,
  865. **kwargs: Any,
  866. ) -> List[Tuple[str, str]]:
  867. """Rename/move the items, whereas the last item is considered the destination of
  868. the move operation.
  869. If the destination is a file, the first item (of two) must be a file as well.
  870. If the destination is a directory, it may be preceded by one or more directories
  871. or files.
  872. The working tree will be affected in non-bare repositories.
  873. :param items:
  874. Multiple types of items are supported, please see the :meth:`remove` method
  875. for reference.
  876. :param skip_errors:
  877. If ``True``, errors such as ones resulting from missing source files will be
  878. skipped.
  879. :param kwargs:
  880. Additional arguments you would like to pass to :manpage:`git-mv(1)`, such as
  881. ``dry_run`` or ``force``.
  882. :return:
  883. List(tuple(source_path_string, destination_path_string), ...)
  884. A list of pairs, containing the source file moved as well as its actual
  885. destination. Relative to the repository root.
  886. :raise ValueError:
  887. If only one item was given.
  888. :raise git.exc.GitCommandError:
  889. If git could not handle your request.
  890. """
  891. args = []
  892. if skip_errors:
  893. args.append("-k")
  894. paths = self._items_to_rela_paths(items)
  895. if len(paths) < 2:
  896. raise ValueError("Please provide at least one source and one destination of the move operation")
  897. was_dry_run = kwargs.pop("dry_run", kwargs.pop("n", None))
  898. kwargs["dry_run"] = True
  899. # First execute rename in dry run so the command tells us what it actually does
  900. # (for later output).
  901. out = []
  902. mvlines = self.repo.git.mv(args, paths, **kwargs).splitlines()
  903. # Parse result - first 0:n/2 lines are 'checking ', the remaining ones are the
  904. # 'renaming' ones which we parse.
  905. for ln in range(int(len(mvlines) / 2), len(mvlines)):
  906. tokens = mvlines[ln].split(" to ")
  907. assert len(tokens) == 2, "Too many tokens in %s" % mvlines[ln]
  908. # [0] = Renaming x
  909. # [1] = y
  910. out.append((tokens[0][9:], tokens[1]))
  911. # END for each line to parse
  912. # Either prepare for the real run, or output the dry-run result.
  913. if was_dry_run:
  914. return out
  915. # END handle dry run
  916. # Now apply the actual operation.
  917. kwargs.pop("dry_run")
  918. self.repo.git.mv(args, paths, **kwargs)
  919. return out
  920. def commit(
  921. self,
  922. message: str,
  923. parent_commits: Union[List[Commit], None] = None,
  924. head: bool = True,
  925. author: Union[None, Actor] = None,
  926. committer: Union[None, Actor] = None,
  927. author_date: Union[datetime.datetime, str, None] = None,
  928. commit_date: Union[datetime.datetime, str, None] = None,
  929. skip_hooks: bool = False,
  930. ) -> Commit:
  931. """Commit the current default index file, creating a
  932. :class:`~git.objects.commit.Commit` object.
  933. For more information on the arguments, see
  934. :meth:`Commit.create_from_tree <git.objects.commit.Commit.create_from_tree>`.
  935. :note:
  936. If you have manually altered the :attr:`entries` member of this instance,
  937. don't forget to :meth:`write` your changes to disk beforehand.
  938. :note:
  939. Passing ``skip_hooks=True`` is the equivalent of using ``-n`` or
  940. ``--no-verify`` on the command line.
  941. :return:
  942. :class:`~git.objects.commit.Commit` object representing the new commit
  943. """
  944. if not skip_hooks:
  945. run_commit_hook("pre-commit", self)
  946. self._write_commit_editmsg(message)
  947. run_commit_hook("commit-msg", self, self._commit_editmsg_filepath())
  948. message = self._read_commit_editmsg()
  949. self._remove_commit_editmsg()
  950. tree = self.write_tree()
  951. rval = Commit.create_from_tree(
  952. self.repo,
  953. tree,
  954. message,
  955. parent_commits,
  956. head,
  957. author=author,
  958. committer=committer,
  959. author_date=author_date,
  960. commit_date=commit_date,
  961. )
  962. if not skip_hooks:
  963. run_commit_hook("post-commit", self)
  964. return rval
  965. def _write_commit_editmsg(self, message: str) -> None:
  966. with open(self._commit_editmsg_filepath(), "wb") as commit_editmsg_file:
  967. commit_editmsg_file.write(message.encode(defenc))
  968. def _remove_commit_editmsg(self) -> None:
  969. os.remove(self._commit_editmsg_filepath())
  970. def _read_commit_editmsg(self) -> str:
  971. with open(self._commit_editmsg_filepath(), "rb") as commit_editmsg_file:
  972. return commit_editmsg_file.read().decode(defenc)
  973. def _commit_editmsg_filepath(self) -> str:
  974. return osp.join(self.repo.common_dir, "COMMIT_EDITMSG")
  975. def _flush_stdin_and_wait(cls, proc: "Popen[bytes]", ignore_stdout: bool = False) -> bytes:
  976. stdin_IO = proc.stdin
  977. if stdin_IO:
  978. stdin_IO.flush()
  979. stdin_IO.close()
  980. stdout = b""
  981. if not ignore_stdout and proc.stdout:
  982. stdout = proc.stdout.read()
  983. if proc.stdout:
  984. proc.stdout.close()
  985. proc.wait()
  986. return stdout
  987. @default_index
  988. def checkout(
  989. self,
  990. paths: Union[None, Iterable[PathLike]] = None,
  991. force: bool = False,
  992. fprogress: Callable = lambda *args: None,
  993. **kwargs: Any,
  994. ) -> Union[None, Iterator[PathLike], Sequence[PathLike]]:
  995. """Check out the given paths or all files from the version known to the index
  996. into the working tree.
  997. :note:
  998. Be sure you have written pending changes using the :meth:`write` method in
  999. case you have altered the entries dictionary directly.
  1000. :param paths:
  1001. If ``None``, all paths in the index will be checked out.
  1002. Otherwise an iterable of relative or absolute paths or a single path
  1003. pointing to files or directories in the index is expected.
  1004. :param force:
  1005. If ``True``, existing files will be overwritten even if they contain local
  1006. modifications.
  1007. If ``False``, these will trigger a :exc:`~git.exc.CheckoutError`.
  1008. :param fprogress:
  1009. See :meth:`IndexFile.add` for signature and explanation.
  1010. The provided progress information will contain ``None`` as path and item if
  1011. no explicit paths are given. Otherwise progress information will be send
  1012. prior and after a file has been checked out.
  1013. :param kwargs:
  1014. Additional arguments to be passed to :manpage:`git-checkout-index(1)`.
  1015. :return:
  1016. Iterable yielding paths to files which have been checked out and are
  1017. guaranteed to match the version stored in the index.
  1018. :raise git.exc.CheckoutError:
  1019. * If at least one file failed to be checked out. This is a summary, hence it
  1020. will checkout as many files as it can anyway.
  1021. * If one of files or directories do not exist in the index (as opposed to
  1022. the original git command, which ignores them).
  1023. :raise git.exc.GitCommandError:
  1024. If error lines could not be parsed - this truly is an exceptional state.
  1025. :note:
  1026. The checkout is limited to checking out the files in the index. Files which
  1027. are not in the index anymore and exist in the working tree will not be
  1028. deleted. This behaviour is fundamentally different to ``head.checkout``,
  1029. i.e. if you want :manpage:`git-checkout(1)`-like behaviour, use
  1030. ``head.checkout`` instead of ``index.checkout``.
  1031. """
  1032. args = ["--index"]
  1033. if force:
  1034. args.append("--force")
  1035. failed_files = []
  1036. failed_reasons = []
  1037. unknown_lines = []
  1038. def handle_stderr(proc: "Popen[bytes]", iter_checked_out_files: Iterable[PathLike]) -> None:
  1039. stderr_IO = proc.stderr
  1040. if not stderr_IO:
  1041. return # Return early if stderr empty.
  1042. stderr_bytes = stderr_IO.read()
  1043. # line contents:
  1044. stderr = stderr_bytes.decode(defenc)
  1045. # git-checkout-index: this already exists
  1046. endings = (
  1047. " already exists",
  1048. " is not in the cache",
  1049. " does not exist at stage",
  1050. " is unmerged",
  1051. )
  1052. for line in stderr.splitlines():
  1053. if not line.startswith("git checkout-index: ") and not line.startswith("git-checkout-index: "):
  1054. is_a_dir = " is a directory"
  1055. unlink_issue = "unable to unlink old '"
  1056. already_exists_issue = " already exists, no checkout" # created by entry.c:checkout_entry(...)
  1057. if line.endswith(is_a_dir):
  1058. failed_files.append(line[: -len(is_a_dir)])
  1059. failed_reasons.append(is_a_dir)
  1060. elif line.startswith(unlink_issue):
  1061. failed_files.append(line[len(unlink_issue) : line.rfind("'")])
  1062. failed_reasons.append(unlink_issue)
  1063. elif line.endswith(already_exists_issue):
  1064. failed_files.append(line[: -len(already_exists_issue)])
  1065. failed_reasons.append(already_exists_issue)
  1066. else:
  1067. unknown_lines.append(line)
  1068. continue
  1069. # END special lines parsing
  1070. for e in endings:
  1071. if line.endswith(e):
  1072. failed_files.append(line[20 : -len(e)])
  1073. failed_reasons.append(e)
  1074. break
  1075. # END if ending matches
  1076. # END for each possible ending
  1077. # END for each line
  1078. if unknown_lines:
  1079. raise GitCommandError(("git-checkout-index",), 128, stderr)
  1080. if failed_files:
  1081. valid_files = list(set(iter_checked_out_files) - set(failed_files))
  1082. raise CheckoutError(
  1083. "Some files could not be checked out from the index due to local modifications",
  1084. failed_files,
  1085. valid_files,
  1086. failed_reasons,
  1087. )
  1088. # END stderr handler
  1089. if paths is None:
  1090. args.append("--all")
  1091. kwargs["as_process"] = 1
  1092. fprogress(None, False, None)
  1093. proc = self.repo.git.checkout_index(*args, **kwargs)
  1094. proc.wait()
  1095. fprogress(None, True, None)
  1096. rval_iter = (e.path for e in self.entries.values())
  1097. handle_stderr(proc, rval_iter)
  1098. return rval_iter
  1099. else:
  1100. if isinstance(paths, str):
  1101. paths = [paths]
  1102. # Make sure we have our entries loaded before we start checkout_index, which
  1103. # will hold a lock on it. We try to get the lock as well during our entries
  1104. # initialization.
  1105. self.entries # noqa: B018
  1106. args.append("--stdin")
  1107. kwargs["as_process"] = True
  1108. kwargs["istream"] = subprocess.PIPE
  1109. proc = self.repo.git.checkout_index(args, **kwargs)
  1110. # FIXME: Reading from GIL!
  1111. def make_exc() -> GitCommandError:
  1112. return GitCommandError(("git-checkout-index", *args), 128, proc.stderr.read())
  1113. checked_out_files: List[PathLike] = []
  1114. for path in paths:
  1115. co_path = to_native_path_linux(self._to_relative_path(path))
  1116. # If the item is not in the index, it could be a directory.
  1117. path_is_directory = False
  1118. try:
  1119. self.entries[(co_path, 0)]
  1120. except KeyError:
  1121. folder = co_path
  1122. if not folder.endswith("/"):
  1123. folder += "/"
  1124. for entry in self.entries.values():
  1125. if os.fspath(entry.path).startswith(folder):
  1126. p = entry.path
  1127. self._write_path_to_stdin(proc, p, p, make_exc, fprogress, read_from_stdout=False)
  1128. checked_out_files.append(p)
  1129. path_is_directory = True
  1130. # END if entry is in directory
  1131. # END for each entry
  1132. # END path exception handlnig
  1133. if not path_is_directory:
  1134. self._write_path_to_stdin(proc, co_path, path, make_exc, fprogress, read_from_stdout=False)
  1135. checked_out_files.append(co_path)
  1136. # END path is a file
  1137. # END for each path
  1138. try:
  1139. self._flush_stdin_and_wait(proc, ignore_stdout=True)
  1140. except GitCommandError:
  1141. # Without parsing stdout we don't know what failed.
  1142. raise CheckoutError( # noqa: B904
  1143. "Some files could not be checked out from the index, probably because they didn't exist.",
  1144. failed_files,
  1145. [],
  1146. failed_reasons,
  1147. )
  1148. handle_stderr(proc, checked_out_files)
  1149. return checked_out_files
  1150. # END paths handling
  1151. @default_index
  1152. def reset(
  1153. self,
  1154. commit: Union[Commit, "Reference", str] = "HEAD",
  1155. working_tree: bool = False,
  1156. paths: Union[None, Iterable[PathLike]] = None,
  1157. head: bool = False,
  1158. **kwargs: Any,
  1159. ) -> "IndexFile":
  1160. """Reset the index to reflect the tree at the given commit. This will not adjust
  1161. our HEAD reference by default, as opposed to
  1162. :meth:`HEAD.reset <git.refs.head.HEAD.reset>`.
  1163. :param commit:
  1164. Revision, :class:`~git.refs.reference.Reference` or
  1165. :class:`~git.objects.commit.Commit` specifying the commit we should
  1166. represent.
  1167. If you want to specify a tree only, use :meth:`IndexFile.from_tree` and
  1168. overwrite the default index.
  1169. :param working_tree:
  1170. If ``True``, the files in the working tree will reflect the changed index.
  1171. If ``False``, the working tree will not be touched.
  1172. Please note that changes to the working copy will be discarded without
  1173. warning!
  1174. :param head:
  1175. If ``True``, the head will be set to the given commit. This is ``False`` by
  1176. default, but if ``True``, this method behaves like
  1177. :meth:`HEAD.reset <git.refs.head.HEAD.reset>`.
  1178. :param paths:
  1179. If given as an iterable of absolute or repository-relative paths, only these
  1180. will be reset to their state at the given commit-ish.
  1181. The paths need to exist at the commit, otherwise an exception will be
  1182. raised.
  1183. :param kwargs:
  1184. Additional keyword arguments passed to :manpage:`git-reset(1)`.
  1185. :note:
  1186. :meth:`IndexFile.reset`, as opposed to
  1187. :meth:`HEAD.reset <git.refs.head.HEAD.reset>`, will not delete any files in
  1188. order to maintain a consistent working tree. Instead, it will just check out
  1189. the files according to their state in the index.
  1190. If you want :manpage:`git-reset(1)`-like behaviour, use
  1191. :meth:`HEAD.reset <git.refs.head.HEAD.reset>` instead.
  1192. :return:
  1193. self
  1194. """
  1195. # What we actually want to do is to merge the tree into our existing index,
  1196. # which is what git-read-tree does.
  1197. new_inst = type(self).from_tree(self.repo, commit)
  1198. if not paths:
  1199. self.entries = new_inst.entries
  1200. else:
  1201. nie = new_inst.entries
  1202. for path in paths:
  1203. path = self._to_relative_path(path)
  1204. try:
  1205. key = entry_key(path, 0)
  1206. self.entries[key] = nie[key]
  1207. except KeyError:
  1208. # If key is not in theirs, it mustn't be in ours.
  1209. try:
  1210. del self.entries[key]
  1211. except KeyError:
  1212. pass
  1213. # END handle deletion keyerror
  1214. # END handle keyerror
  1215. # END for each path
  1216. # END handle paths
  1217. self.write()
  1218. if working_tree:
  1219. self.checkout(paths=paths, force=True)
  1220. # END handle working tree
  1221. if head:
  1222. self.repo.head.set_commit(self.repo.commit(commit), logmsg="%s: Updating HEAD" % commit)
  1223. # END handle head change
  1224. return self
  1225. # FIXME: This is documented to accept the same parameters as Diffable.diff, but this
  1226. # does not handle NULL_TREE for `other`. (The suppressed mypy error is about this.)
  1227. def diff(
  1228. self,
  1229. other: Union[ # type: ignore[override]
  1230. Literal[git_diff.DiffConstants.INDEX],
  1231. "Tree",
  1232. "Commit",
  1233. str,
  1234. None,
  1235. ] = git_diff.INDEX,
  1236. paths: Union[PathLike, List[PathLike], Tuple[PathLike, ...], None] = None,
  1237. create_patch: bool = False,
  1238. **kwargs: Any,
  1239. ) -> git_diff.DiffIndex[git_diff.Diff]:
  1240. """Diff this index against the working copy or a :class:`~git.objects.tree.Tree`
  1241. or :class:`~git.objects.commit.Commit` object.
  1242. For documentation of the parameters and return values, see
  1243. :meth:`Diffable.diff <git.diff.Diffable.diff>`.
  1244. :note:
  1245. Will only work with indices that represent the default git index as they
  1246. have not been initialized with a stream.
  1247. """
  1248. # Only run if we are the default repository index.
  1249. if self._file_path != self._index_path():
  1250. raise AssertionError("Cannot call %r on indices that do not represent the default git index" % self.diff())
  1251. # Index against index is always empty.
  1252. if other is self.INDEX:
  1253. return git_diff.DiffIndex()
  1254. # Index against anything but None is a reverse diff with the respective item.
  1255. # Handle existing -R flags properly.
  1256. # Transform strings to the object so that we can call diff on it.
  1257. if isinstance(other, str):
  1258. other = self.repo.rev_parse(other)
  1259. # END object conversion
  1260. if isinstance(other, Object): # For Tree or Commit.
  1261. # Invert the existing R flag.
  1262. cur_val = kwargs.get("R", False)
  1263. kwargs["R"] = not cur_val
  1264. return other.diff(self.INDEX, paths, create_patch, **kwargs)
  1265. # END diff against other item handling
  1266. # If other is not None here, something is wrong.
  1267. if other is not None:
  1268. raise ValueError("other must be None, Diffable.INDEX, a Tree or Commit, was %r" % other)
  1269. # Diff against working copy - can be handled by superclass natively.
  1270. return super().diff(other, paths, create_patch, **kwargs)