walk.py 14 KB

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