revision.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. import re
  2. import collections
  3. from .. import util
  4. from sqlalchemy import util as sqlautil
  5. from ..util import compat
  6. _relative_destination = re.compile(r'(?:(.+?)@)?(\w+)?((?:\+|-)\d+)')
  7. class RevisionError(Exception):
  8. pass
  9. class RangeNotAncestorError(RevisionError):
  10. def __init__(self, lower, upper):
  11. self.lower = lower
  12. self.upper = upper
  13. super(RangeNotAncestorError, self).__init__(
  14. "Revision %s is not an ancestor of revision %s" %
  15. (lower or "base", upper or "base")
  16. )
  17. class MultipleHeads(RevisionError):
  18. def __init__(self, heads, argument):
  19. self.heads = heads
  20. self.argument = argument
  21. super(MultipleHeads, self).__init__(
  22. "Multiple heads are present for given argument '%s'; "
  23. "%s" % (argument, ", ".join(heads))
  24. )
  25. class ResolutionError(RevisionError):
  26. def __init__(self, message, argument):
  27. super(ResolutionError, self).__init__(message)
  28. self.argument = argument
  29. class RevisionMap(object):
  30. """Maintains a map of :class:`.Revision` objects.
  31. :class:`.RevisionMap` is used by :class:`.ScriptDirectory` to maintain
  32. and traverse the collection of :class:`.Script` objects, which are
  33. themselves instances of :class:`.Revision`.
  34. """
  35. def __init__(self, generator):
  36. """Construct a new :class:`.RevisionMap`.
  37. :param generator: a zero-arg callable that will generate an iterable
  38. of :class:`.Revision` instances to be used. These are typically
  39. :class:`.Script` subclasses within regular Alembic use.
  40. """
  41. self._generator = generator
  42. @util.memoized_property
  43. def heads(self):
  44. """All "head" revisions as strings.
  45. This is normally a tuple of length one,
  46. unless unmerged branches are present.
  47. :return: a tuple of string revision numbers.
  48. """
  49. self._revision_map
  50. return self.heads
  51. @util.memoized_property
  52. def bases(self):
  53. """All "base" revisions as strings.
  54. These are revisions that have a ``down_revision`` of None,
  55. or empty tuple.
  56. :return: a tuple of string revision numbers.
  57. """
  58. self._revision_map
  59. return self.bases
  60. @util.memoized_property
  61. def _real_heads(self):
  62. """All "real" head revisions as strings.
  63. :return: a tuple of string revision numbers.
  64. """
  65. self._revision_map
  66. return self._real_heads
  67. @util.memoized_property
  68. def _real_bases(self):
  69. """All "real" base revisions as strings.
  70. :return: a tuple of string revision numbers.
  71. """
  72. self._revision_map
  73. return self._real_bases
  74. @util.memoized_property
  75. def _revision_map(self):
  76. """memoized attribute, initializes the revision map from the
  77. initial collection.
  78. """
  79. map_ = {}
  80. heads = sqlautil.OrderedSet()
  81. _real_heads = sqlautil.OrderedSet()
  82. self.bases = ()
  83. self._real_bases = ()
  84. has_branch_labels = set()
  85. has_depends_on = set()
  86. for revision in self._generator():
  87. if revision.revision in map_:
  88. util.warn("Revision %s is present more than once" %
  89. revision.revision)
  90. map_[revision.revision] = revision
  91. if revision.branch_labels:
  92. has_branch_labels.add(revision)
  93. if revision.dependencies:
  94. has_depends_on.add(revision)
  95. heads.add(revision.revision)
  96. _real_heads.add(revision.revision)
  97. if revision.is_base:
  98. self.bases += (revision.revision, )
  99. if revision._is_real_base:
  100. self._real_bases += (revision.revision, )
  101. # add the branch_labels to the map_. We'll need these
  102. # to resolve the dependencies.
  103. for revision in has_branch_labels:
  104. self._map_branch_labels(revision, map_)
  105. for revision in has_depends_on:
  106. self._add_depends_on(revision, map_)
  107. for rev in map_.values():
  108. for downrev in rev._all_down_revisions:
  109. if downrev not in map_:
  110. util.warn("Revision %s referenced from %s is not present"
  111. % (downrev, rev))
  112. down_revision = map_[downrev]
  113. down_revision.add_nextrev(rev)
  114. if downrev in rev._versioned_down_revisions:
  115. heads.discard(downrev)
  116. _real_heads.discard(downrev)
  117. map_[None] = map_[()] = None
  118. self.heads = tuple(heads)
  119. self._real_heads = tuple(_real_heads)
  120. for revision in has_branch_labels:
  121. self._add_branches(revision, map_, map_branch_labels=False)
  122. return map_
  123. def _map_branch_labels(self, revision, map_):
  124. if revision.branch_labels:
  125. for branch_label in revision._orig_branch_labels:
  126. if branch_label in map_:
  127. raise RevisionError(
  128. "Branch name '%s' in revision %s already "
  129. "used by revision %s" %
  130. (branch_label, revision.revision,
  131. map_[branch_label].revision)
  132. )
  133. map_[branch_label] = revision
  134. def _add_branches(self, revision, map_, map_branch_labels=True):
  135. if map_branch_labels:
  136. self._map_branch_labels(revision, map_)
  137. if revision.branch_labels:
  138. revision.branch_labels.update(revision.branch_labels)
  139. for node in self._get_descendant_nodes(
  140. [revision], map_, include_dependencies=False):
  141. node.branch_labels.update(revision.branch_labels)
  142. parent = node
  143. while parent and \
  144. not parent._is_real_branch_point and \
  145. not parent.is_merge_point:
  146. parent.branch_labels.update(revision.branch_labels)
  147. if parent.down_revision:
  148. parent = map_[parent.down_revision]
  149. else:
  150. break
  151. def _add_depends_on(self, revision, map_):
  152. if revision.dependencies:
  153. deps = [map_[dep] for dep in util.to_tuple(revision.dependencies)]
  154. revision._resolved_dependencies = tuple([d.revision for d in deps])
  155. def add_revision(self, revision, _replace=False):
  156. """add a single revision to an existing map.
  157. This method is for single-revision use cases, it's not
  158. appropriate for fully populating an entire revision map.
  159. """
  160. map_ = self._revision_map
  161. if not _replace and revision.revision in map_:
  162. util.warn("Revision %s is present more than once" %
  163. revision.revision)
  164. elif _replace and revision.revision not in map_:
  165. raise Exception("revision %s not in map" % revision.revision)
  166. map_[revision.revision] = revision
  167. self._add_branches(revision, map_)
  168. self._add_depends_on(revision, map_)
  169. if revision.is_base:
  170. self.bases += (revision.revision, )
  171. if revision._is_real_base:
  172. self._real_bases += (revision.revision, )
  173. for downrev in revision._all_down_revisions:
  174. if downrev not in map_:
  175. util.warn(
  176. "Revision %s referenced from %s is not present"
  177. % (downrev, revision)
  178. )
  179. map_[downrev].add_nextrev(revision)
  180. if revision._is_real_head:
  181. self._real_heads = tuple(
  182. head for head in self._real_heads
  183. if head not in
  184. set(revision._all_down_revisions).union([revision.revision])
  185. ) + (revision.revision,)
  186. if revision.is_head:
  187. self.heads = tuple(
  188. head for head in self.heads
  189. if head not in
  190. set(revision._versioned_down_revisions).union([revision.revision])
  191. ) + (revision.revision,)
  192. def get_current_head(self, branch_label=None):
  193. """Return the current head revision.
  194. If the script directory has multiple heads
  195. due to branching, an error is raised;
  196. :meth:`.ScriptDirectory.get_heads` should be
  197. preferred.
  198. :param branch_label: optional branch name which will limit the
  199. heads considered to those which include that branch_label.
  200. :return: a string revision number.
  201. .. seealso::
  202. :meth:`.ScriptDirectory.get_heads`
  203. """
  204. current_heads = self.heads
  205. if branch_label:
  206. current_heads = self.filter_for_lineage(current_heads, branch_label)
  207. if len(current_heads) > 1:
  208. raise MultipleHeads(
  209. current_heads,
  210. "%s@head" % branch_label if branch_label else "head")
  211. if current_heads:
  212. return current_heads[0]
  213. else:
  214. return None
  215. def _get_base_revisions(self, identifier):
  216. return self.filter_for_lineage(self.bases, identifier)
  217. def get_revisions(self, id_):
  218. """Return the :class:`.Revision` instances with the given rev id
  219. or identifiers.
  220. May be given a single identifier, a sequence of identifiers, or the
  221. special symbols "head" or "base". The result is a tuple of one
  222. or more identifiers, or an empty tuple in the case of "base".
  223. In the cases where 'head', 'heads' is requested and the
  224. revision map is empty, returns an empty tuple.
  225. Supports partial identifiers, where the given identifier
  226. is matched against all identifiers that start with the given
  227. characters; if there is exactly one match, that determines the
  228. full revision.
  229. """
  230. if isinstance(id_, (list, tuple, set, frozenset)):
  231. return sum([self.get_revisions(id_elem) for id_elem in id_], ())
  232. else:
  233. resolved_id, branch_label = self._resolve_revision_number(id_)
  234. return tuple(
  235. self._revision_for_ident(rev_id, branch_label)
  236. for rev_id in resolved_id)
  237. def get_revision(self, id_):
  238. """Return the :class:`.Revision` instance with the given rev id.
  239. If a symbolic name such as "head" or "base" is given, resolves
  240. the identifier into the current head or base revision. If the symbolic
  241. name refers to multiples, :class:`.MultipleHeads` is raised.
  242. Supports partial identifiers, where the given identifier
  243. is matched against all identifiers that start with the given
  244. characters; if there is exactly one match, that determines the
  245. full revision.
  246. """
  247. resolved_id, branch_label = self._resolve_revision_number(id_)
  248. if len(resolved_id) > 1:
  249. raise MultipleHeads(resolved_id, id_)
  250. elif resolved_id:
  251. resolved_id = resolved_id[0]
  252. return self._revision_for_ident(resolved_id, branch_label)
  253. def _resolve_branch(self, branch_label):
  254. try:
  255. branch_rev = self._revision_map[branch_label]
  256. except KeyError:
  257. try:
  258. nonbranch_rev = self._revision_for_ident(branch_label)
  259. except ResolutionError:
  260. raise ResolutionError(
  261. "No such branch: '%s'" % branch_label, branch_label)
  262. else:
  263. return nonbranch_rev
  264. else:
  265. return branch_rev
  266. def _revision_for_ident(self, resolved_id, check_branch=None):
  267. if check_branch:
  268. branch_rev = self._resolve_branch(check_branch)
  269. else:
  270. branch_rev = None
  271. try:
  272. revision = self._revision_map[resolved_id]
  273. except KeyError:
  274. # do a partial lookup
  275. revs = [x for x in self._revision_map
  276. if x and x.startswith(resolved_id)]
  277. if branch_rev:
  278. revs = self.filter_for_lineage(revs, check_branch)
  279. if not revs:
  280. raise ResolutionError(
  281. "No such revision or branch '%s'" % resolved_id,
  282. resolved_id)
  283. elif len(revs) > 1:
  284. raise ResolutionError(
  285. "Multiple revisions start "
  286. "with '%s': %s..." % (
  287. resolved_id,
  288. ", ".join("'%s'" % r for r in revs[0:3])
  289. ), resolved_id)
  290. else:
  291. revision = self._revision_map[revs[0]]
  292. if check_branch and revision is not None:
  293. if not self._shares_lineage(
  294. revision.revision, branch_rev.revision):
  295. raise ResolutionError(
  296. "Revision %s is not a member of branch '%s'" %
  297. (revision.revision, check_branch), resolved_id)
  298. return revision
  299. def _filter_into_branch_heads(self, targets):
  300. targets = set(targets)
  301. for rev in list(targets):
  302. if targets.intersection(
  303. self._get_descendant_nodes(
  304. [rev], include_dependencies=False)).\
  305. difference([rev]):
  306. targets.discard(rev)
  307. return targets
  308. def filter_for_lineage(
  309. self, targets, check_against, include_dependencies=False):
  310. id_, branch_label = self._resolve_revision_number(check_against)
  311. shares = []
  312. if branch_label:
  313. shares.append(branch_label)
  314. if id_:
  315. shares.extend(id_)
  316. return [
  317. tg for tg in targets
  318. if self._shares_lineage(
  319. tg, shares, include_dependencies=include_dependencies)]
  320. def _shares_lineage(
  321. self, target, test_against_revs, include_dependencies=False):
  322. if not test_against_revs:
  323. return True
  324. if not isinstance(target, Revision):
  325. target = self._revision_for_ident(target)
  326. test_against_revs = [
  327. self._revision_for_ident(test_against_rev)
  328. if not isinstance(test_against_rev, Revision)
  329. else test_against_rev
  330. for test_against_rev
  331. in util.to_tuple(test_against_revs, default=())
  332. ]
  333. return bool(
  334. set(self._get_descendant_nodes([target],
  335. include_dependencies=include_dependencies))
  336. .union(self._get_ancestor_nodes([target],
  337. include_dependencies=include_dependencies))
  338. .intersection(test_against_revs)
  339. )
  340. def _resolve_revision_number(self, id_):
  341. if isinstance(id_, compat.string_types) and "@" in id_:
  342. branch_label, id_ = id_.split('@', 1)
  343. else:
  344. branch_label = None
  345. # ensure map is loaded
  346. self._revision_map
  347. if id_ == 'heads':
  348. if branch_label:
  349. return self.filter_for_lineage(
  350. self.heads, branch_label), branch_label
  351. else:
  352. return self._real_heads, branch_label
  353. elif id_ == 'head':
  354. current_head = self.get_current_head(branch_label)
  355. if current_head:
  356. return (current_head, ), branch_label
  357. else:
  358. return (), branch_label
  359. elif id_ == 'base' or id_ is None:
  360. return (), branch_label
  361. else:
  362. return util.to_tuple(id_, default=None), branch_label
  363. def _relative_iterate(
  364. self, destination, source, is_upwards,
  365. implicit_base, inclusive, assert_relative_length):
  366. if isinstance(destination, compat.string_types):
  367. match = _relative_destination.match(destination)
  368. if not match:
  369. return None
  370. else:
  371. return None
  372. relative = int(match.group(3))
  373. symbol = match.group(2)
  374. branch_label = match.group(1)
  375. reldelta = 1 if inclusive and not symbol else 0
  376. if is_upwards:
  377. if branch_label:
  378. from_ = "%s@head" % branch_label
  379. elif symbol:
  380. if symbol.startswith("head"):
  381. from_ = symbol
  382. else:
  383. from_ = "%s@head" % symbol
  384. else:
  385. from_ = "head"
  386. to_ = source
  387. else:
  388. if branch_label:
  389. to_ = "%s@base" % branch_label
  390. elif symbol:
  391. to_ = "%s@base" % symbol
  392. else:
  393. to_ = "base"
  394. from_ = source
  395. revs = list(
  396. self._iterate_revisions(
  397. from_, to_,
  398. inclusive=inclusive, implicit_base=implicit_base))
  399. if symbol:
  400. if branch_label:
  401. symbol_rev = self.get_revision(
  402. "%s@%s" % (branch_label, symbol))
  403. else:
  404. symbol_rev = self.get_revision(symbol)
  405. if symbol.startswith("head"):
  406. index = 0
  407. elif symbol == "base":
  408. index = len(revs) - 1
  409. else:
  410. range_ = compat.range(len(revs) - 1, 0, -1)
  411. for index in range_:
  412. if symbol_rev.revision == revs[index].revision:
  413. break
  414. else:
  415. index = 0
  416. else:
  417. index = 0
  418. if is_upwards:
  419. revs = revs[index - relative - reldelta:]
  420. if not index and assert_relative_length and \
  421. len(revs) < abs(relative - reldelta):
  422. raise RevisionError(
  423. "Relative revision %s didn't "
  424. "produce %d migrations" % (destination, abs(relative)))
  425. else:
  426. revs = revs[0:index - relative + reldelta]
  427. if not index and assert_relative_length and \
  428. len(revs) != abs(relative) + reldelta:
  429. raise RevisionError(
  430. "Relative revision %s didn't "
  431. "produce %d migrations" % (destination, abs(relative)))
  432. return iter(revs)
  433. def iterate_revisions(
  434. self, upper, lower, implicit_base=False, inclusive=False,
  435. assert_relative_length=True, select_for_downgrade=False):
  436. """Iterate through script revisions, starting at the given
  437. upper revision identifier and ending at the lower.
  438. The traversal uses strictly the `down_revision`
  439. marker inside each migration script, so
  440. it is a requirement that upper >= lower,
  441. else you'll get nothing back.
  442. The iterator yields :class:`.Revision` objects.
  443. """
  444. relative_upper = self._relative_iterate(
  445. upper, lower, True, implicit_base,
  446. inclusive, assert_relative_length
  447. )
  448. if relative_upper:
  449. return relative_upper
  450. relative_lower = self._relative_iterate(
  451. lower, upper, False, implicit_base,
  452. inclusive, assert_relative_length
  453. )
  454. if relative_lower:
  455. return relative_lower
  456. return self._iterate_revisions(
  457. upper, lower, inclusive=inclusive, implicit_base=implicit_base,
  458. select_for_downgrade=select_for_downgrade)
  459. def _get_descendant_nodes(
  460. self, targets, map_=None, check=False,
  461. omit_immediate_dependencies=False, include_dependencies=True):
  462. if omit_immediate_dependencies:
  463. def fn(rev):
  464. if rev not in targets:
  465. return rev._all_nextrev
  466. else:
  467. return rev.nextrev
  468. elif include_dependencies:
  469. def fn(rev):
  470. return rev._all_nextrev
  471. else:
  472. def fn(rev):
  473. return rev.nextrev
  474. return self._iterate_related_revisions(
  475. fn, targets, map_=map_, check=check
  476. )
  477. def _get_ancestor_nodes(
  478. self, targets, map_=None, check=False, include_dependencies=True):
  479. if include_dependencies:
  480. def fn(rev):
  481. return rev._all_down_revisions
  482. else:
  483. def fn(rev):
  484. return rev._versioned_down_revisions
  485. return self._iterate_related_revisions(
  486. fn, targets, map_=map_, check=check
  487. )
  488. def _iterate_related_revisions(self, fn, targets, map_, check=False):
  489. if map_ is None:
  490. map_ = self._revision_map
  491. seen = set()
  492. todo = collections.deque()
  493. for target in targets:
  494. todo.append(target)
  495. if check:
  496. per_target = set()
  497. while todo:
  498. rev = todo.pop()
  499. if check:
  500. per_target.add(rev)
  501. if rev in seen:
  502. continue
  503. seen.add(rev)
  504. todo.extend(
  505. map_[rev_id] for rev_id in fn(rev))
  506. yield rev
  507. if check:
  508. overlaps = per_target.intersection(targets).\
  509. difference([target])
  510. if overlaps:
  511. raise RevisionError(
  512. "Requested revision %s overlaps with "
  513. "other requested revisions %s" % (
  514. target.revision,
  515. ", ".join(r.revision for r in overlaps)
  516. )
  517. )
  518. def _iterate_revisions(
  519. self, upper, lower, inclusive=True, implicit_base=False,
  520. select_for_downgrade=False):
  521. """iterate revisions from upper to lower.
  522. The traversal is depth-first within branches, and breadth-first
  523. across branches as a whole.
  524. """
  525. requested_lowers = self.get_revisions(lower)
  526. # some complexity to accommodate an iteration where some
  527. # branches are starting from nothing, and others are starting
  528. # from a given point. Additionally, if the bottom branch
  529. # is specified using a branch identifier, then we limit operations
  530. # to just that branch.
  531. limit_to_lower_branch = \
  532. isinstance(lower, compat.string_types) and lower.endswith('@base')
  533. uppers = util.dedupe_tuple(self.get_revisions(upper))
  534. if not uppers and not requested_lowers:
  535. raise StopIteration()
  536. upper_ancestors = set(self._get_ancestor_nodes(uppers, check=True))
  537. if limit_to_lower_branch:
  538. lowers = self.get_revisions(self._get_base_revisions(lower))
  539. elif implicit_base and requested_lowers:
  540. lower_ancestors = set(
  541. self._get_ancestor_nodes(requested_lowers)
  542. )
  543. lower_descendants = set(
  544. self._get_descendant_nodes(requested_lowers)
  545. )
  546. base_lowers = set()
  547. candidate_lowers = upper_ancestors.\
  548. difference(lower_ancestors).\
  549. difference(lower_descendants)
  550. for rev in candidate_lowers:
  551. for downrev in rev._all_down_revisions:
  552. if self._revision_map[downrev] in candidate_lowers:
  553. break
  554. else:
  555. base_lowers.add(rev)
  556. lowers = base_lowers.union(requested_lowers)
  557. elif implicit_base:
  558. base_lowers = set(self.get_revisions(self._real_bases))
  559. lowers = base_lowers.union(requested_lowers)
  560. elif not requested_lowers:
  561. lowers = set(self.get_revisions(self._real_bases))
  562. else:
  563. lowers = requested_lowers
  564. # represents all nodes we will produce
  565. total_space = set(
  566. rev.revision for rev in upper_ancestors).intersection(
  567. rev.revision for rev
  568. in self._get_descendant_nodes(
  569. lowers, check=True,
  570. omit_immediate_dependencies=(
  571. select_for_downgrade and requested_lowers
  572. )
  573. )
  574. )
  575. if not total_space:
  576. # no nodes. determine if this is an invalid range
  577. # or not.
  578. start_from = set(requested_lowers)
  579. start_from.update(
  580. self._get_ancestor_nodes(
  581. list(start_from), include_dependencies=True)
  582. )
  583. # determine all the current branch points represented
  584. # by requested_lowers
  585. start_from = self._filter_into_branch_heads(start_from)
  586. # if the requested start is one of those branch points,
  587. # then just return empty set
  588. if start_from.intersection(upper_ancestors):
  589. raise StopIteration()
  590. else:
  591. # otherwise, they requested nodes out of
  592. # order
  593. raise RangeNotAncestorError(lower, upper)
  594. # organize branch points to be consumed separately from
  595. # member nodes
  596. branch_todo = set(
  597. rev for rev in
  598. (self._revision_map[rev] for rev in total_space)
  599. if rev._is_real_branch_point and
  600. len(total_space.intersection(rev._all_nextrev)) > 1
  601. )
  602. # it's not possible for any "uppers" to be in branch_todo,
  603. # because the ._all_nextrev of those nodes is not in total_space
  604. #assert not branch_todo.intersection(uppers)
  605. todo = collections.deque(
  606. r for r in uppers
  607. if r.revision in total_space
  608. )
  609. # iterate for total_space being emptied out
  610. total_space_modified = True
  611. while total_space:
  612. if not total_space_modified:
  613. raise RevisionError(
  614. "Dependency resolution failed; iteration can't proceed")
  615. total_space_modified = False
  616. # when everything non-branch pending is consumed,
  617. # add to the todo any branch nodes that have no
  618. # descendants left in the queue
  619. if not todo:
  620. todo.extendleft(
  621. sorted(
  622. (
  623. rev for rev in branch_todo
  624. if not rev._all_nextrev.intersection(total_space)
  625. ),
  626. # favor "revisioned" branch points before
  627. # dependent ones
  628. key=lambda rev: 0 if rev.is_branch_point else 1
  629. )
  630. )
  631. branch_todo.difference_update(todo)
  632. # iterate nodes that are in the immediate todo
  633. while todo:
  634. rev = todo.popleft()
  635. total_space.remove(rev.revision)
  636. total_space_modified = True
  637. # do depth first for elements within branches,
  638. # don't consume any actual branch nodes
  639. todo.extendleft([
  640. self._revision_map[downrev]
  641. for downrev in reversed(rev._all_down_revisions)
  642. if self._revision_map[downrev] not in branch_todo
  643. and downrev in total_space])
  644. if not inclusive and rev in requested_lowers:
  645. continue
  646. yield rev
  647. assert not branch_todo
  648. class Revision(object):
  649. """Base class for revisioned objects.
  650. The :class:`.Revision` class is the base of the more public-facing
  651. :class:`.Script` object, which represents a migration script.
  652. The mechanics of revision management and traversal are encapsulated
  653. within :class:`.Revision`, while :class:`.Script` applies this logic
  654. to Python files in a version directory.
  655. """
  656. nextrev = frozenset()
  657. """following revisions, based on down_revision only."""
  658. _all_nextrev = frozenset()
  659. revision = None
  660. """The string revision number."""
  661. down_revision = None
  662. """The ``down_revision`` identifier(s) within the migration script.
  663. Note that the total set of "down" revisions is
  664. down_revision + dependencies.
  665. """
  666. dependencies = None
  667. """Additional revisions which this revision is dependent on.
  668. From a migration standpoint, these dependencies are added to the
  669. down_revision to form the full iteration. However, the separation
  670. of down_revision from "dependencies" is to assist in navigating
  671. a history that contains many branches, typically a multi-root scenario.
  672. """
  673. branch_labels = None
  674. """Optional string/tuple of symbolic names to apply to this
  675. revision's branch"""
  676. def __init__(
  677. self, revision, down_revision,
  678. dependencies=None, branch_labels=None):
  679. self.revision = revision
  680. self.down_revision = tuple_rev_as_scalar(down_revision)
  681. self.dependencies = tuple_rev_as_scalar(dependencies)
  682. self._resolved_dependencies = ()
  683. self._orig_branch_labels = util.to_tuple(branch_labels, default=())
  684. self.branch_labels = set(self._orig_branch_labels)
  685. def __repr__(self):
  686. args = [
  687. repr(self.revision),
  688. repr(self.down_revision)
  689. ]
  690. if self.dependencies:
  691. args.append("dependencies=%r" % (self.dependencies,))
  692. if self.branch_labels:
  693. args.append("branch_labels=%r" % (self.branch_labels,))
  694. return "%s(%s)" % (
  695. self.__class__.__name__,
  696. ", ".join(args)
  697. )
  698. def add_nextrev(self, revision):
  699. self._all_nextrev = self._all_nextrev.union([revision.revision])
  700. if self.revision in revision._versioned_down_revisions:
  701. self.nextrev = self.nextrev.union([revision.revision])
  702. @property
  703. def _all_down_revisions(self):
  704. return util.to_tuple(self.down_revision, default=()) + \
  705. self._resolved_dependencies
  706. @property
  707. def _versioned_down_revisions(self):
  708. return util.to_tuple(self.down_revision, default=())
  709. @property
  710. def is_head(self):
  711. """Return True if this :class:`.Revision` is a 'head' revision.
  712. This is determined based on whether any other :class:`.Script`
  713. within the :class:`.ScriptDirectory` refers to this
  714. :class:`.Script`. Multiple heads can be present.
  715. """
  716. return not bool(self.nextrev)
  717. @property
  718. def _is_real_head(self):
  719. return not bool(self._all_nextrev)
  720. @property
  721. def is_base(self):
  722. """Return True if this :class:`.Revision` is a 'base' revision."""
  723. return self.down_revision is None
  724. @property
  725. def _is_real_base(self):
  726. """Return True if this :class:`.Revision` is a "real" base revision,
  727. e.g. that it has no dependencies either."""
  728. # we use self.dependencies here because this is called up
  729. # in initialization where _real_dependencies isn't set up
  730. # yet
  731. return self.down_revision is None and self.dependencies is None
  732. @property
  733. def is_branch_point(self):
  734. """Return True if this :class:`.Script` is a branch point.
  735. A branchpoint is defined as a :class:`.Script` which is referred
  736. to by more than one succeeding :class:`.Script`, that is more
  737. than one :class:`.Script` has a `down_revision` identifier pointing
  738. here.
  739. """
  740. return len(self.nextrev) > 1
  741. @property
  742. def _is_real_branch_point(self):
  743. """Return True if this :class:`.Script` is a 'real' branch point,
  744. taking into account dependencies as well.
  745. """
  746. return len(self._all_nextrev) > 1
  747. @property
  748. def is_merge_point(self):
  749. """Return True if this :class:`.Script` is a merge point."""
  750. return len(self._versioned_down_revisions) > 1
  751. def tuple_rev_as_scalar(rev):
  752. if not rev:
  753. return None
  754. elif len(rev) == 1:
  755. return rev[0]
  756. else:
  757. return rev