revision.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  1. from __future__ import annotations
  2. import collections
  3. import re
  4. from typing import Any
  5. from typing import Callable
  6. from typing import cast
  7. from typing import Collection
  8. from typing import Deque
  9. from typing import Dict
  10. from typing import FrozenSet
  11. from typing import Iterable
  12. from typing import Iterator
  13. from typing import List
  14. from typing import Optional
  15. from typing import overload
  16. from typing import Protocol
  17. from typing import Sequence
  18. from typing import Set
  19. from typing import Tuple
  20. from typing import TYPE_CHECKING
  21. from typing import TypeVar
  22. from typing import Union
  23. from sqlalchemy import util as sqlautil
  24. from .. import util
  25. from ..util import not_none
  26. if TYPE_CHECKING:
  27. from typing import Literal
  28. _RevIdType = Union[str, List[str], Tuple[str, ...]]
  29. _GetRevArg = Union[
  30. str,
  31. Iterable[Optional[str]],
  32. Iterable[str],
  33. ]
  34. _RevisionIdentifierType = Union[str, Tuple[str, ...], None]
  35. _RevisionOrStr = Union["Revision", str]
  36. _RevisionOrBase = Union["Revision", "Literal['base']"]
  37. _InterimRevisionMapType = Dict[str, "Revision"]
  38. _RevisionMapType = Dict[Union[None, str, Tuple[()]], Optional["Revision"]]
  39. _T = TypeVar("_T")
  40. _TR = TypeVar("_TR", bound=Optional[_RevisionOrStr])
  41. _relative_destination = re.compile(r"(?:(.+?)@)?(\w+)?((?:\+|-)\d+)")
  42. _revision_illegal_chars = ["@", "-", "+"]
  43. class _CollectRevisionsProtocol(Protocol):
  44. def __call__(
  45. self,
  46. upper: _RevisionIdentifierType,
  47. lower: _RevisionIdentifierType,
  48. inclusive: bool,
  49. implicit_base: bool,
  50. assert_relative_length: bool,
  51. ) -> Tuple[Set[Revision], Tuple[Optional[_RevisionOrBase], ...]]:
  52. ...
  53. class RevisionError(Exception):
  54. pass
  55. class RangeNotAncestorError(RevisionError):
  56. def __init__(
  57. self, lower: _RevisionIdentifierType, upper: _RevisionIdentifierType
  58. ) -> None:
  59. self.lower = lower
  60. self.upper = upper
  61. super().__init__(
  62. "Revision %s is not an ancestor of revision %s"
  63. % (lower or "base", upper or "base")
  64. )
  65. class MultipleHeads(RevisionError):
  66. def __init__(self, heads: Sequence[str], argument: Optional[str]) -> None:
  67. self.heads = heads
  68. self.argument = argument
  69. super().__init__(
  70. "Multiple heads are present for given argument '%s'; "
  71. "%s" % (argument, ", ".join(heads))
  72. )
  73. class ResolutionError(RevisionError):
  74. def __init__(self, message: str, argument: str) -> None:
  75. super().__init__(message)
  76. self.argument = argument
  77. class CycleDetected(RevisionError):
  78. kind = "Cycle"
  79. def __init__(self, revisions: Sequence[str]) -> None:
  80. self.revisions = revisions
  81. super().__init__(
  82. "%s is detected in revisions (%s)"
  83. % (self.kind, ", ".join(revisions))
  84. )
  85. class DependencyCycleDetected(CycleDetected):
  86. kind = "Dependency cycle"
  87. def __init__(self, revisions: Sequence[str]) -> None:
  88. super().__init__(revisions)
  89. class LoopDetected(CycleDetected):
  90. kind = "Self-loop"
  91. def __init__(self, revision: str) -> None:
  92. super().__init__([revision])
  93. class DependencyLoopDetected(DependencyCycleDetected, LoopDetected):
  94. kind = "Dependency self-loop"
  95. def __init__(self, revision: Sequence[str]) -> None:
  96. super().__init__(revision)
  97. class RevisionMap:
  98. """Maintains a map of :class:`.Revision` objects.
  99. :class:`.RevisionMap` is used by :class:`.ScriptDirectory` to maintain
  100. and traverse the collection of :class:`.Script` objects, which are
  101. themselves instances of :class:`.Revision`.
  102. """
  103. def __init__(self, generator: Callable[[], Iterable[Revision]]) -> None:
  104. """Construct a new :class:`.RevisionMap`.
  105. :param generator: a zero-arg callable that will generate an iterable
  106. of :class:`.Revision` instances to be used. These are typically
  107. :class:`.Script` subclasses within regular Alembic use.
  108. """
  109. self._generator = generator
  110. @util.memoized_property
  111. def heads(self) -> Tuple[str, ...]:
  112. """All "head" revisions as strings.
  113. This is normally a tuple of length one,
  114. unless unmerged branches are present.
  115. :return: a tuple of string revision numbers.
  116. """
  117. self._revision_map
  118. return self.heads
  119. @util.memoized_property
  120. def bases(self) -> Tuple[str, ...]:
  121. """All "base" revisions as strings.
  122. These are revisions that have a ``down_revision`` of None,
  123. or empty tuple.
  124. :return: a tuple of string revision numbers.
  125. """
  126. self._revision_map
  127. return self.bases
  128. @util.memoized_property
  129. def _real_heads(self) -> Tuple[str, ...]:
  130. """All "real" head revisions as strings.
  131. :return: a tuple of string revision numbers.
  132. """
  133. self._revision_map
  134. return self._real_heads
  135. @util.memoized_property
  136. def _real_bases(self) -> Tuple[str, ...]:
  137. """All "real" base revisions as strings.
  138. :return: a tuple of string revision numbers.
  139. """
  140. self._revision_map
  141. return self._real_bases
  142. @util.memoized_property
  143. def _revision_map(self) -> _RevisionMapType:
  144. """memoized attribute, initializes the revision map from the
  145. initial collection.
  146. """
  147. # Ordering required for some tests to pass (but not required in
  148. # general)
  149. map_: _InterimRevisionMapType = sqlautil.OrderedDict()
  150. heads: Set[Revision] = sqlautil.OrderedSet()
  151. _real_heads: Set[Revision] = sqlautil.OrderedSet()
  152. bases: Tuple[Revision, ...] = ()
  153. _real_bases: Tuple[Revision, ...] = ()
  154. has_branch_labels = set()
  155. all_revisions = set()
  156. for revision in self._generator():
  157. all_revisions.add(revision)
  158. if revision.revision in map_:
  159. util.warn(
  160. "Revision %s is present more than once" % revision.revision
  161. )
  162. map_[revision.revision] = revision
  163. if revision.branch_labels:
  164. has_branch_labels.add(revision)
  165. heads.add(revision)
  166. _real_heads.add(revision)
  167. if revision.is_base:
  168. bases += (revision,)
  169. if revision._is_real_base:
  170. _real_bases += (revision,)
  171. # add the branch_labels to the map_. We'll need these
  172. # to resolve the dependencies.
  173. rev_map = map_.copy()
  174. self._map_branch_labels(
  175. has_branch_labels, cast(_RevisionMapType, map_)
  176. )
  177. # resolve dependency names from branch labels and symbolic
  178. # names
  179. self._add_depends_on(all_revisions, cast(_RevisionMapType, map_))
  180. for rev in map_.values():
  181. for downrev in rev._all_down_revisions:
  182. if downrev not in map_:
  183. util.warn(
  184. "Revision %s referenced from %s is not present"
  185. % (downrev, rev)
  186. )
  187. down_revision = map_[downrev]
  188. down_revision.add_nextrev(rev)
  189. if downrev in rev._versioned_down_revisions:
  190. heads.discard(down_revision)
  191. _real_heads.discard(down_revision)
  192. # once the map has downrevisions populated, the dependencies
  193. # can be further refined to include only those which are not
  194. # already ancestors
  195. self._normalize_depends_on(all_revisions, cast(_RevisionMapType, map_))
  196. self._detect_cycles(rev_map, heads, bases, _real_heads, _real_bases)
  197. revision_map: _RevisionMapType = dict(map_.items())
  198. revision_map[None] = revision_map[()] = None
  199. self.heads = tuple(rev.revision for rev in heads)
  200. self._real_heads = tuple(rev.revision for rev in _real_heads)
  201. self.bases = tuple(rev.revision for rev in bases)
  202. self._real_bases = tuple(rev.revision for rev in _real_bases)
  203. self._add_branches(has_branch_labels, revision_map)
  204. return revision_map
  205. def _detect_cycles(
  206. self,
  207. rev_map: _InterimRevisionMapType,
  208. heads: Set[Revision],
  209. bases: Tuple[Revision, ...],
  210. _real_heads: Set[Revision],
  211. _real_bases: Tuple[Revision, ...],
  212. ) -> None:
  213. if not rev_map:
  214. return
  215. if not heads or not bases:
  216. raise CycleDetected(list(rev_map))
  217. total_space = {
  218. rev.revision
  219. for rev in self._iterate_related_revisions(
  220. lambda r: r._versioned_down_revisions,
  221. heads,
  222. map_=cast(_RevisionMapType, rev_map),
  223. )
  224. }.intersection(
  225. rev.revision
  226. for rev in self._iterate_related_revisions(
  227. lambda r: r.nextrev,
  228. bases,
  229. map_=cast(_RevisionMapType, rev_map),
  230. )
  231. )
  232. deleted_revs = set(rev_map.keys()) - total_space
  233. if deleted_revs:
  234. raise CycleDetected(sorted(deleted_revs))
  235. if not _real_heads or not _real_bases:
  236. raise DependencyCycleDetected(list(rev_map))
  237. total_space = {
  238. rev.revision
  239. for rev in self._iterate_related_revisions(
  240. lambda r: r._all_down_revisions,
  241. _real_heads,
  242. map_=cast(_RevisionMapType, rev_map),
  243. )
  244. }.intersection(
  245. rev.revision
  246. for rev in self._iterate_related_revisions(
  247. lambda r: r._all_nextrev,
  248. _real_bases,
  249. map_=cast(_RevisionMapType, rev_map),
  250. )
  251. )
  252. deleted_revs = set(rev_map.keys()) - total_space
  253. if deleted_revs:
  254. raise DependencyCycleDetected(sorted(deleted_revs))
  255. def _map_branch_labels(
  256. self, revisions: Collection[Revision], map_: _RevisionMapType
  257. ) -> None:
  258. for revision in revisions:
  259. if revision.branch_labels:
  260. assert revision._orig_branch_labels is not None
  261. for branch_label in revision._orig_branch_labels:
  262. if branch_label in map_:
  263. map_rev = map_[branch_label]
  264. assert map_rev is not None
  265. raise RevisionError(
  266. "Branch name '%s' in revision %s already "
  267. "used by revision %s"
  268. % (
  269. branch_label,
  270. revision.revision,
  271. map_rev.revision,
  272. )
  273. )
  274. map_[branch_label] = revision
  275. def _add_branches(
  276. self, revisions: Collection[Revision], map_: _RevisionMapType
  277. ) -> None:
  278. for revision in revisions:
  279. if revision.branch_labels:
  280. revision.branch_labels.update(revision.branch_labels)
  281. for node in self._get_descendant_nodes(
  282. [revision], map_, include_dependencies=False
  283. ):
  284. node.branch_labels.update(revision.branch_labels)
  285. parent = node
  286. while (
  287. parent
  288. and not parent._is_real_branch_point
  289. and not parent.is_merge_point
  290. ):
  291. parent.branch_labels.update(revision.branch_labels)
  292. if parent.down_revision:
  293. parent = map_[parent.down_revision]
  294. else:
  295. break
  296. def _add_depends_on(
  297. self, revisions: Collection[Revision], map_: _RevisionMapType
  298. ) -> None:
  299. """Resolve the 'dependencies' for each revision in a collection
  300. in terms of actual revision ids, as opposed to branch labels or other
  301. symbolic names.
  302. The collection is then assigned to the _resolved_dependencies
  303. attribute on each revision object.
  304. """
  305. for revision in revisions:
  306. if revision.dependencies:
  307. deps = [
  308. map_[dep] for dep in util.to_tuple(revision.dependencies)
  309. ]
  310. revision._resolved_dependencies = tuple(
  311. [d.revision for d in deps if d is not None]
  312. )
  313. else:
  314. revision._resolved_dependencies = ()
  315. def _normalize_depends_on(
  316. self, revisions: Collection[Revision], map_: _RevisionMapType
  317. ) -> None:
  318. """Create a collection of "dependencies" that omits dependencies
  319. that are already ancestor nodes for each revision in a given
  320. collection.
  321. This builds upon the _resolved_dependencies collection created in the
  322. _add_depends_on() method, looking in the fully populated revision map
  323. for ancestors, and omitting them as the _resolved_dependencies
  324. collection as it is copied to a new collection. The new collection is
  325. then assigned to the _normalized_resolved_dependencies attribute on
  326. each revision object.
  327. The collection is then used to determine the immediate "down revision"
  328. identifiers for this revision.
  329. """
  330. for revision in revisions:
  331. if revision._resolved_dependencies:
  332. normalized_resolved = set(revision._resolved_dependencies)
  333. for rev in self._get_ancestor_nodes(
  334. [revision],
  335. include_dependencies=False,
  336. map_=map_,
  337. ):
  338. if rev is revision:
  339. continue
  340. elif rev._resolved_dependencies:
  341. normalized_resolved.difference_update(
  342. rev._resolved_dependencies
  343. )
  344. revision._normalized_resolved_dependencies = tuple(
  345. normalized_resolved
  346. )
  347. else:
  348. revision._normalized_resolved_dependencies = ()
  349. def add_revision(self, revision: Revision, _replace: bool = False) -> None:
  350. """add a single revision to an existing map.
  351. This method is for single-revision use cases, it's not
  352. appropriate for fully populating an entire revision map.
  353. """
  354. map_ = self._revision_map
  355. if not _replace and revision.revision in map_:
  356. util.warn(
  357. "Revision %s is present more than once" % revision.revision
  358. )
  359. elif _replace and revision.revision not in map_:
  360. raise Exception("revision %s not in map" % revision.revision)
  361. map_[revision.revision] = revision
  362. revisions = [revision]
  363. self._add_branches(revisions, map_)
  364. self._map_branch_labels(revisions, map_)
  365. self._add_depends_on(revisions, map_)
  366. if revision.is_base:
  367. self.bases += (revision.revision,)
  368. if revision._is_real_base:
  369. self._real_bases += (revision.revision,)
  370. for downrev in revision._all_down_revisions:
  371. if downrev not in map_:
  372. util.warn(
  373. "Revision %s referenced from %s is not present"
  374. % (downrev, revision)
  375. )
  376. not_none(map_[downrev]).add_nextrev(revision)
  377. self._normalize_depends_on(revisions, map_)
  378. if revision._is_real_head:
  379. self._real_heads = tuple(
  380. head
  381. for head in self._real_heads
  382. if head
  383. not in set(revision._all_down_revisions).union(
  384. [revision.revision]
  385. )
  386. ) + (revision.revision,)
  387. if revision.is_head:
  388. self.heads = tuple(
  389. head
  390. for head in self.heads
  391. if head
  392. not in set(revision._versioned_down_revisions).union(
  393. [revision.revision]
  394. )
  395. ) + (revision.revision,)
  396. def get_current_head(
  397. self, branch_label: Optional[str] = None
  398. ) -> Optional[str]:
  399. """Return the current head revision.
  400. If the script directory has multiple heads
  401. due to branching, an error is raised;
  402. :meth:`.ScriptDirectory.get_heads` should be
  403. preferred.
  404. :param branch_label: optional branch name which will limit the
  405. heads considered to those which include that branch_label.
  406. :return: a string revision number.
  407. .. seealso::
  408. :meth:`.ScriptDirectory.get_heads`
  409. """
  410. current_heads: Sequence[str] = self.heads
  411. if branch_label:
  412. current_heads = self.filter_for_lineage(
  413. current_heads, branch_label
  414. )
  415. if len(current_heads) > 1:
  416. raise MultipleHeads(
  417. current_heads,
  418. "%s@head" % branch_label if branch_label else "head",
  419. )
  420. if current_heads:
  421. return current_heads[0]
  422. else:
  423. return None
  424. def _get_base_revisions(self, identifier: str) -> Tuple[str, ...]:
  425. return self.filter_for_lineage(self.bases, identifier)
  426. def get_revisions(
  427. self, id_: Optional[_GetRevArg]
  428. ) -> Tuple[Optional[_RevisionOrBase], ...]:
  429. """Return the :class:`.Revision` instances with the given rev id
  430. or identifiers.
  431. May be given a single identifier, a sequence of identifiers, or the
  432. special symbols "head" or "base". The result is a tuple of one
  433. or more identifiers, or an empty tuple in the case of "base".
  434. In the cases where 'head', 'heads' is requested and the
  435. revision map is empty, returns an empty tuple.
  436. Supports partial identifiers, where the given identifier
  437. is matched against all identifiers that start with the given
  438. characters; if there is exactly one match, that determines the
  439. full revision.
  440. """
  441. if isinstance(id_, (list, tuple, set, frozenset)):
  442. return sum([self.get_revisions(id_elem) for id_elem in id_], ())
  443. else:
  444. resolved_id, branch_label = self._resolve_revision_number(id_)
  445. if len(resolved_id) == 1:
  446. try:
  447. rint = int(resolved_id[0])
  448. if rint < 0:
  449. # branch@-n -> walk down from heads
  450. select_heads = self.get_revisions("heads")
  451. if branch_label is not None:
  452. select_heads = tuple(
  453. head
  454. for head in select_heads
  455. if branch_label
  456. in is_revision(head).branch_labels
  457. )
  458. return tuple(
  459. self._walk(head, steps=rint)
  460. for head in select_heads
  461. )
  462. except ValueError:
  463. # couldn't resolve as integer
  464. pass
  465. return tuple(
  466. self._revision_for_ident(rev_id, branch_label)
  467. for rev_id in resolved_id
  468. )
  469. def get_revision(self, id_: Optional[str]) -> Optional[Revision]:
  470. """Return the :class:`.Revision` instance with the given rev id.
  471. If a symbolic name such as "head" or "base" is given, resolves
  472. the identifier into the current head or base revision. If the symbolic
  473. name refers to multiples, :class:`.MultipleHeads` is raised.
  474. Supports partial identifiers, where the given identifier
  475. is matched against all identifiers that start with the given
  476. characters; if there is exactly one match, that determines the
  477. full revision.
  478. """
  479. resolved_id, branch_label = self._resolve_revision_number(id_)
  480. if len(resolved_id) > 1:
  481. raise MultipleHeads(resolved_id, id_)
  482. resolved: Union[str, Tuple[()]] = resolved_id[0] if resolved_id else ()
  483. return self._revision_for_ident(resolved, branch_label)
  484. def _resolve_branch(self, branch_label: str) -> Optional[Revision]:
  485. try:
  486. branch_rev = self._revision_map[branch_label]
  487. except KeyError:
  488. try:
  489. nonbranch_rev = self._revision_for_ident(branch_label)
  490. except ResolutionError as re:
  491. raise ResolutionError(
  492. "No such branch: '%s'" % branch_label, branch_label
  493. ) from re
  494. else:
  495. return nonbranch_rev
  496. else:
  497. return branch_rev
  498. def _revision_for_ident(
  499. self,
  500. resolved_id: Union[str, Tuple[()], None],
  501. check_branch: Optional[str] = None,
  502. ) -> Optional[Revision]:
  503. branch_rev: Optional[Revision]
  504. if check_branch:
  505. branch_rev = self._resolve_branch(check_branch)
  506. else:
  507. branch_rev = None
  508. revision: Union[Optional[Revision], Literal[False]]
  509. try:
  510. revision = self._revision_map[resolved_id]
  511. except KeyError:
  512. # break out to avoid misleading py3k stack traces
  513. revision = False
  514. revs: Sequence[str]
  515. if revision is False:
  516. assert resolved_id
  517. # do a partial lookup
  518. revs = [
  519. x
  520. for x in self._revision_map
  521. if x and len(x) > 3 and x.startswith(resolved_id)
  522. ]
  523. if branch_rev:
  524. revs = self.filter_for_lineage(revs, check_branch)
  525. if not revs:
  526. raise ResolutionError(
  527. "No such revision or branch '%s'%s"
  528. % (
  529. resolved_id,
  530. (
  531. "; please ensure at least four characters are "
  532. "present for partial revision identifier matches"
  533. if len(resolved_id) < 4
  534. else ""
  535. ),
  536. ),
  537. resolved_id,
  538. )
  539. elif len(revs) > 1:
  540. raise ResolutionError(
  541. "Multiple revisions start "
  542. "with '%s': %s..."
  543. % (resolved_id, ", ".join("'%s'" % r for r in revs[0:3])),
  544. resolved_id,
  545. )
  546. else:
  547. revision = self._revision_map[revs[0]]
  548. if check_branch and revision is not None:
  549. assert branch_rev is not None
  550. assert resolved_id
  551. if not self._shares_lineage(
  552. revision.revision, branch_rev.revision
  553. ):
  554. raise ResolutionError(
  555. "Revision %s is not a member of branch '%s'"
  556. % (revision.revision, check_branch),
  557. resolved_id,
  558. )
  559. return revision
  560. def _filter_into_branch_heads(
  561. self, targets: Iterable[Optional[_RevisionOrBase]]
  562. ) -> Set[Optional[_RevisionOrBase]]:
  563. targets = set(targets)
  564. for rev in list(targets):
  565. assert rev
  566. if targets.intersection(
  567. self._get_descendant_nodes([rev], include_dependencies=False)
  568. ).difference([rev]):
  569. targets.discard(rev)
  570. return targets
  571. def filter_for_lineage(
  572. self,
  573. targets: Iterable[_TR],
  574. check_against: Optional[str],
  575. include_dependencies: bool = False,
  576. ) -> Tuple[_TR, ...]:
  577. id_, branch_label = self._resolve_revision_number(check_against)
  578. shares = []
  579. if branch_label:
  580. shares.append(branch_label)
  581. if id_:
  582. shares.extend(id_)
  583. return tuple(
  584. tg
  585. for tg in targets
  586. if self._shares_lineage(
  587. tg, shares, include_dependencies=include_dependencies
  588. )
  589. )
  590. def _shares_lineage(
  591. self,
  592. target: Optional[_RevisionOrStr],
  593. test_against_revs: Sequence[_RevisionOrStr],
  594. include_dependencies: bool = False,
  595. ) -> bool:
  596. if not test_against_revs:
  597. return True
  598. if not isinstance(target, Revision):
  599. resolved_target = not_none(self._revision_for_ident(target))
  600. else:
  601. resolved_target = target
  602. resolved_test_against_revs = [
  603. self._revision_for_ident(test_against_rev)
  604. if not isinstance(test_against_rev, Revision)
  605. else test_against_rev
  606. for test_against_rev in util.to_tuple(
  607. test_against_revs, default=()
  608. )
  609. ]
  610. return bool(
  611. set(
  612. self._get_descendant_nodes(
  613. [resolved_target],
  614. include_dependencies=include_dependencies,
  615. )
  616. )
  617. .union(
  618. self._get_ancestor_nodes(
  619. [resolved_target],
  620. include_dependencies=include_dependencies,
  621. )
  622. )
  623. .intersection(resolved_test_against_revs)
  624. )
  625. def _resolve_revision_number(
  626. self, id_: Optional[_GetRevArg]
  627. ) -> Tuple[Tuple[str, ...], Optional[str]]:
  628. branch_label: Optional[str]
  629. if isinstance(id_, str) and "@" in id_:
  630. branch_label, id_ = id_.split("@", 1)
  631. elif id_ is not None and (
  632. (isinstance(id_, tuple) and id_ and not isinstance(id_[0], str))
  633. or not isinstance(id_, (str, tuple))
  634. ):
  635. raise RevisionError(
  636. "revision identifier %r is not a string; ensure database "
  637. "driver settings are correct" % (id_,)
  638. )
  639. else:
  640. branch_label = None
  641. # ensure map is loaded
  642. self._revision_map
  643. if id_ == "heads":
  644. if branch_label:
  645. return (
  646. self.filter_for_lineage(self.heads, branch_label),
  647. branch_label,
  648. )
  649. else:
  650. return self._real_heads, branch_label
  651. elif id_ == "head":
  652. current_head = self.get_current_head(branch_label)
  653. if current_head:
  654. return (current_head,), branch_label
  655. else:
  656. return (), branch_label
  657. elif id_ == "base" or id_ is None:
  658. return (), branch_label
  659. else:
  660. return util.to_tuple(id_, default=None), branch_label
  661. def iterate_revisions(
  662. self,
  663. upper: _RevisionIdentifierType,
  664. lower: _RevisionIdentifierType,
  665. implicit_base: bool = False,
  666. inclusive: bool = False,
  667. assert_relative_length: bool = True,
  668. select_for_downgrade: bool = False,
  669. ) -> Iterator[Revision]:
  670. """Iterate through script revisions, starting at the given
  671. upper revision identifier and ending at the lower.
  672. The traversal uses strictly the `down_revision`
  673. marker inside each migration script, so
  674. it is a requirement that upper >= lower,
  675. else you'll get nothing back.
  676. The iterator yields :class:`.Revision` objects.
  677. """
  678. fn: _CollectRevisionsProtocol
  679. if select_for_downgrade:
  680. fn = self._collect_downgrade_revisions
  681. else:
  682. fn = self._collect_upgrade_revisions
  683. revisions, heads = fn(
  684. upper,
  685. lower,
  686. inclusive=inclusive,
  687. implicit_base=implicit_base,
  688. assert_relative_length=assert_relative_length,
  689. )
  690. for node in self._topological_sort(revisions, heads):
  691. yield not_none(self.get_revision(node))
  692. def _get_descendant_nodes(
  693. self,
  694. targets: Collection[Optional[_RevisionOrBase]],
  695. map_: Optional[_RevisionMapType] = None,
  696. check: bool = False,
  697. omit_immediate_dependencies: bool = False,
  698. include_dependencies: bool = True,
  699. ) -> Iterator[Any]:
  700. if omit_immediate_dependencies:
  701. def fn(rev: Revision) -> Iterable[str]:
  702. if rev not in targets:
  703. return rev._all_nextrev
  704. else:
  705. return rev.nextrev
  706. elif include_dependencies:
  707. def fn(rev: Revision) -> Iterable[str]:
  708. return rev._all_nextrev
  709. else:
  710. def fn(rev: Revision) -> Iterable[str]:
  711. return rev.nextrev
  712. return self._iterate_related_revisions(
  713. fn, targets, map_=map_, check=check
  714. )
  715. def _get_ancestor_nodes(
  716. self,
  717. targets: Collection[Optional[_RevisionOrBase]],
  718. map_: Optional[_RevisionMapType] = None,
  719. check: bool = False,
  720. include_dependencies: bool = True,
  721. ) -> Iterator[Revision]:
  722. if include_dependencies:
  723. def fn(rev: Revision) -> Iterable[str]:
  724. return rev._normalized_down_revisions
  725. else:
  726. def fn(rev: Revision) -> Iterable[str]:
  727. return rev._versioned_down_revisions
  728. return self._iterate_related_revisions(
  729. fn, targets, map_=map_, check=check
  730. )
  731. def _iterate_related_revisions(
  732. self,
  733. fn: Callable[[Revision], Iterable[str]],
  734. targets: Collection[Optional[_RevisionOrBase]],
  735. map_: Optional[_RevisionMapType],
  736. check: bool = False,
  737. ) -> Iterator[Revision]:
  738. if map_ is None:
  739. map_ = self._revision_map
  740. seen = set()
  741. todo: Deque[Revision] = collections.deque()
  742. for target_for in targets:
  743. target = is_revision(target_for)
  744. todo.append(target)
  745. if check:
  746. per_target = set()
  747. while todo:
  748. rev = todo.pop()
  749. if check:
  750. per_target.add(rev)
  751. if rev in seen:
  752. continue
  753. seen.add(rev)
  754. # Check for map errors before collecting.
  755. for rev_id in fn(rev):
  756. next_rev = map_[rev_id]
  757. assert next_rev is not None
  758. if next_rev.revision != rev_id:
  759. raise RevisionError(
  760. "Dependency resolution failed; broken map"
  761. )
  762. todo.append(next_rev)
  763. yield rev
  764. if check:
  765. overlaps = per_target.intersection(targets).difference(
  766. [target]
  767. )
  768. if overlaps:
  769. raise RevisionError(
  770. "Requested revision %s overlaps with "
  771. "other requested revisions %s"
  772. % (
  773. target.revision,
  774. ", ".join(r.revision for r in overlaps),
  775. )
  776. )
  777. def _topological_sort(
  778. self,
  779. revisions: Collection[Revision],
  780. heads: Any,
  781. ) -> List[str]:
  782. """Yield revision ids of a collection of Revision objects in
  783. topological sorted order (i.e. revisions always come after their
  784. down_revisions and dependencies). Uses the order of keys in
  785. _revision_map to sort.
  786. """
  787. id_to_rev = self._revision_map
  788. def get_ancestors(rev_id: str) -> Set[str]:
  789. return {
  790. r.revision
  791. for r in self._get_ancestor_nodes([id_to_rev[rev_id]])
  792. }
  793. todo = {d.revision for d in revisions}
  794. # Use revision map (ordered dict) key order to pre-sort.
  795. inserted_order = list(self._revision_map)
  796. current_heads = list(
  797. sorted(
  798. {d.revision for d in heads if d.revision in todo},
  799. key=inserted_order.index,
  800. )
  801. )
  802. ancestors_by_idx = [get_ancestors(rev_id) for rev_id in current_heads]
  803. output = []
  804. current_candidate_idx = 0
  805. while current_heads:
  806. candidate = current_heads[current_candidate_idx]
  807. for check_head_index, ancestors in enumerate(ancestors_by_idx):
  808. # scan all the heads. see if we can continue walking
  809. # down the current branch indicated by current_candidate_idx.
  810. if (
  811. check_head_index != current_candidate_idx
  812. and candidate in ancestors
  813. ):
  814. current_candidate_idx = check_head_index
  815. # nope, another head is dependent on us, they have
  816. # to be traversed first
  817. break
  818. else:
  819. # yup, we can emit
  820. if candidate in todo:
  821. output.append(candidate)
  822. todo.remove(candidate)
  823. # now update the heads with our ancestors.
  824. candidate_rev = id_to_rev[candidate]
  825. assert candidate_rev is not None
  826. heads_to_add = [
  827. r
  828. for r in candidate_rev._normalized_down_revisions
  829. if r in todo and r not in current_heads
  830. ]
  831. if not heads_to_add:
  832. # no ancestors, so remove this head from the list
  833. del current_heads[current_candidate_idx]
  834. del ancestors_by_idx[current_candidate_idx]
  835. current_candidate_idx = max(current_candidate_idx - 1, 0)
  836. else:
  837. if (
  838. not candidate_rev._normalized_resolved_dependencies
  839. and len(candidate_rev._versioned_down_revisions) == 1
  840. ):
  841. current_heads[current_candidate_idx] = heads_to_add[0]
  842. # for plain movement down a revision line without
  843. # any mergepoints, branchpoints, or deps, we
  844. # can update the ancestors collection directly
  845. # by popping out the candidate we just emitted
  846. ancestors_by_idx[current_candidate_idx].discard(
  847. candidate
  848. )
  849. else:
  850. # otherwise recalculate it again, things get
  851. # complicated otherwise. This can possibly be
  852. # improved to not run the whole ancestor thing
  853. # each time but it was getting complicated
  854. current_heads[current_candidate_idx] = heads_to_add[0]
  855. current_heads.extend(heads_to_add[1:])
  856. ancestors_by_idx[
  857. current_candidate_idx
  858. ] = get_ancestors(heads_to_add[0])
  859. ancestors_by_idx.extend(
  860. get_ancestors(head) for head in heads_to_add[1:]
  861. )
  862. assert not todo
  863. return output
  864. def _walk(
  865. self,
  866. start: Optional[Union[str, Revision]],
  867. steps: int,
  868. branch_label: Optional[str] = None,
  869. no_overwalk: bool = True,
  870. ) -> Optional[_RevisionOrBase]:
  871. """
  872. Walk the requested number of :steps up (steps > 0) or down (steps < 0)
  873. the revision tree.
  874. :branch_label is used to select branches only when walking up.
  875. If the walk goes past the boundaries of the tree and :no_overwalk is
  876. True, None is returned, otherwise the walk terminates early.
  877. A RevisionError is raised if there is no unambiguous revision to
  878. walk to.
  879. """
  880. initial: Optional[_RevisionOrBase]
  881. if isinstance(start, str):
  882. initial = self.get_revision(start)
  883. else:
  884. initial = start
  885. children: Sequence[Optional[_RevisionOrBase]]
  886. for _ in range(abs(steps)):
  887. if steps > 0:
  888. assert initial != "base" # type: ignore[comparison-overlap]
  889. # Walk up
  890. walk_up = [
  891. is_revision(rev)
  892. for rev in self.get_revisions(
  893. self.bases if initial is None else initial.nextrev
  894. )
  895. ]
  896. if branch_label:
  897. children = self.filter_for_lineage(walk_up, branch_label)
  898. else:
  899. children = walk_up
  900. else:
  901. # Walk down
  902. if initial == "base": # type: ignore[comparison-overlap]
  903. children = ()
  904. else:
  905. children = self.get_revisions(
  906. self.heads
  907. if initial is None
  908. else initial.down_revision
  909. )
  910. if not children:
  911. children = ("base",)
  912. if not children:
  913. # This will return an invalid result if no_overwalk, otherwise
  914. # further steps will stay where we are.
  915. ret = None if no_overwalk else initial
  916. return ret
  917. elif len(children) > 1:
  918. raise RevisionError("Ambiguous walk")
  919. initial = children[0]
  920. return initial
  921. def _parse_downgrade_target(
  922. self,
  923. current_revisions: _RevisionIdentifierType,
  924. target: _RevisionIdentifierType,
  925. assert_relative_length: bool,
  926. ) -> Tuple[Optional[str], Optional[_RevisionOrBase]]:
  927. """
  928. Parse downgrade command syntax :target to retrieve the target revision
  929. and branch label (if any) given the :current_revisions stamp of the
  930. database.
  931. Returns a tuple (branch_label, target_revision) where branch_label
  932. is a string from the command specifying the branch to consider (or
  933. None if no branch given), and target_revision is a Revision object
  934. which the command refers to. target_revisions is None if the command
  935. refers to 'base'. The target may be specified in absolute form, or
  936. relative to :current_revisions.
  937. """
  938. if target is None:
  939. return None, None
  940. assert isinstance(
  941. target, str
  942. ), "Expected downgrade target in string form"
  943. match = _relative_destination.match(target)
  944. if match:
  945. branch_label, symbol, relative = match.groups()
  946. rel_int = int(relative)
  947. if rel_int >= 0:
  948. if symbol is None:
  949. # Downgrading to current + n is not valid.
  950. raise RevisionError(
  951. "Relative revision %s didn't "
  952. "produce %d migrations" % (relative, abs(rel_int))
  953. )
  954. # Find target revision relative to given symbol.
  955. rev = self._walk(
  956. symbol,
  957. rel_int,
  958. branch_label,
  959. no_overwalk=assert_relative_length,
  960. )
  961. if rev is None:
  962. raise RevisionError("Walked too far")
  963. return branch_label, rev
  964. else:
  965. relative_revision = symbol is None
  966. if relative_revision:
  967. # Find target revision relative to current state.
  968. if branch_label:
  969. cr_tuple = util.to_tuple(current_revisions)
  970. symbol_list: Sequence[str]
  971. symbol_list = self.filter_for_lineage(
  972. cr_tuple, branch_label
  973. )
  974. if not symbol_list:
  975. # check the case where there are multiple branches
  976. # but there is currently a single heads, since all
  977. # other branch heads are dependent of the current
  978. # single heads.
  979. all_current = cast(
  980. Set[Revision], self._get_all_current(cr_tuple)
  981. )
  982. sl_all_current = self.filter_for_lineage(
  983. all_current, branch_label
  984. )
  985. symbol_list = [
  986. r.revision if r else r # type: ignore[misc]
  987. for r in sl_all_current
  988. ]
  989. assert len(symbol_list) == 1
  990. symbol = symbol_list[0]
  991. else:
  992. current_revisions = util.to_tuple(current_revisions)
  993. if not current_revisions:
  994. raise RevisionError(
  995. "Relative revision %s didn't "
  996. "produce %d migrations"
  997. % (relative, abs(rel_int))
  998. )
  999. # Have to check uniques here for duplicate rows test.
  1000. if len(set(current_revisions)) > 1:
  1001. util.warn(
  1002. "downgrade -1 from multiple heads is "
  1003. "ambiguous; "
  1004. "this usage will be disallowed in a future "
  1005. "release."
  1006. )
  1007. symbol = current_revisions[0]
  1008. # Restrict iteration to just the selected branch when
  1009. # ambiguous branches are involved.
  1010. branch_label = symbol
  1011. # Walk down the tree to find downgrade target.
  1012. rev = self._walk(
  1013. start=self.get_revision(symbol)
  1014. if branch_label is None
  1015. else self.get_revision("%s@%s" % (branch_label, symbol)),
  1016. steps=rel_int,
  1017. no_overwalk=assert_relative_length,
  1018. )
  1019. if rev is None:
  1020. if relative_revision:
  1021. raise RevisionError(
  1022. "Relative revision %s didn't "
  1023. "produce %d migrations" % (relative, abs(rel_int))
  1024. )
  1025. else:
  1026. raise RevisionError("Walked too far")
  1027. return branch_label, rev
  1028. # No relative destination given, revision specified is absolute.
  1029. branch_label, _, symbol = target.rpartition("@")
  1030. if not branch_label:
  1031. branch_label = None
  1032. return branch_label, self.get_revision(symbol)
  1033. def _parse_upgrade_target(
  1034. self,
  1035. current_revisions: _RevisionIdentifierType,
  1036. target: _RevisionIdentifierType,
  1037. assert_relative_length: bool,
  1038. ) -> Tuple[Optional[_RevisionOrBase], ...]:
  1039. """
  1040. Parse upgrade command syntax :target to retrieve the target revision
  1041. and given the :current_revisions stamp of the database.
  1042. Returns a tuple of Revision objects which should be iterated/upgraded
  1043. to. The target may be specified in absolute form, or relative to
  1044. :current_revisions.
  1045. """
  1046. if isinstance(target, str):
  1047. match = _relative_destination.match(target)
  1048. else:
  1049. match = None
  1050. if not match:
  1051. # No relative destination, target is absolute.
  1052. return self.get_revisions(target)
  1053. current_revisions_tup: Union[str, Tuple[Optional[str], ...], None]
  1054. current_revisions_tup = util.to_tuple(current_revisions)
  1055. branch_label, symbol, relative_str = match.groups()
  1056. relative = int(relative_str)
  1057. if relative > 0:
  1058. if symbol is None:
  1059. if not current_revisions_tup:
  1060. current_revisions_tup = (None,)
  1061. # Try to filter to a single target (avoid ambiguous branches).
  1062. start_revs = current_revisions_tup
  1063. if branch_label:
  1064. start_revs = self.filter_for_lineage(
  1065. self.get_revisions(current_revisions_tup), # type: ignore[arg-type] # noqa: E501
  1066. branch_label,
  1067. )
  1068. if not start_revs:
  1069. # The requested branch is not a head, so we need to
  1070. # backtrack to find a branchpoint.
  1071. active_on_branch = self.filter_for_lineage(
  1072. self._get_ancestor_nodes(
  1073. self.get_revisions(current_revisions_tup)
  1074. ),
  1075. branch_label,
  1076. )
  1077. # Find the tips of this set of revisions (revisions
  1078. # without children within the set).
  1079. start_revs = tuple(
  1080. {rev.revision for rev in active_on_branch}
  1081. - {
  1082. down
  1083. for rev in active_on_branch
  1084. for down in rev._normalized_down_revisions
  1085. }
  1086. )
  1087. if not start_revs:
  1088. # We must need to go right back to base to find
  1089. # a starting point for this branch.
  1090. start_revs = (None,)
  1091. if len(start_revs) > 1:
  1092. raise RevisionError(
  1093. "Ambiguous upgrade from multiple current revisions"
  1094. )
  1095. # Walk up from unique target revision.
  1096. rev = self._walk(
  1097. start=start_revs[0],
  1098. steps=relative,
  1099. branch_label=branch_label,
  1100. no_overwalk=assert_relative_length,
  1101. )
  1102. if rev is None:
  1103. raise RevisionError(
  1104. "Relative revision %s didn't "
  1105. "produce %d migrations" % (relative_str, abs(relative))
  1106. )
  1107. return (rev,)
  1108. else:
  1109. # Walk is relative to a given revision, not the current state.
  1110. return (
  1111. self._walk(
  1112. start=self.get_revision(symbol),
  1113. steps=relative,
  1114. branch_label=branch_label,
  1115. no_overwalk=assert_relative_length,
  1116. ),
  1117. )
  1118. else:
  1119. if symbol is None:
  1120. # Upgrading to current - n is not valid.
  1121. raise RevisionError(
  1122. "Relative revision %s didn't "
  1123. "produce %d migrations" % (relative, abs(relative))
  1124. )
  1125. return (
  1126. self._walk(
  1127. start=self.get_revision(symbol)
  1128. if branch_label is None
  1129. else self.get_revision("%s@%s" % (branch_label, symbol)),
  1130. steps=relative,
  1131. no_overwalk=assert_relative_length,
  1132. ),
  1133. )
  1134. def _collect_downgrade_revisions(
  1135. self,
  1136. upper: _RevisionIdentifierType,
  1137. lower: _RevisionIdentifierType,
  1138. inclusive: bool,
  1139. implicit_base: bool,
  1140. assert_relative_length: bool,
  1141. ) -> Tuple[Set[Revision], Tuple[Optional[_RevisionOrBase], ...]]:
  1142. """
  1143. Compute the set of current revisions specified by :upper, and the
  1144. downgrade target specified by :target. Return all dependents of target
  1145. which are currently active.
  1146. :inclusive=True includes the target revision in the set
  1147. """
  1148. branch_label, target_revision = self._parse_downgrade_target(
  1149. current_revisions=upper,
  1150. target=lower,
  1151. assert_relative_length=assert_relative_length,
  1152. )
  1153. if target_revision == "base":
  1154. target_revision = None
  1155. assert target_revision is None or isinstance(target_revision, Revision)
  1156. roots: List[Revision]
  1157. # Find candidates to drop.
  1158. if target_revision is None:
  1159. # Downgrading back to base: find all tree roots.
  1160. roots = [
  1161. rev
  1162. for rev in self._revision_map.values()
  1163. if rev is not None and rev.down_revision is None
  1164. ]
  1165. elif inclusive:
  1166. # inclusive implies target revision should also be dropped
  1167. roots = [target_revision]
  1168. else:
  1169. # Downgrading to fixed target: find all direct children.
  1170. roots = [
  1171. is_revision(rev)
  1172. for rev in self.get_revisions(target_revision.nextrev)
  1173. ]
  1174. if branch_label and len(roots) > 1:
  1175. # Need to filter roots.
  1176. ancestors = {
  1177. rev.revision
  1178. for rev in self._get_ancestor_nodes(
  1179. [self._resolve_branch(branch_label)],
  1180. include_dependencies=False,
  1181. )
  1182. }
  1183. # Intersection gives the root revisions we are trying to
  1184. # rollback with the downgrade.
  1185. roots = [
  1186. is_revision(rev)
  1187. for rev in self.get_revisions(
  1188. {rev.revision for rev in roots}.intersection(ancestors)
  1189. )
  1190. ]
  1191. # Ensure we didn't throw everything away when filtering branches.
  1192. if len(roots) == 0:
  1193. raise RevisionError(
  1194. "Not a valid downgrade target from current heads"
  1195. )
  1196. heads = self.get_revisions(upper)
  1197. # Aim is to drop :branch_revision; to do so we also need to drop its
  1198. # descendents and anything dependent on it.
  1199. downgrade_revisions = set(
  1200. self._get_descendant_nodes(
  1201. roots,
  1202. include_dependencies=True,
  1203. omit_immediate_dependencies=False,
  1204. )
  1205. )
  1206. active_revisions = set(
  1207. self._get_ancestor_nodes(heads, include_dependencies=True)
  1208. )
  1209. # Emit revisions to drop in reverse topological sorted order.
  1210. downgrade_revisions.intersection_update(active_revisions)
  1211. if implicit_base:
  1212. # Wind other branches back to base.
  1213. downgrade_revisions.update(
  1214. active_revisions.difference(self._get_ancestor_nodes(roots))
  1215. )
  1216. if (
  1217. target_revision is not None
  1218. and not downgrade_revisions
  1219. and target_revision not in heads
  1220. ):
  1221. # Empty intersection: target revs are not present.
  1222. raise RangeNotAncestorError("Nothing to drop", upper)
  1223. return downgrade_revisions, heads
  1224. def _collect_upgrade_revisions(
  1225. self,
  1226. upper: _RevisionIdentifierType,
  1227. lower: _RevisionIdentifierType,
  1228. inclusive: bool,
  1229. implicit_base: bool,
  1230. assert_relative_length: bool,
  1231. ) -> Tuple[Set[Revision], Tuple[Revision, ...]]:
  1232. """
  1233. Compute the set of required revisions specified by :upper, and the
  1234. current set of active revisions specified by :lower. Find the
  1235. difference between the two to compute the required upgrades.
  1236. :inclusive=True includes the current/lower revisions in the set
  1237. :implicit_base=False only returns revisions which are downstream
  1238. of the current/lower revisions. Dependencies from branches with
  1239. different bases will not be included.
  1240. """
  1241. targets: Collection[Revision] = [
  1242. is_revision(rev)
  1243. for rev in self._parse_upgrade_target(
  1244. current_revisions=lower,
  1245. target=upper,
  1246. assert_relative_length=assert_relative_length,
  1247. )
  1248. ]
  1249. # assert type(targets) is tuple, "targets should be a tuple"
  1250. # Handled named bases (e.g. branch@... -> heads should only produce
  1251. # targets on the given branch)
  1252. if isinstance(lower, str) and "@" in lower:
  1253. branch, _, _ = lower.partition("@")
  1254. branch_rev = self.get_revision(branch)
  1255. if branch_rev is not None and branch_rev.revision == branch:
  1256. # A revision was used as a label; get its branch instead
  1257. assert len(branch_rev.branch_labels) == 1
  1258. branch = next(iter(branch_rev.branch_labels))
  1259. targets = {
  1260. need for need in targets if branch in need.branch_labels
  1261. }
  1262. required_node_set = set(
  1263. self._get_ancestor_nodes(
  1264. targets, check=True, include_dependencies=True
  1265. )
  1266. ).union(targets)
  1267. current_revisions = self.get_revisions(lower)
  1268. if not implicit_base and any(
  1269. rev not in required_node_set
  1270. for rev in current_revisions
  1271. if rev is not None
  1272. ):
  1273. raise RangeNotAncestorError(lower, upper)
  1274. assert (
  1275. type(current_revisions) is tuple
  1276. ), "current_revisions should be a tuple"
  1277. # Special case where lower = a relative value (get_revisions can't
  1278. # find it)
  1279. if current_revisions and current_revisions[0] is None:
  1280. _, rev = self._parse_downgrade_target(
  1281. current_revisions=upper,
  1282. target=lower,
  1283. assert_relative_length=assert_relative_length,
  1284. )
  1285. assert rev
  1286. if rev == "base":
  1287. current_revisions = tuple()
  1288. lower = None
  1289. else:
  1290. current_revisions = (rev,)
  1291. lower = rev.revision
  1292. current_node_set = set(
  1293. self._get_ancestor_nodes(
  1294. current_revisions, check=True, include_dependencies=True
  1295. )
  1296. ).union(current_revisions)
  1297. needs = required_node_set.difference(current_node_set)
  1298. # Include the lower revision (=current_revisions?) in the iteration
  1299. if inclusive:
  1300. needs.update(is_revision(rev) for rev in self.get_revisions(lower))
  1301. # By default, base is implicit as we want all dependencies returned.
  1302. # Base is also implicit if lower = base
  1303. # implicit_base=False -> only return direct downstreams of
  1304. # current_revisions
  1305. if current_revisions and not implicit_base:
  1306. lower_descendents = self._get_descendant_nodes(
  1307. [is_revision(rev) for rev in current_revisions],
  1308. check=True,
  1309. include_dependencies=False,
  1310. )
  1311. needs.intersection_update(lower_descendents)
  1312. return needs, tuple(targets)
  1313. def _get_all_current(
  1314. self, id_: Tuple[str, ...]
  1315. ) -> Set[Optional[_RevisionOrBase]]:
  1316. top_revs: Set[Optional[_RevisionOrBase]]
  1317. top_revs = set(self.get_revisions(id_))
  1318. top_revs.update(
  1319. self._get_ancestor_nodes(list(top_revs), include_dependencies=True)
  1320. )
  1321. return self._filter_into_branch_heads(top_revs)
  1322. class Revision:
  1323. """Base class for revisioned objects.
  1324. The :class:`.Revision` class is the base of the more public-facing
  1325. :class:`.Script` object, which represents a migration script.
  1326. The mechanics of revision management and traversal are encapsulated
  1327. within :class:`.Revision`, while :class:`.Script` applies this logic
  1328. to Python files in a version directory.
  1329. """
  1330. nextrev: FrozenSet[str] = frozenset()
  1331. """following revisions, based on down_revision only."""
  1332. _all_nextrev: FrozenSet[str] = frozenset()
  1333. revision: str = None # type: ignore[assignment]
  1334. """The string revision number."""
  1335. down_revision: Optional[_RevIdType] = None
  1336. """The ``down_revision`` identifier(s) within the migration script.
  1337. Note that the total set of "down" revisions is
  1338. down_revision + dependencies.
  1339. """
  1340. dependencies: Optional[_RevIdType] = None
  1341. """Additional revisions which this revision is dependent on.
  1342. From a migration standpoint, these dependencies are added to the
  1343. down_revision to form the full iteration. However, the separation
  1344. of down_revision from "dependencies" is to assist in navigating
  1345. a history that contains many branches, typically a multi-root scenario.
  1346. """
  1347. branch_labels: Set[str] = None # type: ignore[assignment]
  1348. """Optional string/tuple of symbolic names to apply to this
  1349. revision's branch"""
  1350. _resolved_dependencies: Tuple[str, ...]
  1351. _normalized_resolved_dependencies: Tuple[str, ...]
  1352. @classmethod
  1353. def verify_rev_id(cls, revision: str) -> None:
  1354. illegal_chars = set(revision).intersection(_revision_illegal_chars)
  1355. if illegal_chars:
  1356. raise RevisionError(
  1357. "Character(s) '%s' not allowed in revision identifier '%s'"
  1358. % (", ".join(sorted(illegal_chars)), revision)
  1359. )
  1360. def __init__(
  1361. self,
  1362. revision: str,
  1363. down_revision: Optional[Union[str, Tuple[str, ...]]],
  1364. dependencies: Optional[Union[str, Tuple[str, ...]]] = None,
  1365. branch_labels: Optional[Union[str, Tuple[str, ...]]] = None,
  1366. ) -> None:
  1367. if down_revision and revision in util.to_tuple(down_revision):
  1368. raise LoopDetected(revision)
  1369. elif dependencies is not None and revision in util.to_tuple(
  1370. dependencies
  1371. ):
  1372. raise DependencyLoopDetected(revision)
  1373. self.verify_rev_id(revision)
  1374. self.revision = revision
  1375. self.down_revision = tuple_rev_as_scalar(util.to_tuple(down_revision))
  1376. self.dependencies = tuple_rev_as_scalar(util.to_tuple(dependencies))
  1377. self._orig_branch_labels = util.to_tuple(branch_labels, default=())
  1378. self.branch_labels = set(self._orig_branch_labels)
  1379. def __repr__(self) -> str:
  1380. args = [repr(self.revision), repr(self.down_revision)]
  1381. if self.dependencies:
  1382. args.append("dependencies=%r" % (self.dependencies,))
  1383. if self.branch_labels:
  1384. args.append("branch_labels=%r" % (self.branch_labels,))
  1385. return "%s(%s)" % (self.__class__.__name__, ", ".join(args))
  1386. def add_nextrev(self, revision: Revision) -> None:
  1387. self._all_nextrev = self._all_nextrev.union([revision.revision])
  1388. if self.revision in revision._versioned_down_revisions:
  1389. self.nextrev = self.nextrev.union([revision.revision])
  1390. @property
  1391. def _all_down_revisions(self) -> Tuple[str, ...]:
  1392. return util.dedupe_tuple(
  1393. util.to_tuple(self.down_revision, default=())
  1394. + self._resolved_dependencies
  1395. )
  1396. @property
  1397. def _normalized_down_revisions(self) -> Tuple[str, ...]:
  1398. """return immediate down revisions for a rev, omitting dependencies
  1399. that are still dependencies of ancestors.
  1400. """
  1401. return util.dedupe_tuple(
  1402. util.to_tuple(self.down_revision, default=())
  1403. + self._normalized_resolved_dependencies
  1404. )
  1405. @property
  1406. def _versioned_down_revisions(self) -> Tuple[str, ...]:
  1407. return util.to_tuple(self.down_revision, default=())
  1408. @property
  1409. def is_head(self) -> bool:
  1410. """Return True if this :class:`.Revision` is a 'head' revision.
  1411. This is determined based on whether any other :class:`.Script`
  1412. within the :class:`.ScriptDirectory` refers to this
  1413. :class:`.Script`. Multiple heads can be present.
  1414. """
  1415. return not bool(self.nextrev)
  1416. @property
  1417. def _is_real_head(self) -> bool:
  1418. return not bool(self._all_nextrev)
  1419. @property
  1420. def is_base(self) -> bool:
  1421. """Return True if this :class:`.Revision` is a 'base' revision."""
  1422. return self.down_revision is None
  1423. @property
  1424. def _is_real_base(self) -> bool:
  1425. """Return True if this :class:`.Revision` is a "real" base revision,
  1426. e.g. that it has no dependencies either."""
  1427. # we use self.dependencies here because this is called up
  1428. # in initialization where _real_dependencies isn't set up
  1429. # yet
  1430. return self.down_revision is None and self.dependencies is None
  1431. @property
  1432. def is_branch_point(self) -> bool:
  1433. """Return True if this :class:`.Script` is a branch point.
  1434. A branchpoint is defined as a :class:`.Script` which is referred
  1435. to by more than one succeeding :class:`.Script`, that is more
  1436. than one :class:`.Script` has a `down_revision` identifier pointing
  1437. here.
  1438. """
  1439. return len(self.nextrev) > 1
  1440. @property
  1441. def _is_real_branch_point(self) -> bool:
  1442. """Return True if this :class:`.Script` is a 'real' branch point,
  1443. taking into account dependencies as well.
  1444. """
  1445. return len(self._all_nextrev) > 1
  1446. @property
  1447. def is_merge_point(self) -> bool:
  1448. """Return True if this :class:`.Script` is a merge point."""
  1449. return len(self._versioned_down_revisions) > 1
  1450. @overload
  1451. def tuple_rev_as_scalar(rev: None) -> None:
  1452. ...
  1453. @overload
  1454. def tuple_rev_as_scalar(
  1455. rev: Union[Tuple[_T, ...], List[_T]]
  1456. ) -> Union[_T, Tuple[_T, ...], List[_T]]:
  1457. ...
  1458. def tuple_rev_as_scalar(
  1459. rev: Optional[Sequence[_T]],
  1460. ) -> Union[_T, Sequence[_T], None]:
  1461. if not rev:
  1462. return None
  1463. elif len(rev) == 1:
  1464. return rev[0]
  1465. else:
  1466. return rev
  1467. def is_revision(rev: Any) -> Revision:
  1468. assert isinstance(rev, Revision)
  1469. return rev