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.

1076 lines
43KB

  1. # repo.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. from builtins import str
  7. from collections import namedtuple
  8. import logging
  9. import os
  10. import re
  11. import warnings
  12. from git.cmd import (
  13. Git,
  14. handle_process_output
  15. )
  16. from git.compat import (
  17. text_type,
  18. defenc,
  19. PY3,
  20. safe_decode,
  21. range,
  22. is_win,
  23. )
  24. from git.config import GitConfigParser
  25. from git.db import GitCmdObjectDB
  26. from git.exc import InvalidGitRepositoryError, NoSuchPathError, GitCommandError
  27. from git.index import IndexFile
  28. from git.objects import Submodule, RootModule, Commit
  29. from git.refs import HEAD, Head, Reference, TagReference
  30. from git.remote import Remote, add_progress, to_progress_instance
  31. from git.util import Actor, finalize_process, decygpath, hex_to_bin, expand_path
  32. import os.path as osp
  33. from .fun import rev_parse, is_git_dir, find_submodule_git_dir, touch, find_worktree_git_dir
  34. import gc
  35. import gitdb
  36. try:
  37. import pathlib
  38. except ImportError:
  39. pathlib = None
  40. log = logging.getLogger(__name__)
  41. BlameEntry = namedtuple('BlameEntry', ['commit', 'linenos', 'orig_path', 'orig_linenos'])
  42. __all__ = ('Repo',)
  43. class Repo(object):
  44. """Represents a git repository and allows you to query references,
  45. gather commit information, generate diffs, create and clone repositories query
  46. the log.
  47. The following attributes are worth using:
  48. 'working_dir' is the working directory of the git command, which is the working tree
  49. directory if available or the .git directory in case of bare repositories
  50. 'working_tree_dir' is the working tree directory, but will raise AssertionError
  51. if we are a bare repository.
  52. 'git_dir' is the .git repository directory, which is always set."""
  53. DAEMON_EXPORT_FILE = 'git-daemon-export-ok'
  54. git = None # Must exist, or __del__ will fail in case we raise on `__init__()`
  55. working_dir = None
  56. _working_tree_dir = None
  57. git_dir = None
  58. _common_dir = None
  59. # precompiled regex
  60. re_whitespace = re.compile(r'\s+')
  61. re_hexsha_only = re.compile('^[0-9A-Fa-f]{40}$')
  62. re_hexsha_shortened = re.compile('^[0-9A-Fa-f]{4,40}$')
  63. re_author_committer_start = re.compile(r'^(author|committer)')
  64. re_tab_full_line = re.compile(r'^\t(.*)$')
  65. # invariants
  66. # represents the configuration level of a configuration file
  67. config_level = ("system", "user", "global", "repository")
  68. # Subclass configuration
  69. # Subclasses may easily bring in their own custom types by placing a constructor or type here
  70. GitCommandWrapperType = Git
  71. def __init__(self, path=None, odbt=GitCmdObjectDB, search_parent_directories=False, expand_vars=True):
  72. """Create a new Repo instance
  73. :param path:
  74. the path to either the root git directory or the bare git repo::
  75. repo = Repo("/Users/mtrier/Development/git-python")
  76. repo = Repo("/Users/mtrier/Development/git-python.git")
  77. repo = Repo("~/Development/git-python.git")
  78. repo = Repo("$REPOSITORIES/Development/git-python.git")
  79. repo = Repo("C:\\Users\\mtrier\\Development\\git-python\\.git")
  80. - In *Cygwin*, path may be a `'cygdrive/...'` prefixed path.
  81. - If it evaluates to false, :envvar:`GIT_DIR` is used, and if this also evals to false,
  82. the current-directory is used.
  83. :param odbt:
  84. Object DataBase type - a type which is constructed by providing
  85. the directory containing the database objects, i.e. .git/objects. It will
  86. be used to access all object data
  87. :param search_parent_directories:
  88. if True, all parent directories will be searched for a valid repo as well.
  89. Please note that this was the default behaviour in older versions of GitPython,
  90. which is considered a bug though.
  91. :raise InvalidGitRepositoryError:
  92. :raise NoSuchPathError:
  93. :return: git.Repo """
  94. epath = path or os.getenv('GIT_DIR')
  95. if not epath:
  96. epath = os.getcwd()
  97. if Git.is_cygwin():
  98. epath = decygpath(epath)
  99. epath = epath or path or os.getcwd()
  100. if not isinstance(epath, str):
  101. epath = str(epath)
  102. if expand_vars and ("%" in epath or "$" in epath):
  103. warnings.warn("The use of environment variables in paths is deprecated" +
  104. "\nfor security reasons and may be removed in the future!!")
  105. epath = expand_path(epath, expand_vars)
  106. if not os.path.exists(epath):
  107. raise NoSuchPathError(epath)
  108. ## Walk up the path to find the `.git` dir.
  109. #
  110. curpath = epath
  111. while curpath:
  112. # ABOUT osp.NORMPATH
  113. # It's important to normalize the paths, as submodules will otherwise initialize their
  114. # repo instances with paths that depend on path-portions that will not exist after being
  115. # removed. It's just cleaner.
  116. if is_git_dir(curpath):
  117. self.git_dir = curpath
  118. # from man git-config : core.worktree
  119. # Set the path to the root of the working tree. If GIT_COMMON_DIR environment
  120. # variable is set, core.worktree is ignored and not used for determining the
  121. # root of working tree. This can be overridden by the GIT_WORK_TREE environment
  122. # variable. The value can be an absolute path or relative to the path to the .git
  123. # directory, which is either specified by GIT_DIR, or automatically discovered.
  124. # If GIT_DIR is specified but none of GIT_WORK_TREE and core.worktree is specified,
  125. # the current working directory is regarded as the top level of your working tree.
  126. self._working_tree_dir = os.path.dirname(self.git_dir)
  127. if os.environ.get('GIT_COMMON_DIR') is None:
  128. gitconf = self.config_reader("repository")
  129. if gitconf.has_option('core', 'worktree'):
  130. self._working_tree_dir = gitconf.get('core', 'worktree')
  131. if 'GIT_WORK_TREE' in os.environ:
  132. self._working_tree_dir = os.getenv('GIT_WORK_TREE')
  133. break
  134. dotgit = osp.join(curpath, '.git')
  135. sm_gitpath = find_submodule_git_dir(dotgit)
  136. if sm_gitpath is not None:
  137. self.git_dir = osp.normpath(sm_gitpath)
  138. sm_gitpath = find_submodule_git_dir(dotgit)
  139. if sm_gitpath is None:
  140. sm_gitpath = find_worktree_git_dir(dotgit)
  141. if sm_gitpath is not None:
  142. self.git_dir = expand_path(sm_gitpath, expand_vars)
  143. self._working_tree_dir = curpath
  144. break
  145. if not search_parent_directories:
  146. break
  147. curpath, tail = osp.split(curpath)
  148. if not tail:
  149. break
  150. # END while curpath
  151. if self.git_dir is None:
  152. raise InvalidGitRepositoryError(epath)
  153. self._bare = False
  154. try:
  155. self._bare = self.config_reader("repository").getboolean('core', 'bare')
  156. except Exception:
  157. # lets not assume the option exists, although it should
  158. pass
  159. try:
  160. common_dir = open(osp.join(self.git_dir, 'commondir'), 'rt').readlines()[0].strip()
  161. self._common_dir = osp.join(self.git_dir, common_dir)
  162. except (OSError, IOError):
  163. self._common_dir = None
  164. # adjust the wd in case we are actually bare - we didn't know that
  165. # in the first place
  166. if self._bare:
  167. self._working_tree_dir = None
  168. # END working dir handling
  169. self.working_dir = self._working_tree_dir or self.common_dir
  170. self.git = self.GitCommandWrapperType(self.working_dir)
  171. # special handling, in special times
  172. args = [osp.join(self.common_dir, 'objects')]
  173. if issubclass(odbt, GitCmdObjectDB):
  174. args.append(self.git)
  175. self.odb = odbt(*args)
  176. def __enter__(self):
  177. return self
  178. def __exit__(self, exc_type, exc_value, traceback):
  179. self.close()
  180. def __del__(self):
  181. try:
  182. self.close()
  183. except Exception:
  184. pass
  185. def close(self):
  186. if self.git:
  187. self.git.clear_cache()
  188. # Tempfiles objects on Windows are holding references to
  189. # open files until they are collected by the garbage
  190. # collector, thus preventing deletion.
  191. # TODO: Find these references and ensure they are closed
  192. # and deleted synchronously rather than forcing a gc
  193. # collection.
  194. if is_win:
  195. gc.collect()
  196. gitdb.util.mman.collect()
  197. if is_win:
  198. gc.collect()
  199. def __eq__(self, rhs):
  200. if isinstance(rhs, Repo):
  201. return self.git_dir == rhs.git_dir
  202. return False
  203. def __ne__(self, rhs):
  204. return not self.__eq__(rhs)
  205. def __hash__(self):
  206. return hash(self.git_dir)
  207. # Description property
  208. def _get_description(self):
  209. filename = osp.join(self.git_dir, 'description')
  210. with open(filename, 'rb') as fp:
  211. return fp.read().rstrip().decode(defenc)
  212. def _set_description(self, descr):
  213. filename = osp.join(self.git_dir, 'description')
  214. with open(filename, 'wb') as fp:
  215. fp.write((descr + '\n').encode(defenc))
  216. description = property(_get_description, _set_description,
  217. doc="the project's description")
  218. del _get_description
  219. del _set_description
  220. @property
  221. def working_tree_dir(self):
  222. """:return: The working tree directory of our git repository. If this is a bare repository, None is returned.
  223. """
  224. return self._working_tree_dir
  225. @property
  226. def common_dir(self):
  227. """:return: The git dir that holds everything except possibly HEAD,
  228. FETCH_HEAD, ORIG_HEAD, COMMIT_EDITMSG, index, and logs/ .
  229. """
  230. return self._common_dir or self.git_dir
  231. @property
  232. def bare(self):
  233. """:return: True if the repository is bare"""
  234. return self._bare
  235. @property
  236. def heads(self):
  237. """A list of ``Head`` objects representing the branch heads in
  238. this repo
  239. :return: ``git.IterableList(Head, ...)``"""
  240. return Head.list_items(self)
  241. @property
  242. def references(self):
  243. """A list of Reference objects representing tags, heads and remote references.
  244. :return: IterableList(Reference, ...)"""
  245. return Reference.list_items(self)
  246. # alias for references
  247. refs = references
  248. # alias for heads
  249. branches = heads
  250. @property
  251. def index(self):
  252. """:return: IndexFile representing this repository's index.
  253. :note: This property can be expensive, as the returned ``IndexFile`` will be
  254. reinitialized. It's recommended to re-use the object."""
  255. return IndexFile(self)
  256. @property
  257. def head(self):
  258. """:return: HEAD Object pointing to the current head reference"""
  259. return HEAD(self, 'HEAD')
  260. @property
  261. def remotes(self):
  262. """A list of Remote objects allowing to access and manipulate remotes
  263. :return: ``git.IterableList(Remote, ...)``"""
  264. return Remote.list_items(self)
  265. def remote(self, name='origin'):
  266. """:return: Remote with the specified name
  267. :raise ValueError: if no remote with such a name exists"""
  268. r = Remote(self, name)
  269. if not r.exists():
  270. raise ValueError("Remote named '%s' didn't exist" % name)
  271. return r
  272. #{ Submodules
  273. @property
  274. def submodules(self):
  275. """
  276. :return: git.IterableList(Submodule, ...) of direct submodules
  277. available from the current head"""
  278. return Submodule.list_items(self)
  279. def submodule(self, name):
  280. """ :return: Submodule with the given name
  281. :raise ValueError: If no such submodule exists"""
  282. try:
  283. return self.submodules[name]
  284. except IndexError:
  285. raise ValueError("Didn't find submodule named %r" % name)
  286. # END exception handling
  287. def create_submodule(self, *args, **kwargs):
  288. """Create a new submodule
  289. :note: See the documentation of Submodule.add for a description of the
  290. applicable parameters
  291. :return: created submodules"""
  292. return Submodule.add(self, *args, **kwargs)
  293. def iter_submodules(self, *args, **kwargs):
  294. """An iterator yielding Submodule instances, see Traversable interface
  295. for a description of args and kwargs
  296. :return: Iterator"""
  297. return RootModule(self).traverse(*args, **kwargs)
  298. def submodule_update(self, *args, **kwargs):
  299. """Update the submodules, keeping the repository consistent as it will
  300. take the previous state into consideration. For more information, please
  301. see the documentation of RootModule.update"""
  302. return RootModule(self).update(*args, **kwargs)
  303. #}END submodules
  304. @property
  305. def tags(self):
  306. """A list of ``Tag`` objects that are available in this repo
  307. :return: ``git.IterableList(TagReference, ...)`` """
  308. return TagReference.list_items(self)
  309. def tag(self, path):
  310. """:return: TagReference Object, reference pointing to a Commit or Tag
  311. :param path: path to the tag reference, i.e. 0.1.5 or tags/0.1.5 """
  312. return TagReference(self, path)
  313. def create_head(self, path, commit='HEAD', force=False, logmsg=None):
  314. """Create a new head within the repository.
  315. For more documentation, please see the Head.create method.
  316. :return: newly created Head Reference"""
  317. return Head.create(self, path, commit, force, logmsg)
  318. def delete_head(self, *heads, **kwargs):
  319. """Delete the given heads
  320. :param kwargs: Additional keyword arguments to be passed to git-branch"""
  321. return Head.delete(self, *heads, **kwargs)
  322. def create_tag(self, path, ref='HEAD', message=None, force=False, **kwargs):
  323. """Create a new tag reference.
  324. For more documentation, please see the TagReference.create method.
  325. :return: TagReference object """
  326. return TagReference.create(self, path, ref, message, force, **kwargs)
  327. def delete_tag(self, *tags):
  328. """Delete the given tag references"""
  329. return TagReference.delete(self, *tags)
  330. def create_remote(self, name, url, **kwargs):
  331. """Create a new remote.
  332. For more information, please see the documentation of the Remote.create
  333. methods
  334. :return: Remote reference"""
  335. return Remote.create(self, name, url, **kwargs)
  336. def delete_remote(self, remote):
  337. """Delete the given remote."""
  338. return Remote.remove(self, remote)
  339. def _get_config_path(self, config_level):
  340. # we do not support an absolute path of the gitconfig on windows ,
  341. # use the global config instead
  342. if is_win and config_level == "system":
  343. config_level = "global"
  344. if config_level == "system":
  345. return "/etc/gitconfig"
  346. elif config_level == "user":
  347. config_home = os.environ.get("XDG_CONFIG_HOME") or osp.join(os.environ.get("HOME", '~'), ".config")
  348. return osp.normpath(osp.expanduser(osp.join(config_home, "git", "config")))
  349. elif config_level == "global":
  350. return osp.normpath(osp.expanduser("~/.gitconfig"))
  351. elif config_level == "repository":
  352. return osp.normpath(osp.join(self._common_dir or self.git_dir, "config"))
  353. raise ValueError("Invalid configuration level: %r" % config_level)
  354. def config_reader(self, config_level=None):
  355. """
  356. :return:
  357. GitConfigParser allowing to read the full git configuration, but not to write it
  358. The configuration will include values from the system, user and repository
  359. configuration files.
  360. :param config_level:
  361. For possible values, see config_writer method
  362. If None, all applicable levels will be used. Specify a level in case
  363. you know which file you wish to read to prevent reading multiple files.
  364. :note: On windows, system configuration cannot currently be read as the path is
  365. unknown, instead the global path will be used."""
  366. files = None
  367. if config_level is None:
  368. files = [self._get_config_path(f) for f in self.config_level]
  369. else:
  370. files = [self._get_config_path(config_level)]
  371. return GitConfigParser(files, read_only=True)
  372. def config_writer(self, config_level="repository"):
  373. """
  374. :return:
  375. GitConfigParser allowing to write values of the specified configuration file level.
  376. Config writers should be retrieved, used to change the configuration, and written
  377. right away as they will lock the configuration file in question and prevent other's
  378. to write it.
  379. :param config_level:
  380. One of the following values
  381. system = system wide configuration file
  382. global = user level configuration file
  383. repository = configuration file for this repostory only"""
  384. return GitConfigParser(self._get_config_path(config_level), read_only=False)
  385. def commit(self, rev=None):
  386. """The Commit object for the specified revision
  387. :param rev: revision specifier, see git-rev-parse for viable options.
  388. :return: ``git.Commit``"""
  389. if rev is None:
  390. return self.head.commit
  391. else:
  392. return self.rev_parse(text_type(rev) + "^0")
  393. def iter_trees(self, *args, **kwargs):
  394. """:return: Iterator yielding Tree objects
  395. :note: Takes all arguments known to iter_commits method"""
  396. return (c.tree for c in self.iter_commits(*args, **kwargs))
  397. def tree(self, rev=None):
  398. """The Tree object for the given treeish revision
  399. Examples::
  400. repo.tree(repo.heads[0])
  401. :param rev: is a revision pointing to a Treeish ( being a commit or tree )
  402. :return: ``git.Tree``
  403. :note:
  404. If you need a non-root level tree, find it by iterating the root tree. Otherwise
  405. it cannot know about its path relative to the repository root and subsequent
  406. operations might have unexpected results."""
  407. if rev is None:
  408. return self.head.commit.tree
  409. else:
  410. return self.rev_parse(text_type(rev) + "^{tree}")
  411. def iter_commits(self, rev=None, paths='', **kwargs):
  412. """A list of Commit objects representing the history of a given ref/commit
  413. :param rev:
  414. revision specifier, see git-rev-parse for viable options.
  415. If None, the active branch will be used.
  416. :param paths:
  417. is an optional path or a list of paths to limit the returned commits to
  418. Commits that do not contain that path or the paths will not be returned.
  419. :param kwargs:
  420. Arguments to be passed to git-rev-list - common ones are
  421. max_count and skip
  422. :note: to receive only commits between two named revisions, use the
  423. "revA...revB" revision specifier
  424. :return: ``git.Commit[]``"""
  425. if rev is None:
  426. rev = self.head.commit
  427. return Commit.iter_items(self, rev, paths, **kwargs)
  428. def merge_base(self, *rev, **kwargs):
  429. """Find the closest common ancestor for the given revision (e.g. Commits, Tags, References, etc)
  430. :param rev: At least two revs to find the common ancestor for.
  431. :param kwargs: Additional arguments to be passed to the repo.git.merge_base() command which does all the work.
  432. :return: A list of Commit objects. If --all was not specified as kwarg, the list will have at max one Commit,
  433. or is empty if no common merge base exists.
  434. :raises ValueError: If not at least two revs are provided
  435. """
  436. if len(rev) < 2:
  437. raise ValueError("Please specify at least two revs, got only %i" % len(rev))
  438. # end handle input
  439. res = []
  440. try:
  441. lines = self.git.merge_base(*rev, **kwargs).splitlines()
  442. except GitCommandError as err:
  443. if err.status == 128:
  444. raise
  445. # end handle invalid rev
  446. # Status code 1 is returned if there is no merge-base
  447. # (see https://github.com/git/git/blob/master/builtin/merge-base.c#L16)
  448. return res
  449. # end exception handling
  450. for line in lines:
  451. res.append(self.commit(line))
  452. # end for each merge-base
  453. return res
  454. def is_ancestor(self, ancestor_rev, rev):
  455. """Check if a commit is an ancestor of another
  456. :param ancestor_rev: Rev which should be an ancestor
  457. :param rev: Rev to test against ancestor_rev
  458. :return: ``True``, ancestor_rev is an ancestor to rev.
  459. """
  460. try:
  461. self.git.merge_base(ancestor_rev, rev, is_ancestor=True)
  462. except GitCommandError as err:
  463. if err.status == 1:
  464. return False
  465. raise
  466. return True
  467. def _get_daemon_export(self):
  468. filename = osp.join(self.git_dir, self.DAEMON_EXPORT_FILE)
  469. return osp.exists(filename)
  470. def _set_daemon_export(self, value):
  471. filename = osp.join(self.git_dir, self.DAEMON_EXPORT_FILE)
  472. fileexists = osp.exists(filename)
  473. if value and not fileexists:
  474. touch(filename)
  475. elif not value and fileexists:
  476. os.unlink(filename)
  477. daemon_export = property(_get_daemon_export, _set_daemon_export,
  478. doc="If True, git-daemon may export this repository")
  479. del _get_daemon_export
  480. del _set_daemon_export
  481. def _get_alternates(self):
  482. """The list of alternates for this repo from which objects can be retrieved
  483. :return: list of strings being pathnames of alternates"""
  484. alternates_path = osp.join(self.git_dir, 'objects', 'info', 'alternates')
  485. if osp.exists(alternates_path):
  486. with open(alternates_path, 'rb') as f:
  487. alts = f.read().decode(defenc)
  488. return alts.strip().splitlines()
  489. else:
  490. return []
  491. def _set_alternates(self, alts):
  492. """Sets the alternates
  493. :param alts:
  494. is the array of string paths representing the alternates at which
  495. git should look for objects, i.e. /home/user/repo/.git/objects
  496. :raise NoSuchPathError:
  497. :note:
  498. The method does not check for the existence of the paths in alts
  499. as the caller is responsible."""
  500. alternates_path = osp.join(self.common_dir, 'objects', 'info', 'alternates')
  501. if not alts:
  502. if osp.isfile(alternates_path):
  503. os.remove(alternates_path)
  504. else:
  505. with open(alternates_path, 'wb') as f:
  506. f.write("\n".join(alts).encode(defenc))
  507. alternates = property(_get_alternates, _set_alternates,
  508. doc="Retrieve a list of alternates paths or set a list paths to be used as alternates")
  509. def is_dirty(self, index=True, working_tree=True, untracked_files=False,
  510. submodules=True, path=None):
  511. """
  512. :return:
  513. ``True``, the repository is considered dirty. By default it will react
  514. like a git-status without untracked files, hence it is dirty if the
  515. index or the working copy have changes."""
  516. if self._bare:
  517. # Bare repositories with no associated working directory are
  518. # always consired to be clean.
  519. return False
  520. # start from the one which is fastest to evaluate
  521. default_args = ['--abbrev=40', '--full-index', '--raw']
  522. if not submodules:
  523. default_args.append('--ignore-submodules')
  524. if path:
  525. default_args.append(path)
  526. if index:
  527. # diff index against HEAD
  528. if osp.isfile(self.index.path) and \
  529. len(self.git.diff('--cached', *default_args)):
  530. return True
  531. # END index handling
  532. if working_tree:
  533. # diff index against working tree
  534. if len(self.git.diff(*default_args)):
  535. return True
  536. # END working tree handling
  537. if untracked_files:
  538. if len(self._get_untracked_files(path, ignore_submodules=not submodules)):
  539. return True
  540. # END untracked files
  541. return False
  542. @property
  543. def untracked_files(self):
  544. """
  545. :return:
  546. list(str,...)
  547. Files currently untracked as they have not been staged yet. Paths
  548. are relative to the current working directory of the git command.
  549. :note:
  550. ignored files will not appear here, i.e. files mentioned in .gitignore
  551. :note:
  552. This property is expensive, as no cache is involved. To process the result, please
  553. consider caching it yourself."""
  554. return self._get_untracked_files()
  555. def _get_untracked_files(self, *args, **kwargs):
  556. # make sure we get all files, not only untracked directories
  557. proc = self.git.status(*args,
  558. porcelain=True,
  559. untracked_files=True,
  560. as_process=True,
  561. **kwargs)
  562. # Untracked files preffix in porcelain mode
  563. prefix = "?? "
  564. untracked_files = []
  565. for line in proc.stdout:
  566. line = line.decode(defenc)
  567. if not line.startswith(prefix):
  568. continue
  569. filename = line[len(prefix):].rstrip('\n')
  570. # Special characters are escaped
  571. if filename[0] == filename[-1] == '"':
  572. filename = filename[1:-1]
  573. if PY3:
  574. # WHATEVER ... it's a mess, but works for me
  575. filename = filename.encode('ascii').decode('unicode_escape').encode('latin1').decode(defenc)
  576. else:
  577. filename = filename.decode('string_escape').decode(defenc)
  578. untracked_files.append(filename)
  579. finalize_process(proc)
  580. return untracked_files
  581. @property
  582. def active_branch(self):
  583. """The name of the currently active branch.
  584. :return: Head to the active branch"""
  585. return self.head.reference
  586. def blame_incremental(self, rev, file, **kwargs):
  587. """Iterator for blame information for the given file at the given revision.
  588. Unlike .blame(), this does not return the actual file's contents, only
  589. a stream of BlameEntry tuples.
  590. :param rev: revision specifier, see git-rev-parse for viable options.
  591. :return: lazy iterator of BlameEntry tuples, where the commit
  592. indicates the commit to blame for the line, and range
  593. indicates a span of line numbers in the resulting file.
  594. If you combine all line number ranges outputted by this command, you
  595. should get a continuous range spanning all line numbers in the file.
  596. """
  597. data = self.git.blame(rev, '--', file, p=True, incremental=True, stdout_as_string=False, **kwargs)
  598. commits = {}
  599. stream = (line for line in data.split(b'\n') if line)
  600. while True:
  601. try:
  602. line = next(stream) # when exhausted, causes a StopIteration, terminating this function
  603. except StopIteration:
  604. return
  605. hexsha, orig_lineno, lineno, num_lines = line.split()
  606. lineno = int(lineno)
  607. num_lines = int(num_lines)
  608. orig_lineno = int(orig_lineno)
  609. if hexsha not in commits:
  610. # Now read the next few lines and build up a dict of properties
  611. # for this commit
  612. props = {}
  613. while True:
  614. try:
  615. line = next(stream)
  616. except StopIteration:
  617. return
  618. if line == b'boundary':
  619. # "boundary" indicates a root commit and occurs
  620. # instead of the "previous" tag
  621. continue
  622. tag, value = line.split(b' ', 1)
  623. props[tag] = value
  624. if tag == b'filename':
  625. # "filename" formally terminates the entry for --incremental
  626. orig_filename = value
  627. break
  628. c = Commit(self, hex_to_bin(hexsha),
  629. author=Actor(safe_decode(props[b'author']),
  630. safe_decode(props[b'author-mail'].lstrip(b'<').rstrip(b'>'))),
  631. authored_date=int(props[b'author-time']),
  632. committer=Actor(safe_decode(props[b'committer']),
  633. safe_decode(props[b'committer-mail'].lstrip(b'<').rstrip(b'>'))),
  634. committed_date=int(props[b'committer-time']))
  635. commits[hexsha] = c
  636. else:
  637. # Discard all lines until we find "filename" which is
  638. # guaranteed to be the last line
  639. while True:
  640. try:
  641. line = next(stream) # will fail if we reach the EOF unexpectedly
  642. except StopIteration:
  643. return
  644. tag, value = line.split(b' ', 1)
  645. if tag == b'filename':
  646. orig_filename = value
  647. break
  648. yield BlameEntry(commits[hexsha],
  649. range(lineno, lineno + num_lines),
  650. safe_decode(orig_filename),
  651. range(orig_lineno, orig_lineno + num_lines))
  652. def blame(self, rev, file, incremental=False, **kwargs):
  653. """The blame information for the given file at the given revision.
  654. :param rev: revision specifier, see git-rev-parse for viable options.
  655. :return:
  656. list: [git.Commit, list: [<line>]]
  657. A list of tuples associating a Commit object with a list of lines that
  658. changed within the given commit. The Commit objects will be given in order
  659. of appearance."""
  660. if incremental:
  661. return self.blame_incremental(rev, file, **kwargs)
  662. data = self.git.blame(rev, '--', file, p=True, stdout_as_string=False, **kwargs)
  663. commits = {}
  664. blames = []
  665. info = None
  666. keepends = True
  667. for line in data.splitlines(keepends):
  668. try:
  669. line = line.rstrip().decode(defenc)
  670. except UnicodeDecodeError:
  671. firstpart = ''
  672. is_binary = True
  673. else:
  674. # As we don't have an idea when the binary data ends, as it could contain multiple newlines
  675. # in the process. So we rely on being able to decode to tell us what is is.
  676. # This can absolutely fail even on text files, but even if it does, we should be fine treating it
  677. # as binary instead
  678. parts = self.re_whitespace.split(line, 1)
  679. firstpart = parts[0]
  680. is_binary = False
  681. # end handle decode of line
  682. if self.re_hexsha_only.search(firstpart):
  683. # handles
  684. # 634396b2f541a9f2d58b00be1a07f0c358b999b3 1 1 7 - indicates blame-data start
  685. # 634396b2f541a9f2d58b00be1a07f0c358b999b3 2 2 - indicates
  686. # another line of blame with the same data
  687. digits = parts[-1].split(" ")
  688. if len(digits) == 3:
  689. info = {'id': firstpart}
  690. blames.append([None, []])
  691. elif info['id'] != firstpart:
  692. info = {'id': firstpart}
  693. blames.append([commits.get(firstpart), []])
  694. # END blame data initialization
  695. else:
  696. m = self.re_author_committer_start.search(firstpart)
  697. if m:
  698. # handles:
  699. # author Tom Preston-Werner
  700. # author-mail <tom@mojombo.com>
  701. # author-time 1192271832
  702. # author-tz -0700
  703. # committer Tom Preston-Werner
  704. # committer-mail <tom@mojombo.com>
  705. # committer-time 1192271832
  706. # committer-tz -0700 - IGNORED BY US
  707. role = m.group(0)
  708. if firstpart.endswith('-mail'):
  709. info["%s_email" % role] = parts[-1]
  710. elif firstpart.endswith('-time'):
  711. info["%s_date" % role] = int(parts[-1])
  712. elif role == firstpart:
  713. info[role] = parts[-1]
  714. # END distinguish mail,time,name
  715. else:
  716. # handle
  717. # filename lib/grit.rb
  718. # summary add Blob
  719. # <and rest>
  720. if firstpart.startswith('filename'):
  721. info['filename'] = parts[-1]
  722. elif firstpart.startswith('summary'):
  723. info['summary'] = parts[-1]
  724. elif firstpart == '':
  725. if info:
  726. sha = info['id']
  727. c = commits.get(sha)
  728. if c is None:
  729. c = Commit(self, hex_to_bin(sha),
  730. author=Actor._from_string(info['author'] + ' ' + info['author_email']),
  731. authored_date=info['author_date'],
  732. committer=Actor._from_string(
  733. info['committer'] + ' ' + info['committer_email']),
  734. committed_date=info['committer_date'])
  735. commits[sha] = c
  736. # END if commit objects needs initial creation
  737. if not is_binary:
  738. if line and line[0] == '\t':
  739. line = line[1:]
  740. else:
  741. # NOTE: We are actually parsing lines out of binary data, which can lead to the
  742. # binary being split up along the newline separator. We will append this to the blame
  743. # we are currently looking at, even though it should be concatenated with the last line
  744. # we have seen.
  745. pass
  746. # end handle line contents
  747. blames[-1][0] = c
  748. blames[-1][1].append(line)
  749. info = {'id': sha}
  750. # END if we collected commit info
  751. # END distinguish filename,summary,rest
  752. # END distinguish author|committer vs filename,summary,rest
  753. # END distinguish hexsha vs other information
  754. return blames
  755. @classmethod
  756. def init(cls, path=None, mkdir=True, odbt=GitCmdObjectDB, expand_vars=True, **kwargs):
  757. """Initialize a git repository at the given path if specified
  758. :param path:
  759. is the full path to the repo (traditionally ends with /<name>.git)
  760. or None in which case the repository will be created in the current
  761. working directory
  762. :param mkdir:
  763. if specified will create the repository directory if it doesn't
  764. already exists. Creates the directory with a mode=0755.
  765. Only effective if a path is explicitly given
  766. :param odbt:
  767. Object DataBase type - a type which is constructed by providing
  768. the directory containing the database objects, i.e. .git/objects.
  769. It will be used to access all object data
  770. :param expand_vars:
  771. if specified, environment variables will not be escaped. This
  772. can lead to information disclosure, allowing attackers to
  773. access the contents of environment variables
  774. :param kwargs:
  775. keyword arguments serving as additional options to the git-init command
  776. :return: ``git.Repo`` (the newly created repo)"""
  777. if path:
  778. path = expand_path(path, expand_vars)
  779. if mkdir and path and not osp.exists(path):
  780. os.makedirs(path, 0o755)
  781. # git command automatically chdir into the directory
  782. git = Git(path)
  783. git.init(**kwargs)
  784. return cls(path, odbt=odbt)
  785. @classmethod
  786. def _clone(cls, git, url, path, odb_default_type, progress, multi_options=None, **kwargs):
  787. if progress is not None:
  788. progress = to_progress_instance(progress)
  789. odbt = kwargs.pop('odbt', odb_default_type)
  790. # when pathlib.Path or other classbased path is passed
  791. if not isinstance(path, str):
  792. path = str(path)
  793. ## A bug win cygwin's Git, when `--bare` or `--separate-git-dir`
  794. # it prepends the cwd or(?) the `url` into the `path, so::
  795. # git clone --bare /cygwin/d/foo.git C:\\Work
  796. # becomes::
  797. # git clone --bare /cygwin/d/foo.git /cygwin/d/C:\\Work
  798. #
  799. clone_path = (Git.polish_url(path)
  800. if Git.is_cygwin() and 'bare' in kwargs
  801. else path)
  802. sep_dir = kwargs.get('separate_git_dir')
  803. if sep_dir:
  804. kwargs['separate_git_dir'] = Git.polish_url(sep_dir)
  805. multi = None
  806. if multi_options:
  807. multi = ' '.join(multi_options).split(' ')
  808. proc = git.clone(multi, Git.polish_url(url), clone_path, with_extended_output=True, as_process=True,
  809. v=True, universal_newlines=True, **add_progress(kwargs, git, progress))
  810. if progress:
  811. handle_process_output(proc, None, progress.new_message_handler(), finalize_process, decode_streams=False)
  812. else:
  813. (stdout, stderr) = proc.communicate()
  814. log.debug("Cmd(%s)'s unused stdout: %s", getattr(proc, 'args', ''), stdout)
  815. finalize_process(proc, stderr=stderr)
  816. # our git command could have a different working dir than our actual
  817. # environment, hence we prepend its working dir if required
  818. if not osp.isabs(path) and git.working_dir:
  819. path = osp.join(git._working_dir, path)
  820. repo = cls(path, odbt=odbt)
  821. # retain env values that were passed to _clone()
  822. repo.git.update_environment(**git.environment())
  823. # adjust remotes - there may be operating systems which use backslashes,
  824. # These might be given as initial paths, but when handling the config file
  825. # that contains the remote from which we were clones, git stops liking it
  826. # as it will escape the backslashes. Hence we undo the escaping just to be
  827. # sure
  828. if repo.remotes:
  829. with repo.remotes[0].config_writer as writer:
  830. writer.set_value('url', Git.polish_url(repo.remotes[0].url))
  831. # END handle remote repo
  832. return repo
  833. def clone(self, path, progress=None, multi_options=None, **kwargs):
  834. """Create a clone from this repository.
  835. :param path: is the full path of the new repo (traditionally ends with ./<name>.git).
  836. :param progress: See 'git.remote.Remote.push'.
  837. :param multi_options: A list of Clone options that can be provided multiple times. One
  838. option per list item which is passed exactly as specified to clone.
  839. For example ['--config core.filemode=false', '--config core.ignorecase',
  840. '--recurse-submodule=repo1_path', '--recurse-submodule=repo2_path']
  841. :param kwargs:
  842. * odbt = ObjectDatabase Type, allowing to determine the object database
  843. implementation used by the returned Repo instance
  844. * All remaining keyword arguments are given to the git-clone command
  845. :return: ``git.Repo`` (the newly cloned repo)"""
  846. return self._clone(self.git, self.common_dir, path, type(self.odb), progress, multi_options, **kwargs)
  847. @classmethod
  848. def clone_from(cls, url, to_path, progress=None, env=None, multi_options=None, **kwargs):
  849. """Create a clone from the given URL
  850. :param url: valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS
  851. :param to_path: Path to which the repository should be cloned to
  852. :param progress: See 'git.remote.Remote.push'.
  853. :param env: Optional dictionary containing the desired environment variables.
  854. :param multi_options: See ``clone`` method
  855. :param kwargs: see the ``clone`` method
  856. :return: Repo instance pointing to the cloned directory"""
  857. git = Git(os.getcwd())
  858. if env is not None:
  859. git.update_environment(**env)
  860. return cls._clone(git, url, to_path, GitCmdObjectDB, progress, multi_options, **kwargs)
  861. def archive(self, ostream, treeish=None, prefix=None, **kwargs):
  862. """Archive the tree at the given revision.
  863. :param ostream: file compatible stream object to which the archive will be written as bytes
  864. :param treeish: is the treeish name/id, defaults to active branch
  865. :param prefix: is the optional prefix to prepend to each filename in the archive
  866. :param kwargs: Additional arguments passed to git-archive
  867. * Use the 'format' argument to define the kind of format. Use
  868. specialized ostreams to write any format supported by python.
  869. * You may specify the special **path** keyword, which may either be a repository-relative
  870. path to a directory or file to place into the archive, or a list or tuple of multiple paths.
  871. :raise GitCommandError: in case something went wrong
  872. :return: self"""
  873. if treeish is None:
  874. treeish = self.head.commit
  875. if prefix and 'prefix' not in kwargs:
  876. kwargs['prefix'] = prefix
  877. kwargs['output_stream'] = ostream
  878. path = kwargs.pop('path', [])
  879. if not isinstance(path, (tuple, list)):
  880. path = [path]
  881. # end assure paths is list
  882. self.git.archive(treeish, *path, **kwargs)
  883. return self
  884. def has_separate_working_tree(self):
  885. """
  886. :return: True if our git_dir is not at the root of our working_tree_dir, but a .git file with a
  887. platform agnositic symbolic link. Our git_dir will be wherever the .git file points to
  888. :note: bare repositories will always return False here
  889. """
  890. if self.bare:
  891. return False
  892. return osp.isfile(osp.join(self.working_tree_dir, '.git'))
  893. rev_parse = rev_parse
  894. def __repr__(self):
  895. return '<git.Repo "%s">' % self.git_dir
  896. def currently_rebasing_on(self):
  897. """
  898. :return: The commit which is currently being replayed while rebasing.
  899. None if we are not currently rebasing.
  900. """
  901. rebase_head_file = osp.join(self.git_dir, "REBASE_HEAD")
  902. if not osp.isfile(rebase_head_file):
  903. return None
  904. return self.commit(open(rebase_head_file, "rt").readline().strip())