2
0

walk.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. try:
  20. from collections import defaultdict
  21. except ImportError:
  22. from _compat import defaultdict
  23. import collections
  24. import heapq
  25. import itertools
  26. import os
  27. from dulwich.diff_tree import (
  28. RENAME_CHANGE_TYPES,
  29. tree_changes,
  30. tree_changes_for_merge,
  31. RenameDetector,
  32. )
  33. from dulwich.errors import (
  34. MissingCommitError,
  35. )
  36. ORDER_DATE = 'date'
  37. ORDER_TOPO = 'topo'
  38. ALL_ORDERS = (ORDER_DATE, ORDER_TOPO)
  39. # Maximum number of commits to walk past a commit time boundary.
  40. _MAX_EXTRA_COMMITS = 5
  41. class WalkEntry(object):
  42. """Object encapsulating a single result from a walk."""
  43. def __init__(self, walker, commit):
  44. self.commit = commit
  45. self._store = walker.store
  46. self._changes = None
  47. self._rename_detector = walker.rename_detector
  48. def changes(self):
  49. """Get the tree changes for this entry.
  50. :return: For commits with up to one parent, a list of TreeChange
  51. objects; if the commit has no parents, these will be relative to the
  52. empty tree. For merge commits, a list of lists of TreeChange
  53. objects; see dulwich.diff.tree_changes_for_merge.
  54. """
  55. if self._changes is None:
  56. commit = self.commit
  57. if not commit.parents:
  58. changes_func = tree_changes
  59. parent = None
  60. elif len(commit.parents) == 1:
  61. changes_func = tree_changes
  62. parent = self._store[commit.parents[0]].tree
  63. else:
  64. changes_func = tree_changes_for_merge
  65. parent = [self._store[p].tree for p in commit.parents]
  66. self._changes = list(changes_func(
  67. self._store, parent, commit.tree,
  68. rename_detector=self._rename_detector))
  69. return self._changes
  70. def __repr__(self):
  71. return '<WalkEntry commit=%s, changes=%r>' % (
  72. self.commit.id, self.changes())
  73. class _CommitTimeQueue(object):
  74. """Priority queue of WalkEntry objects by commit time."""
  75. def __init__(self, walker):
  76. self._walker = walker
  77. self._store = walker.store
  78. self._excluded = walker.excluded
  79. self._pq = []
  80. self._pq_set = set()
  81. self._done = set()
  82. self._min_time = walker.since
  83. self._extra_commits_left = _MAX_EXTRA_COMMITS
  84. self._is_finished = False
  85. for commit_id in itertools.chain(walker.include, walker.excluded):
  86. self._push(commit_id)
  87. def _push(self, commit_id):
  88. try:
  89. commit = self._store[commit_id]
  90. except KeyError:
  91. raise MissingCommitError(commit_id)
  92. if commit_id not in self._pq_set and commit_id not in self._done:
  93. heapq.heappush(self._pq, (-commit.commit_time, commit))
  94. self._pq_set.add(commit_id)
  95. def next(self):
  96. if self._is_finished:
  97. return None
  98. while self._pq:
  99. _, commit = heapq.heappop(self._pq)
  100. sha = commit.id
  101. self._pq_set.remove(sha)
  102. if sha in self._done:
  103. continue
  104. is_excluded = sha in self._excluded
  105. if is_excluded:
  106. self._excluded.update(commit.parents)
  107. self._done.add(commit.id)
  108. if self._min_time is not None:
  109. if commit.commit_time < self._min_time:
  110. # We want to stop walking at min_time, but commits at the
  111. # boundary may be out of order with respect to their
  112. # parents. So we walk _MAX_EXTRA_COMMITS more commits once
  113. # we hit this boundary.
  114. self._extra_commits_left -= 1
  115. if not self._extra_commits_left:
  116. break
  117. else:
  118. # We're not at a boundary, so reset the counter.
  119. self._extra_commits_left = _MAX_EXTRA_COMMITS
  120. for parent_id in commit.parents:
  121. self._push(parent_id)
  122. if not is_excluded:
  123. return WalkEntry(self._walker, commit)
  124. self._is_finished = True
  125. return None
  126. class Walker(object):
  127. """Object for performing a walk of commits in a store.
  128. Walker objects are initialized with a store and other options and can then
  129. be treated as iterators of Commit objects.
  130. """
  131. def __init__(self, store, include, exclude=None, order=ORDER_DATE,
  132. reverse=False, max_entries=None, paths=None,
  133. rename_detector=None, follow=False, since=None, until=None,
  134. queue_cls=_CommitTimeQueue):
  135. """Constructor.
  136. :param store: ObjectStore instance for looking up objects.
  137. :param include: Iterable of SHAs of commits to include along with their
  138. ancestors.
  139. :param exclude: Iterable of SHAs of commits to exclude along with their
  140. ancestors, overriding includes.
  141. :param order: ORDER_* constant specifying the order of results. Anything
  142. other than ORDER_DATE may result in O(n) memory usage.
  143. :param reverse: If True, reverse the order of output, requiring O(n)
  144. memory.
  145. :param max_entries: The maximum number of entries to yield, or None for
  146. no limit.
  147. :param paths: Iterable of file or subtree paths to show entries for.
  148. :param rename_detector: diff.RenameDetector object for detecting
  149. renames.
  150. :param follow: If True, follow path across renames/copies. Forces a
  151. default rename_detector.
  152. :param since: Timestamp to list commits after.
  153. :param until: Timestamp to list commits before.
  154. :param queue_cls: A class to use for a queue of commits, supporting the
  155. iterator protocol. The constructor takes a single argument, the
  156. Walker.
  157. """
  158. if order not in ALL_ORDERS:
  159. raise ValueError('Unknown walk order %s' % order)
  160. self.store = store
  161. self.include = include
  162. self.excluded = set(exclude or [])
  163. self.order = order
  164. self.reverse = reverse
  165. self.max_entries = max_entries
  166. self.paths = paths and set(paths) or None
  167. if follow and not rename_detector:
  168. rename_detector = RenameDetector(store)
  169. self.rename_detector = rename_detector
  170. self.follow = follow
  171. self.since = since
  172. self.until = until
  173. self._num_entries = 0
  174. self._queue = queue_cls(self)
  175. self._out_queue = collections.deque()
  176. def _path_matches(self, changed_path):
  177. if changed_path is None:
  178. return False
  179. for followed_path in self.paths:
  180. if changed_path == followed_path:
  181. return True
  182. if (changed_path.startswith(followed_path) and
  183. changed_path[len(followed_path)] == '/'):
  184. return True
  185. return False
  186. def _change_matches(self, change):
  187. old_path = change.old.path
  188. new_path = change.new.path
  189. if self._path_matches(new_path):
  190. if self.follow and change.type in RENAME_CHANGE_TYPES:
  191. self.paths.add(old_path)
  192. self.paths.remove(new_path)
  193. return True
  194. elif self._path_matches(old_path):
  195. return True
  196. return False
  197. def _should_return(self, entry):
  198. """Determine if a walk entry should be returned..
  199. :param entry: The WalkEntry to consider.
  200. :return: True if the WalkEntry should be returned by this walk, or False
  201. otherwise (e.g. if it doesn't match any requested paths).
  202. """
  203. commit = entry.commit
  204. if self.since is not None and commit.commit_time < self.since:
  205. return False
  206. if self.until is not None and commit.commit_time > self.until:
  207. return False
  208. if self.paths is None:
  209. return True
  210. if len(commit.parents) > 1:
  211. for path_changes in entry.changes():
  212. # For merge commits, only include changes with conflicts for
  213. # this path. Since a rename conflict may include different
  214. # old.paths, we have to check all of them.
  215. for change in path_changes:
  216. if self._change_matches(change):
  217. return True
  218. else:
  219. for change in entry.changes():
  220. if self._change_matches(change):
  221. return True
  222. return None
  223. def _next(self):
  224. max_entries = self.max_entries
  225. while max_entries is None or self._num_entries < max_entries:
  226. entry = self._queue.next()
  227. if entry is not None:
  228. self._out_queue.append(entry)
  229. if entry is None or len(self._out_queue) > _MAX_EXTRA_COMMITS:
  230. if not self._out_queue:
  231. return None
  232. entry = self._out_queue.popleft()
  233. if self._should_return(entry):
  234. self._num_entries += 1
  235. return entry
  236. return None
  237. def _reorder(self, results):
  238. """Possibly reorder a results iterator.
  239. :param results: An iterator of WalkEntry objects, in the order returned
  240. from the queue_cls.
  241. :return: An iterator or list of WalkEntry objects, in the order required
  242. by the Walker.
  243. """
  244. if self.order == ORDER_TOPO:
  245. results = _topo_reorder(results)
  246. if self.reverse:
  247. results = reversed(list(results))
  248. return results
  249. def __iter__(self):
  250. return iter(self._reorder(iter(self._next, None)))
  251. def _topo_reorder(entries):
  252. """Reorder an iterable of entries topologically.
  253. This works best assuming the entries are already in almost-topological
  254. order, e.g. in commit time order.
  255. :param entries: An iterable of WalkEntry objects.
  256. :yield: WalkEntry objects from entries in FIFO order, except where a parent
  257. would be yielded before any of its children.
  258. """
  259. todo = collections.deque()
  260. pending = {}
  261. num_children = defaultdict(int)
  262. for entry in entries:
  263. todo.append(entry)
  264. for p in entry.commit.parents:
  265. num_children[p] += 1
  266. while todo:
  267. entry = todo.popleft()
  268. commit = entry.commit
  269. commit_id = commit.id
  270. if num_children[commit_id]:
  271. pending[commit_id] = entry
  272. continue
  273. for parent_id in commit.parents:
  274. num_children[parent_id] -= 1
  275. if not num_children[parent_id]:
  276. parent_entry = pending.pop(parent_id, None)
  277. if parent_entry:
  278. todo.appendleft(parent_entry)
  279. yield entry