2
0

walk.py 13 KB

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