common.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. # Copyright 2021-2025 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. # --------------------------------------------------------------------------------------------------
  12. # Common artifacts used by the other scripts located in this directory.
  13. # --------------------------------------------------------------------------------------------------
  14. import argparse
  15. import json
  16. import os
  17. import re
  18. import subprocess
  19. import typing as t
  20. from dataclasses import asdict, dataclass
  21. from datetime import datetime
  22. from pathlib import Path
  23. import requests
  24. # --------------------------------------------------------------------------------------------------
  25. @dataclass(frozen=True)
  26. class Version:
  27. """Helps manipulate version numbers."""
  28. major: int
  29. minor: int
  30. patch: int = 0
  31. ext: t.Optional[str] = None
  32. # Matching level
  33. MAJOR: t.ClassVar[int] = 1
  34. MINOR: t.ClassVar[int] = 2
  35. PATCH: t.ClassVar[int] = 3
  36. # Unknown version constant
  37. UNKNOWN: t.ClassVar["Version"]
  38. @property
  39. def name(self) -> str:
  40. """Returns a string representation of this Version without the extension part."""
  41. return f"{self.major}.{self.minor}.{self.patch}"
  42. @property
  43. def full_name(self) -> str:
  44. """Returns a full string representation of this Version."""
  45. return f"{self.name}.{self.ext}" if self.ext else self.name
  46. def __str__(self) -> str:
  47. """Returns a string representation of this version."""
  48. return self.full_name
  49. def __repr__(self) -> str:
  50. """Returns a full string representation of this version."""
  51. ext = f".{self.ext}" if self.ext else ""
  52. return f"Version({self.major}.{self.minor}.{self.patch}{ext})"
  53. @classmethod
  54. def from_string(cls, version: str):
  55. """Creates a Version from a string.
  56. Arguments:
  57. version: a version name as a string.<br/>
  58. The format should be "<major>.<minor>[.<patch>[.<extension>]] where
  59. - <major> must be a number, indicating the major number of the version
  60. - <minor> must be a number, indicating the minor number of the version
  61. - <patch> must be a number, indicating the patch level of the version. Optional.
  62. - <extension> must be a string. It is common practice that <extension> ends with a
  63. number, but it is not required. Optional.
  64. Returns:
  65. A new Version object with the appropriate values that were parsed.
  66. """
  67. match = re.fullmatch(r"(\d+)\.(\d+)(?:\.(\d+))?(?:\.([^\s]+))?", version)
  68. if match:
  69. major = int(match[1])
  70. minor = int(match[2])
  71. patch = int(match[3]) if match[3] else 0
  72. ext = match[4]
  73. return cls(major=major, minor=minor, patch=patch, ext=ext)
  74. else:
  75. raise ValueError(f"String not in expected format: {version}")
  76. def to_dict(self) -> dict[str, str]:
  77. """Returns this Version as a dictionary."""
  78. return {k: v for k, v in asdict(self).items() if v is not None}
  79. @staticmethod
  80. def check_argument(value: str) -> "Version":
  81. """Checks version parameter in an argparse context."""
  82. try:
  83. version = Version.from_string(value)
  84. except Exception as e:
  85. raise argparse.ArgumentTypeError(f"'{value}' is not a valid version number.") from e
  86. return version
  87. def validate_extension(self, ext="dev"):
  88. """Returns True if the extension part of this Version is the one queried."""
  89. return self.split_ext()[0] == ext
  90. def split_ext(self) -> t.Tuple[str, int]:
  91. """Splits extension into the (identifier, index) tuple
  92. Returns:
  93. ("", -1) if there is no extension.
  94. (extension, -1) if there is no extension index.
  95. (extension, index) if there is an extension index (e.g. "dev3").
  96. """
  97. if not self.ext or (match := re.fullmatch(r"(.*?)(\d+)?", self.ext)) is None:
  98. return ("", -1) # No extension
  99. # Potentially no index
  100. return (match[1], int(match[2]) if match[2] else -1)
  101. def is_compatible(self, version: "Version") -> bool:
  102. """Checks if this version is compatible with another.
  103. Version v1 is defined as being compatible with version v2 if a package built with version v1
  104. can safely depend on another package built with version v2.<br/>
  105. Here are the conditions set when checking whether v1 is compatible with v2:
  106. - If v1 and v2 have different major or minor numbers, they are not compatible.
  107. - If v1 has no extension, it is compatible only with v2 that have no extension.
  108. - If v1 has an extension, it is compatible with any v2 that has the same extension, no
  109. matter the extension index.
  110. I.e.:
  111. package-1.[m].[t] is NOT compatible with any sub-package-[M].* where M != 1
  112. package-1.2.[t] is NOT compatible with any sub-package-1.[m].* where m != 2
  113. package-1.2.[t] is compatible with all sub-package-1.2.*
  114. package-1.2.[t].ext[X] is compatible with all sub-package-1.2.*.ext*
  115. package-1.2.3 is NOT compatible with any sub-package-1.2.*.*
  116. package-1.2.3.extA is NOT compatible with any sub-package-1.2.*.extB if extA != extB,
  117. independently of a potential extension index.
  118. Arguments:
  119. version: the version to check compatibility against.
  120. Returns:
  121. True is this Version is compatible with *version* and False if it is not.
  122. """
  123. if self.major != version.major or self.minor != version.minor:
  124. return False
  125. if self.patch > version.patch:
  126. return True
  127. # No extensions on either → Compatible
  128. if not self.ext and not version.ext:
  129. return True
  130. # self has extension, version doesn't → Compatible
  131. if self.ext and not version.ext:
  132. return True
  133. # Version has extension, self doesn't → Not compatible
  134. if not self.ext and version.ext:
  135. return False
  136. # Both have extensions → check identifiers. Dissimilar identifiers → Not compatible
  137. self_prefix, _ = self.split_ext()
  138. other_prefix, _ = version.split_ext()
  139. if self_prefix != other_prefix:
  140. return False
  141. # Same identifiers → Compatible
  142. return True
  143. def matches(self, version: "Version", level: int = PATCH) -> bool:
  144. """Checks whether this version matches another, up to some level.
  145. Arguments:
  146. version: The version to check against.
  147. level: The level of precision for the match:
  148. - Version.MAJOR: compare only the major version;
  149. - Version.MINOR: compare major and minor versions;
  150. - Version.PATCH: compare major, minor, and patch versions.
  151. Returns:
  152. True if the versions match up to the given level, False otherwise.
  153. """
  154. if self.major != version.major:
  155. return False
  156. if level >= self.MINOR and self.minor != version.minor:
  157. return False
  158. if level >= self.PATCH and self.patch != version.patch:
  159. return False
  160. return True
  161. def __lt__(self, other: "Version") -> bool:
  162. if not isinstance(other, Version):
  163. return NotImplemented
  164. # Compare major, minor, patch
  165. self_tuple = (self.major, self.minor, self.patch)
  166. other_tuple = (other.major, other.minor, other.patch)
  167. if self_tuple != other_tuple:
  168. return self_tuple < other_tuple
  169. # Same version number, now compare extensions
  170. return self._ext_sort_key() < other._ext_sort_key()
  171. def _ext_sort_key(self) -> t.Tuple[int, str, int]:
  172. """
  173. Defines ordering for extensions.
  174. Final versions (None) are considered greater than prereleases.
  175. Example sort order:
  176. 1.0.0.dev1 < 1.0.0.rc1 < 1.0.0 < 1.0.1
  177. """
  178. if self.ext is None:
  179. return (2, "", 0) # Final release — highest priority
  180. # Parse extension like "dev1" into prefix + number
  181. match = re.match(r"([a-zA-Z]+)(\d*)", self.ext)
  182. if match:
  183. label, num = match.groups()
  184. num_val = int(num) if num else 0
  185. return (1, label, num_val) # Pre-release
  186. else:
  187. return (0, self.ext, 0) # Unknown extension format — lowest priority
  188. Version.UNKNOWN = Version(0, 0)
  189. # --------------------------------------------------------------------------------------------------
  190. class Package:
  191. """Information on any Taipy package and sub-package."""
  192. # Base names of the sub packages taipy-*
  193. # They also are the names of the directory where their code belongs, under the 'taipy' directory,
  194. # in the root of the Taipy repository.
  195. # Order is important: package that are dependent of others must appear first.
  196. NAMES = ["common", "core", "gui", "rest", "templates"]
  197. _packages = {}
  198. def __new__(cls, name: str) -> "Package":
  199. if name.startswith("taipy-"):
  200. name = name[6:]
  201. if name in cls._packages:
  202. return cls._packages[name]
  203. package = super().__new__(cls)
  204. cls._packages[name] = package
  205. return package
  206. def __init__(self, package: str) -> None:
  207. self._name = package
  208. if package == "taipy":
  209. self._short = package
  210. else:
  211. if package.startswith("taipy-"):
  212. self._short = package[6:]
  213. else:
  214. self._name = f"taipy-{package}"
  215. self._short = package
  216. if self._short not in Package.NAMES:
  217. raise ValueError(f"Invalid package name '{package}'.")
  218. @classmethod
  219. def names(cls, add_taipy=False) -> list[str]:
  220. return cls.NAMES + (["taipy"] if add_taipy else [])
  221. @staticmethod
  222. def check_argument(value: str) -> str:
  223. """Checks package parameter in an argparse context."""
  224. n_value = value.lower()
  225. if n_value in Package.names(True) or value == "all":
  226. return n_value
  227. raise argparse.ArgumentTypeError(f"'{value}' is not a valid Taipy package name.")
  228. @property
  229. def name(self) -> str:
  230. """The full package name."""
  231. return self._name
  232. @property
  233. def short_name(self) -> str:
  234. """The short package name."""
  235. return self._short
  236. @property
  237. def package_dir(self) -> str:
  238. return "taipy" if self._name == "taipy" else os.path.join("taipy", self._short)
  239. def load_version(self) -> Version:
  240. """
  241. Returns the Version defined in this package's version.json content.
  242. """
  243. with open(Path(self.package_dir) / "version.json") as version_file:
  244. data = json.load(version_file)
  245. return Version(**data)
  246. def save_version(self, version: Version) -> None:
  247. """
  248. Saves the Version to this package's version.json file.
  249. """
  250. with open(os.path.join(Path(self.package_dir), "version.json"), "w") as version_file:
  251. json.dump(version.to_dict(), version_file)
  252. def __str__(self) -> str:
  253. """Returns a string representation of this package."""
  254. return self.name
  255. def __repr__(self) -> str:
  256. """Returns a full string representation of this package."""
  257. return f"Package({self.name})"
  258. def __eq__(self, other):
  259. return isinstance(other, Package) and (self._short, self._short) == (other._short, other._short)
  260. def __hash__(self):
  261. return hash(self._short)
  262. # --------------------------------------------------------------------------------------------------
  263. def run_command(*args) -> str:
  264. return subprocess.run(args, stdout=subprocess.PIPE, text=True, check=True).stdout.strip()
  265. # --------------------------------------------------------------------------------------------------
  266. class Git:
  267. @staticmethod
  268. def get_current_branch() -> str:
  269. return run_command("git", "branch", "--show-current")
  270. @staticmethod
  271. def get_github_path() -> t.Optional[str]:
  272. """Retrieve current Git path (<owner>/<repo>)."""
  273. branch_name = Git.get_current_branch()
  274. remote_name = run_command("git", "config", f"branch.{branch_name}.remote")
  275. url = run_command("git", "remote", "get-url", remote_name)
  276. if match := re.fullmatch(r"(?:git@github\.com:|https://github\.com/)(.*)\.git", url):
  277. return match[1]
  278. print("ERROR - Could not retrieve GibHub branch path") # noqa: T201
  279. return None
  280. # --------------------------------------------------------------------------------------------------
  281. class Release(t.TypedDict):
  282. version: Version
  283. id: str
  284. tag: str
  285. published_at: str
  286. def fetch_github_releases(gh_path: t.Optional[str] = None) -> dict[Package, list[Release]]:
  287. # Retrieve all available releases (potentially paginating results) for all packages.
  288. # Returns a dictionary of package_short_name/list-of-releases pairs.
  289. # A 'release' is a dictionary where "version" if the package version, "id" is the release id and
  290. # "tag" is the release tag name.
  291. headers = {"Accept": "application/vnd.github+json"}
  292. all_releases: dict[str, list[Release]] = {}
  293. if gh_path is None:
  294. gh_path = Git.get_github_path()
  295. if gh_path is None:
  296. raise ValueError("Couldn't figure out GitHub branch path.")
  297. url = f"https://api.github.com/repos/{gh_path}/releases"
  298. page = 1
  299. # Read all release versions and store them in a package_name - list[Version] dictionary
  300. while url:
  301. response = requests.get(url, params={"per_page": 50, "page": page}, headers=headers)
  302. response.raise_for_status() # Raise error for bad responses
  303. for release in response.json():
  304. release_id = release["id"]
  305. tag = release["tag_name"]
  306. published_at = release["published_at"]
  307. pkg_ver, pkg = tag.split("-") if "-" in tag else (tag, "taipy")
  308. # Drop legacy packages (config...)
  309. if pkg != "taipy" and pkg not in Package.NAMES:
  310. continue
  311. # Exception for legacy version: v1.0.0 -> 1.0.0
  312. if pkg_ver == "v1.0.0":
  313. pkg_ver = pkg_ver[1:]
  314. version = Version.from_string(pkg_ver)
  315. new_release: Release = {"version": version, "id": release_id, "tag": tag, "published_at": published_at}
  316. if releases := all_releases.get(pkg):
  317. releases.append(new_release)
  318. else:
  319. all_releases[pkg] = [new_release]
  320. # Check for pagination in the `Link` header
  321. link_header = response.headers.get("Link", "")
  322. if 'rel="next"' in link_header:
  323. url = link_header.split(";")[0].strip("<>") # Extract next page URL
  324. page += 1
  325. else:
  326. url = None # No more pages
  327. # Sort all releases for all packages by publishing date (most recent first)
  328. for p in all_releases.keys():
  329. all_releases[p].sort(
  330. key=lambda r: datetime.fromisoformat(r["published_at"].replace("Z", "+00:00")), reverse=True
  331. )
  332. # Build and return the dictionary using Package instances
  333. return {Package(p): v for p, v in all_releases.items()}
  334. # --------------------------------------------------------------------------------------------------
  335. def fetch_latest_github_taipy_releases(
  336. all_releases: t.Optional[dict[Package, list[Release]]] = None, gh_path: t.Optional[str] = None
  337. ) -> Version:
  338. # Retrieve all available releases if necessary
  339. if all_releases is None:
  340. all_releases = fetch_github_releases(gh_path)
  341. # Find the latest 'taipy' version that has no extension
  342. latest_taipy_version = Version.UNKNOWN
  343. releases = all_releases.get(Package("taipy"))
  344. if releases := all_releases.get(Package("taipy")):
  345. # Retrieve all non-dev releases
  346. versions = [release["version"] for release in releases if release["version"].ext is None]
  347. # Find the latest
  348. if versions:
  349. latest_taipy_version = max(versions)
  350. return latest_taipy_version