walk.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. # walk.py -- General implementation of walking commits and their contents.
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # or (at your option) any later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """General implementation of walking commits and their contents."""
  19. import heapq
  20. import itertools
  21. import os
  22. from dulwich.diff_tree import (
  23. RENAME_CHANGE_TYPES,
  24. tree_changes,
  25. tree_changes_for_merge,
  26. RenameDetector,
  27. )
  28. from dulwich.errors import (
  29. MissingCommitError,
  30. )
  31. ORDER_DATE = 'date'
  32. # Maximum number of commits to walk past a commit time boundary.
  33. _MAX_EXTRA_COMMITS = 5
  34. class WalkEntry(object):
  35. """Object encapsulating a single result from a walk."""
  36. def __init__(self, store, commit, rename_detector):
  37. self.commit = commit
  38. self._store = store
  39. self._changes = None
  40. self._rename_detector = rename_detector
  41. def changes(self):
  42. """Get the tree changes for this entry.
  43. :return: For commits with up to one parent, a list of TreeChange
  44. objects; if the commit has no parents, these will be relative to the
  45. empty tree. For merge commits, a list of lists of TreeChange
  46. objects; see dulwich.diff.tree_changes_for_merge.
  47. """
  48. if self._changes is None:
  49. commit = self.commit
  50. if not commit.parents:
  51. changes_func = tree_changes
  52. parent = None
  53. elif len(commit.parents) == 1:
  54. changes_func = tree_changes
  55. parent = self._store[commit.parents[0]].tree
  56. else:
  57. changes_func = tree_changes_for_merge
  58. parent = [self._store[p].tree for p in commit.parents]
  59. self._changes = list(changes_func(
  60. self._store, parent, commit.tree,
  61. rename_detector=self._rename_detector))
  62. return self._changes
  63. def __repr__(self):
  64. return '<WalkEntry commit=%s, changes=%r>' % (
  65. self.commit.id, self.changes())
  66. class Walker(object):
  67. """Object for performing a walk of commits in a store.
  68. Walker objects are initialized with a store and other options and can then
  69. be treated as iterators of Commit objects.
  70. """
  71. def __init__(self, store, include, exclude=None, order=ORDER_DATE,
  72. reverse=False, max_entries=None, paths=None,
  73. rename_detector=None, follow=False, since=None, until=None):
  74. """Constructor.
  75. :param store: ObjectStore instance for looking up objects.
  76. :param include: Iterable of SHAs of commits to include along with their
  77. ancestors.
  78. :param exclude: Iterable of SHAs of commits to exclude along with their
  79. ancestors, overriding includes.
  80. :param order: ORDER_* constant specifying the order of results. Anything
  81. other than ORDER_DATE may result in O(n) memory usage.
  82. :param reverse: If True, reverse the order of output, requiring O(n)
  83. memory.
  84. :param max_entries: The maximum number of entries to yield, or None for
  85. no limit.
  86. :param paths: Iterable of file or subtree paths to show entries for.
  87. :param rename_detector: diff.RenameDetector object for detecting
  88. renames.
  89. :param follow: If True, follow path across renames/copies. Forces a
  90. default rename_detector.
  91. :param since: Timestamp to list commits after.
  92. :param until: Timestamp to list commits before.
  93. """
  94. self._store = store
  95. if order not in (ORDER_DATE,):
  96. raise ValueError('Unknown walk order %s' % order)
  97. self._order = order
  98. self._reverse = reverse
  99. self._max_entries = max_entries
  100. self._num_entries = 0
  101. if follow and not rename_detector:
  102. rename_detector = RenameDetector(store)
  103. self._rename_detector = rename_detector
  104. exclude = exclude or []
  105. self._excluded = set(exclude)
  106. self._pq = []
  107. self._pq_set = set()
  108. self._done = set()
  109. self._paths = paths and set(paths) or None
  110. self._follow = follow
  111. self._since = since
  112. self._until = until
  113. self._extra_commits_left = _MAX_EXTRA_COMMITS
  114. for commit_id in itertools.chain(include, exclude):
  115. self._push(commit_id)
  116. def _push(self, commit_id):
  117. try:
  118. commit = self._store[commit_id]
  119. except KeyError:
  120. raise MissingCommitError(commit_id)
  121. if commit_id not in self._pq_set and commit_id not in self._done:
  122. heapq.heappush(self._pq, (-commit.commit_time, commit))
  123. self._pq_set.add(commit_id)
  124. def _pop(self):
  125. while self._pq:
  126. _, commit = heapq.heappop(self._pq)
  127. sha = commit.id
  128. self._pq_set.remove(sha)
  129. if sha in self._done:
  130. continue
  131. is_excluded = sha in self._excluded
  132. if is_excluded:
  133. self._excluded.update(commit.parents)
  134. self._done.add(commit.id)
  135. if self._since is not None:
  136. if commit.commit_time < self._since:
  137. # We want to stop walking at since, but commits at the
  138. # boundary may be out of order with respect to their
  139. # parents. So we walk _MAX_EXTRA_COMMITS more commits once
  140. # we hit this boundary.
  141. self._extra_commits_left -= 1
  142. if not self._extra_commits_left:
  143. break
  144. else:
  145. # We're not at a boundary, so reset the counter.
  146. self._extra_commits_left = _MAX_EXTRA_COMMITS
  147. for parent_id in commit.parents:
  148. self._push(parent_id)
  149. if not is_excluded:
  150. return commit
  151. return None
  152. def _path_matches(self, changed_path):
  153. if changed_path is None:
  154. return False
  155. for followed_path in self._paths:
  156. if changed_path == followed_path:
  157. return True
  158. if (changed_path.startswith(followed_path) and
  159. changed_path[len(followed_path)] == '/'):
  160. return True
  161. return False
  162. def _change_matches(self, change):
  163. old_path = change.old.path
  164. new_path = change.new.path
  165. if self._path_matches(new_path):
  166. if self._follow and change.type in RENAME_CHANGE_TYPES:
  167. self._paths.add(old_path)
  168. self._paths.remove(new_path)
  169. return True
  170. elif self._path_matches(old_path):
  171. return True
  172. return False
  173. def _make_entry(self, commit):
  174. """Make a WalkEntry from a commit.
  175. :param commit: The commit for the WalkEntry.
  176. :return: A WalkEntry object, or None if no entry should be returned for
  177. this commit (e.g. if it doesn't match any requested paths).
  178. """
  179. if self._since is not None and commit.commit_time < self._since:
  180. return None
  181. if self._until is not None and commit.commit_time > self._until:
  182. return None
  183. entry = WalkEntry(self._store, commit, self._rename_detector)
  184. if self._paths is None:
  185. return entry
  186. if len(commit.parents) > 1:
  187. for path_changes in entry.changes():
  188. # For merge commits, only include changes with conflicts for
  189. # this path. Since a rename conflict may include different
  190. # old.paths, we have to check all of them.
  191. for change in path_changes:
  192. if self._change_matches(change):
  193. return entry
  194. else:
  195. for change in entry.changes():
  196. if self._change_matches(change):
  197. return entry
  198. return None
  199. def _next(self):
  200. max_entries = self._max_entries
  201. while True:
  202. if max_entries is not None and self._num_entries >= max_entries:
  203. return None
  204. commit = self._pop()
  205. if commit is None:
  206. return None
  207. entry = self._make_entry(commit)
  208. if entry:
  209. self._num_entries += 1
  210. return entry
  211. def __iter__(self):
  212. results = iter(self._next, None)
  213. if self._reverse:
  214. results = reversed(list(results))
  215. return iter(results)