walk.py 16 KB

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