|
| 1 | +import datetime |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import shutil |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +import tempfile |
| 8 | +from contextlib import AbstractContextManager |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +from databricks.sdk import WorkspaceClient |
| 12 | +from databricks.sdk.mixins.compute import SemVer |
| 13 | +from databricks.sdk.service.workspace import ImportFormat |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class Wheels(AbstractContextManager): |
| 19 | + def __init__(self, ws: WorkspaceClient, install_folder: str, released_version: str): |
| 20 | + self._ws = ws |
| 21 | + self._this_file = Path(__file__) |
| 22 | + self._install_folder = install_folder |
| 23 | + self._released_version = released_version |
| 24 | + |
| 25 | + def version(self): |
| 26 | + if hasattr(self, "__version"): |
| 27 | + return self.__version |
| 28 | + project_root = find_project_root() |
| 29 | + if not (project_root / ".git/config").exists(): |
| 30 | + # normal install, downloaded releases won't have the .git folder |
| 31 | + return self._released_version |
| 32 | + try: |
| 33 | + out = subprocess.run(["git", "describe", "--tags"], stdout=subprocess.PIPE, check=True) # noqa S607 |
| 34 | + git_detached_version = out.stdout.decode("utf8") |
| 35 | + dv = SemVer.parse(git_detached_version) |
| 36 | + datestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") |
| 37 | + # new commits on main branch since the last tag |
| 38 | + new_commits = dv.pre_release.split("-")[0] if dv.pre_release else None |
| 39 | + # show that it's a version different from the released one in stats |
| 40 | + bump_patch = dv.patch + 1 |
| 41 | + # create something that is both https://semver.org and https://peps.python.org/pep-0440/ |
| 42 | + semver_and_pep0440 = f"{dv.major}.{dv.minor}.{bump_patch}+{new_commits}{datestamp}" |
| 43 | + # validate the semver |
| 44 | + SemVer.parse(semver_and_pep0440) |
| 45 | + self.__version = semver_and_pep0440 |
| 46 | + return semver_and_pep0440 |
| 47 | + except Exception as err: |
| 48 | + msg = ( |
| 49 | + f"Cannot determine unreleased version. Please report this error " |
| 50 | + f"message that you see on https://github.com/databrickslabs/ucx/issues/new. " |
| 51 | + f"Meanwhile, download, unpack, and install the latest released version from " |
| 52 | + f"https://github.com/databrickslabs/ucx/releases. Original error is: {err!s}" |
| 53 | + ) |
| 54 | + raise OSError(msg) from None |
| 55 | + |
| 56 | + def __enter__(self) -> "Wheels": |
| 57 | + self._tmp_dir = tempfile.TemporaryDirectory() |
| 58 | + self._local_wheel = self._build_wheel(self._tmp_dir.name) |
| 59 | + self._remote_wheel = f"{self._install_folder}/wheels/{self._local_wheel.name}" |
| 60 | + self._remote_dirname = os.path.dirname(self._remote_wheel) |
| 61 | + return self |
| 62 | + |
| 63 | + def __exit__(self, __exc_type, __exc_value, __traceback): |
| 64 | + self._tmp_dir.cleanup() |
| 65 | + |
| 66 | + def upload_to_dbfs(self) -> str: |
| 67 | + with self._local_wheel.open("rb") as f: |
| 68 | + self._ws.dbfs.mkdirs(self._remote_dirname) |
| 69 | + logger.info(f"Uploading wheel to dbfs:{self._remote_wheel}") |
| 70 | + self._ws.dbfs.upload(self._remote_wheel, f, overwrite=True) |
| 71 | + return self._remote_wheel |
| 72 | + |
| 73 | + def upload_to_wsfs(self) -> str: |
| 74 | + with self._local_wheel.open("rb") as f: |
| 75 | + self._ws.workspace.mkdirs(self._remote_dirname) |
| 76 | + logger.info(f"Uploading wheel to /Workspace{self._remote_wheel}") |
| 77 | + self._ws.workspace.upload(self._remote_wheel, f, overwrite=True, format=ImportFormat.AUTO) |
| 78 | + return self._remote_wheel |
| 79 | + |
| 80 | + def _build_wheel(self, tmp_dir: str, *, verbose: bool = False): |
| 81 | + """Helper to build the wheel package""" |
| 82 | + stdout = subprocess.STDOUT |
| 83 | + stderr = subprocess.STDOUT |
| 84 | + if not verbose: |
| 85 | + stdout = subprocess.DEVNULL |
| 86 | + stderr = subprocess.DEVNULL |
| 87 | + project_root = find_project_root() |
| 88 | + is_non_released_version = "+" in self.version() |
| 89 | + if (project_root / ".git" / "config").exists() and is_non_released_version: |
| 90 | + tmp_dir_path = Path(tmp_dir) / "working-copy" |
| 91 | + # copy everything to a temporary directory |
| 92 | + shutil.copytree(project_root, tmp_dir_path) |
| 93 | + # and override the version file |
| 94 | + # TODO: make it configurable |
| 95 | + version_file = tmp_dir_path / "src/databricks/labs/ucx/__about__.py" |
| 96 | + with version_file.open("w") as f: |
| 97 | + f.write(f'__version__ = "{self.version()}"') |
| 98 | + # working copy becomes project root for building a wheel |
| 99 | + project_root = tmp_dir_path |
| 100 | + logger.debug(f"Building wheel for {project_root} in {tmp_dir}") |
| 101 | + subprocess.run( |
| 102 | + [sys.executable, "-m", "pip", "wheel", "--no-deps", "--wheel-dir", tmp_dir, project_root.as_posix()], |
| 103 | + check=True, |
| 104 | + stdout=stdout, |
| 105 | + stderr=stderr, |
| 106 | + ) |
| 107 | + # get wheel name as first file in the temp directory |
| 108 | + return next(Path(tmp_dir).glob("*.whl")) |
| 109 | + |
| 110 | + |
| 111 | +def find_project_root() -> Path: |
| 112 | + def _find_dir_with_leaf(folder: Path, leaf: str) -> Path | None: |
| 113 | + root = folder.root |
| 114 | + while str(folder.absolute()) != root: |
| 115 | + if (folder / leaf).exists(): |
| 116 | + return folder |
| 117 | + folder = folder.parent |
| 118 | + return None |
| 119 | + |
| 120 | + for leaf in ["pyproject.toml", "setup.py"]: |
| 121 | + root = _find_dir_with_leaf(Path(__file__), leaf) |
| 122 | + if root is not None: |
| 123 | + return root |
| 124 | + msg = "Cannot find project root" |
| 125 | + raise NotADirectoryError(msg) |
0 commit comments