walk.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. # walk.py -- General implementation of walking commits and their contents.
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """General implementation of walking commits and their contents."""
  21. from collections import defaultdict
  22. import collections
  23. import heapq
  24. from itertools import chain
  25. from dulwich.diff_tree import (
  26. RENAME_CHANGE_TYPES,
  27. tree_changes,
  28. tree_changes_for_merge,
  29. RenameDetector,
  30. )
  31. from dulwich.errors import (
  32. MissingCommitError,
  33. )
  34. ORDER_DATE = 'date'
  35. ORDER_TOPO = 'topo'
  36. ALL_ORDERS = (ORDER_DATE, ORDER_TOPO)
  37. # Maximum number of commits to walk past a commit time boundary.
  38. _MAX_EXTRA_COMMITS = 5
  39. class WalkEntry(object):
  40. """Object encapsulating a single result from a walk."""
  41. def __init__(self, walker, commit):
  42. self.commit = commit
  43. self._store = walker.store
  44. self._get_parents = walker.get_parents
  45. self._changes = {}
  46. self._rename_detector = walker.rename_detector
  47. def changes(self, path_prefix=None):
  48. """Get the tree changes for this entry.
  49. :param path_prefix: Portion of the path in the repository to
  50. use to filter changes. Must be a directory name. Must be
  51. a full, valid, path reference (no partial names or wildcards).
  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. cached = self._changes.get(path_prefix)
  58. if cached is None:
  59. commit = self.commit
  60. if not self._get_parents(commit):
  61. changes_func = tree_changes
  62. parent = None
  63. elif len(self._get_parents(commit)) == 1:
  64. changes_func = tree_changes
  65. parent = self._store[self._get_parents(commit)[0]].tree
  66. if path_prefix:
  67. mode, subtree_sha = parent.lookup_path(
  68. self._store.__getitem__,
  69. path_prefix,
  70. )
  71. parent = self._store[subtree_sha]
  72. else:
  73. changes_func = tree_changes_for_merge
  74. parent = [self._store[p].tree for p in self._get_parents(commit)]
  75. if path_prefix:
  76. parent_trees = [self._store[p] for p in parent]
  77. parent = []
  78. for p in parent_trees:
  79. try:
  80. mode, st = p.lookup_path(
  81. self._store.__getitem__,
  82. path_prefix,
  83. )
  84. except KeyError:
  85. pass
  86. else:
  87. parent.append(st)
  88. commit_tree_sha = commit.tree
  89. if path_prefix:
  90. commit_tree = self._store[commit_tree_sha]
  91. mode, commit_tree_sha = commit_tree.lookup_path(
  92. self._store.__getitem__,
  93. path_prefix,
  94. )
  95. cached = list(changes_func(
  96. self._store, parent, commit_tree_sha,
  97. rename_detector=self._rename_detector))
  98. self._changes[path_prefix] = cached
  99. return self._changes[path_prefix]
  100. def __repr__(self):
  101. return '<WalkEntry commit=%s, changes=%r>' % (
  102. self.commit.id, self.changes())
  103. class _CommitTimeQueue(object):
  104. """Priority queue of WalkEntry objects by commit time."""
  105. def __init__(self, walker):
  106. self._walker = walker
  107. self._store = walker.store
  108. self._get_parents = walker.get_parents
  109. self._excluded = walker.excluded
  110. self._pq = []
  111. self._pq_set = set()
  112. self._seen = set()
  113. self._done = set()
  114. self._min_time = walker.since
  115. self._last = None
  116. self._extra_commits_left = _MAX_EXTRA_COMMITS
  117. self._is_finished = False
  118. for commit_id in chain(walker.include, walker.excluded):
  119. self._push(commit_id)
  120. def _push(self, commit_id):
  121. try:
  122. commit = self._store[commit_id]
  123. except KeyError:
  124. raise MissingCommitError(commit_id)
  125. if commit_id not in self._pq_set and commit_id not in self._done:
  126. heapq.heappush(self._pq, (-commit.commit_time, commit))
  127. self._pq_set.add(commit_id)
  128. self._seen.add(commit_id)
  129. def _exclude_parents(self, commit):
  130. excluded = self._excluded
  131. seen = self._seen
  132. todo = [commit]
  133. while todo:
  134. commit = todo.pop()
  135. for parent in self._get_parents(commit):
  136. if parent not in excluded and parent in seen:
  137. # TODO: This is inefficient unless the object store does
  138. # some caching (which DiskObjectStore currently does not).
  139. # We could either add caching in this class or pass around
  140. # parsed queue entry objects instead of commits.
  141. todo.append(self._store[parent])
  142. excluded.add(parent)
  143. def next(self):
  144. if self._is_finished:
  145. return None
  146. while self._pq:
  147. _, commit = heapq.heappop(self._pq)
  148. sha = commit.id
  149. self._pq_set.remove(sha)
  150. if sha in self._done:
  151. continue
  152. self._done.add(sha)
  153. for parent_id in self._get_parents(commit):
  154. self._push(parent_id)
  155. reset_extra_commits = True
  156. is_excluded = sha in self._excluded
  157. if is_excluded:
  158. self._exclude_parents(commit)
  159. if self._pq and all(c.id in self._excluded
  160. for _, c in self._pq):
  161. _, n = self._pq[0]
  162. if self._last and n.commit_time >= self._last.commit_time:
  163. # If the next commit is newer than the last one, we need
  164. # to keep walking in case its parents (which we may not
  165. # have seen yet) are excluded. This gives the excluded
  166. # set a chance to "catch up" while the commit is still
  167. # in the Walker's output queue.
  168. reset_extra_commits = True
  169. else:
  170. reset_extra_commits = False
  171. if (self._min_time is not None and
  172. commit.commit_time < self._min_time):
  173. # We want to stop walking at min_time, but commits at the
  174. # boundary may be out of order with respect to their parents. So
  175. # we walk _MAX_EXTRA_COMMITS more commits once we hit this
  176. # boundary.
  177. reset_extra_commits = False
  178. if reset_extra_commits:
  179. # We're not at a boundary, so reset the counter.
  180. self._extra_commits_left = _MAX_EXTRA_COMMITS
  181. else:
  182. self._extra_commits_left -= 1
  183. if not self._extra_commits_left:
  184. break
  185. if not is_excluded:
  186. self._last = commit
  187. return WalkEntry(self._walker, commit)
  188. self._is_finished = True
  189. return None
  190. __next__ = next
  191. class Walker(object):
  192. """Object for performing a walk of commits in a store.
  193. Walker objects are initialized with a store and other options and can then
  194. be treated as iterators of Commit objects.
  195. """
  196. def __init__(self, store, include, exclude=None, order=ORDER_DATE,
  197. reverse=False, max_entries=None, paths=None,
  198. rename_detector=None, follow=False, since=None, until=None,
  199. get_parents=lambda commit: commit.parents,
  200. queue_cls=_CommitTimeQueue):
  201. """Constructor.
  202. :param store: ObjectStore instance for looking up objects.
  203. :param include: Iterable of SHAs of commits to include along with their
  204. ancestors.
  205. :param exclude: Iterable of SHAs of commits to exclude along with their
  206. ancestors, overriding includes.
  207. :param order: ORDER_* constant specifying the order of results. Anything
  208. other than ORDER_DATE may result in O(n) memory usage.
  209. :param reverse: If True, reverse the order of output, requiring O(n)
  210. memory.
  211. :param max_entries: The maximum number of entries to yield, or None for
  212. no limit.
  213. :param paths: Iterable of file or subtree paths to show entries for.
  214. :param rename_detector: diff.RenameDetector object for detecting
  215. renames.
  216. :param follow: If True, follow path across renames/copies. Forces a
  217. default rename_detector.
  218. :param since: Timestamp to list commits after.
  219. :param until: Timestamp to list commits before.
  220. :param get_parents: Method to retrieve the parents of a commit
  221. :param queue_cls: A class to use for a queue of commits, supporting the
  222. iterator protocol. The constructor takes a single argument, the
  223. Walker.
  224. """
  225. # Note: when adding arguments to this method, please also update
  226. # dulwich.repo.BaseRepo.get_walker
  227. if order not in ALL_ORDERS:
  228. raise ValueError('Unknown walk order %s' % order)
  229. self.store = store
  230. if not isinstance(include, list):
  231. include = [include]
  232. self.include = include
  233. self.excluded = set(exclude or [])
  234. self.order = order
  235. self.reverse = reverse
  236. self.max_entries = max_entries
  237. self.paths = paths and set(paths) or None
  238. if follow and not rename_detector:
  239. rename_detector = RenameDetector(store)
  240. self.rename_detector = rename_detector
  241. self.get_parents = get_parents
  242. self.follow = follow
  243. self.since = since
  244. self.until = until
  245. self._num_entries = 0
  246. self._queue = queue_cls(self)
  247. self._out_queue = collections.deque()
  248. def _path_matches(self, changed_path):
  249. if changed_path is None:
  250. return False
  251. for followed_path in self.paths:
  252. if changed_path == followed_path:
  253. return True
  254. if (changed_path.startswith(followed_path) and
  255. changed_path[len(followed_path)] == b'/'[0]):
  256. return True
  257. return False
  258. def _change_matches(self, change):
  259. if not change:
  260. return False
  261. old_path = change.old.path
  262. new_path = change.new.path
  263. if self._path_matches(new_path):
  264. if self.follow and change.type in RENAME_CHANGE_TYPES:
  265. self.paths.add(old_path)
  266. self.paths.remove(new_path)
  267. return True
  268. elif self._path_matches(old_path):
  269. return True
  270. return False
  271. def _should_return(self, entry):
  272. """Determine if a walk entry should be returned..
  273. :param entry: The WalkEntry to consider.
  274. :return: True if the WalkEntry should be returned by this walk, or False
  275. otherwise (e.g. if it doesn't match any requested paths).
  276. """
  277. commit = entry.commit
  278. if self.since is not None and commit.commit_time < self.since:
  279. return False
  280. if self.until is not None and commit.commit_time > self.until:
  281. return False
  282. if commit.id in self.excluded:
  283. return False
  284. if self.paths is None:
  285. return True
  286. if len(self.get_parents(commit)) > 1:
  287. for path_changes in entry.changes():
  288. # For merge commits, only include changes with conflicts for
  289. # this path. Since a rename conflict may include different
  290. # old.paths, we have to check all of them.
  291. for change in path_changes:
  292. if self._change_matches(change):
  293. return True
  294. else:
  295. for change in entry.changes():
  296. if self._change_matches(change):
  297. return True
  298. return None
  299. def _next(self):
  300. max_entries = self.max_entries
  301. while max_entries is None or self._num_entries < max_entries:
  302. entry = next(self._queue)
  303. if entry is not None:
  304. self._out_queue.append(entry)
  305. if entry is None or len(self._out_queue) > _MAX_EXTRA_COMMITS:
  306. if not self._out_queue:
  307. return None
  308. entry = self._out_queue.popleft()
  309. if self._should_return(entry):
  310. self._num_entries += 1
  311. return entry
  312. return None
  313. def _reorder(self, results):
  314. """Possibly reorder a results iterator.
  315. :param results: An iterator of WalkEntry objects, in the order returned
  316. from the queue_cls.
  317. :return: An iterator or list of WalkEntry objects, in the order required
  318. by the Walker.
  319. """
  320. if self.order == ORDER_TOPO:
  321. results = _topo_reorder(results, self.get_parents)
  322. if self.reverse:
  323. results = reversed(list(results))
  324. return results
  325. def __iter__(self):
  326. return iter(self._reorder(iter(self._next, None)))
  327. def _topo_reorder(entries, get_parents=lambda commit: commit.parents):
  328. """Reorder an iterable of entries topologically.
  329. This works best assuming the entries are already in almost-topological
  330. order, e.g. in commit time order.
  331. :param entries: An iterable of WalkEntry objects.
  332. :param get_parents: Optional function for getting the parents of a commit.
  333. :return: iterator over WalkEntry objects from entries in FIFO order, except
  334. where a parent would be yielded before any of its children.
  335. """
  336. todo = collections.deque()
  337. pending = {}
  338. num_children = defaultdict(int)
  339. for entry in entries:
  340. todo.append(entry)
  341. for p in get_parents(entry.commit):
  342. num_children[p] += 1
  343. while todo:
  344. entry = todo.popleft()
  345. commit = entry.commit
  346. commit_id = commit.id
  347. if num_children[commit_id]:
  348. pending[commit_id] = entry
  349. continue
  350. for parent_id in get_parents(commit):
  351. num_children[parent_id] -= 1
  352. if not num_children[parent_id]:
  353. parent_entry = pending.pop(parent_id, None)
  354. if parent_entry:
  355. todo.appendleft(parent_entry)
  356. yield entry