You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1240 lines
51KB

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