From b6ca2929759fb301281c31c0547303a41fe16f6f Mon Sep 17 00:00:00 2001 From: romainx Date: Wed, 12 Feb 2020 20:30:25 +0100 Subject: [PATCH 1/6] Check outdated packages --- Makefile | 6 ++- pytest.ini | 4 +- requirements-dev.txt | 2 + test/test_outdated.py | 100 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 test/test_outdated.py diff --git a/Makefile b/Makefile index b6c89099..8f844bb2 100644 --- a/Makefile +++ b/Makefile @@ -49,6 +49,9 @@ build/%: ## build the latest image for a stack build-all: $(foreach I,$(ALL_IMAGES),arch_patch/$(I) build/$(I) ) ## build all stacks build-test-all: $(foreach I,$(ALL_IMAGES),arch_patch/$(I) build/$(I) test/$(I) ) ## build and test all stacks +check_outdated/%: ## Check the outdated conda packages in a stack and produce a report (experimental) + @TEST_IMAGE="$(OWNER)/$(notdir $@)" pytest test/test_outdated.py + dev/%: ARGS?= dev/%: DARGS?= dev/%: PORT?=8888 @@ -89,4 +92,5 @@ tx-en: ## rebuild en locale strings and push to master (req: GH_TOKEN) @git push -u origin-tx master test/%: ## run tests against a stack (only common tests or common tests + specific tests) - @if [ ! -d "$(notdir $@)/test" ]; then TEST_IMAGE="$(OWNER)/$(notdir $@)" pytest test; else TEST_IMAGE="$(OWNER)/$(notdir $@)" pytest test $(notdir $@)/test; fi + @if [ ! -d "$(notdir $@)/test" ]; then TEST_IMAGE="$(OWNER)/$(notdir $@)" pytest -m "not info" test; \ + else TEST_IMAGE="$(OWNER)/$(notdir $@)" pytest -m "not info" test $(notdir $@)/test; fi diff --git a/pytest.ini b/pytest.ini index f861f05e..bf9c450c 100644 --- a/pytest.ini +++ b/pytest.ini @@ -2,4 +2,6 @@ log_cli = 1 log_cli_level = INFO log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s) -log_cli_date_format=%Y-%m-%d %H:%M:%S \ No newline at end of file +log_cli_date_format=%Y-%m-%d %H:%M:%S +markers = + info: marks tests as info (deselect with '-m "not info"') \ No newline at end of file diff --git a/requirements-dev.txt b/requirements-dev.txt index 9a268afc..e51280fb 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,4 +4,6 @@ recommonmark==0.5.0 requests sphinx>=1.6 sphinx-intl +tabulate transifex-client + diff --git a/test/test_outdated.py b/test/test_outdated.py new file mode 100644 index 00000000..d1cb0943 --- /dev/null +++ b/test/test_outdated.py @@ -0,0 +1,100 @@ +""" +Based on the work https://oerpli.github.io/post/2019/06/conda-outdated/. +See copyright below. + +MIT License +Copyright (c) 2019 Abraham Hinteregger +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +import re +import subprocess +from collections import defaultdict +from itertools import chain +import logging + +import pytest + +from tabulate import tabulate + +LOGGER = logging.getLogger(__name__) + + +def get_versions(lines): + """Extract versions from the lines""" + ddict = defaultdict(set) + for line in lines.splitlines()[2:]: + pkg, version = re.match(r"^(\S+)\s+(\S+)", line, re.MULTILINE).groups() + ddict[pkg].add(version) + return ddict + + +def semantic_cmp(version_string): + """Manage semantic versioning for comparison""" + + def mysplit(string): + version_substrs = lambda x: re.findall(r"([A-z]+|\d+)", x) + return list(chain(map(version_substrs, string.split(".")))) + + def str_ord(string): + num = 0 + for char in string: + num *= 255 + num += ord(char) + return num + + def try_int(version_str): + try: + return int(version_str) + except ValueError: + return str_ord(version_str) + + mss = list(chain(*mysplit(version_string))) + return tuple(map(try_int, mss)) + + +def print_result(installed, result): + """Print the result of the outdated check""" + nb_packages = len(installed) + nb_updatable = len(result) + updatable_ratio = nb_updatable / nb_packages + LOGGER.info( + f"{nb_updatable} packages can be updated over {nb_packages} -> {updatable_ratio:.0%}" + ) + LOGGER.info(f"\n{tabulate(result, headers='keys')}\n") + + +@pytest.mark.info +def test_outdated_packages(container): + """Getting the list of outdated packages""" + LOGGER.info(f"Checking outdated packages in {container.image_name} ...") + c = container.run(tty=True, command=["start.sh", "bash", "-c", "sleep infinity"]) + sp_i = c.exec_run(["conda", "list"]) + sp_v = c.exec_run(["conda", "search", "--outdated"]) + installed = get_versions(sp_i.output.decode("utf-8")) + available = get_versions(sp_v.output.decode("utf-8")) + result = list() + for pkg, inst_vs in installed.items(): + avail_vs = sorted(list(available[pkg]), key=semantic_cmp) + if not avail_vs: + continue + current = min(inst_vs, key=semantic_cmp) + newest = avail_vs[-1] + if avail_vs and current != newest: + if semantic_cmp(current) < semantic_cmp(newest): + result.append({"Package": pkg, "Current": current, "Newest": newest}) + print_result(installed, result) From bf91753dc6142a0de6fbc7c1b9bd5957a7e0fe1c Mon Sep 17 00:00:00 2001 From: romainx Date: Thu, 13 Feb 2020 10:20:42 +0100 Subject: [PATCH 2/6] minor changes on outdated package helper --- Makefile | 2 +- test/test_outdated.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 8f844bb2..55f4cd1b 100644 --- a/Makefile +++ b/Makefile @@ -49,7 +49,7 @@ build/%: ## build the latest image for a stack build-all: $(foreach I,$(ALL_IMAGES),arch_patch/$(I) build/$(I) ) ## build all stacks build-test-all: $(foreach I,$(ALL_IMAGES),arch_patch/$(I) build/$(I) test/$(I) ) ## build and test all stacks -check_outdated/%: ## Check the outdated conda packages in a stack and produce a report (experimental) +check-outdated/%: ## check the outdated conda packages in a stack and produce a report (experimental) @TEST_IMAGE="$(OWNER)/$(notdir $@)" pytest test/test_outdated.py dev/%: ARGS?= diff --git a/test/test_outdated.py b/test/test_outdated.py index d1cb0943..46d9bf2f 100644 --- a/test/test_outdated.py +++ b/test/test_outdated.py @@ -73,7 +73,7 @@ def print_result(installed, result): nb_updatable = len(result) updatable_ratio = nb_updatable / nb_packages LOGGER.info( - f"{nb_updatable} packages can be updated over {nb_packages} -> {updatable_ratio:.0%}" + f"{nb_updatable}/{nb_packages} ({updatable_ratio:.0%}) packages could be updated" ) LOGGER.info(f"\n{tabulate(result, headers='keys')}\n") From 083e2bbe33e47b42c0f4a6830354211ff2079375 Mon Sep 17 00:00:00 2001 From: romainx Date: Thu, 27 Feb 2020 22:38:18 +0100 Subject: [PATCH 3/6] filter dependencies from outdated packages --- test/test_outdated.py | 52 +++++++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 12 deletions(-) diff --git a/test/test_outdated.py b/test/test_outdated.py index 46d9bf2f..4e74f701 100644 --- a/test/test_outdated.py +++ b/test/test_outdated.py @@ -26,6 +26,7 @@ import subprocess from collections import defaultdict from itertools import chain import logging +import ast import pytest @@ -67,9 +68,12 @@ def semantic_cmp(version_string): return tuple(map(try_int, mss)) -def print_result(installed, result): +def print_result(installed, specs, result): """Print the result of the outdated check""" - nb_packages = len(installed) + if specs is None: + nb_packages = len(installed) + else: + nb_packages = len(specs) nb_updatable = len(result) updatable_ratio = nb_updatable / nb_packages LOGGER.info( @@ -79,22 +83,46 @@ def print_result(installed, result): @pytest.mark.info -def test_outdated_packages(container): +def test_outdated_packages(container, remove_dependencies=True): """Getting the list of outdated packages""" LOGGER.info(f"Checking outdated packages in {container.image_name} ...") c = container.run(tty=True, command=["start.sh", "bash", "-c", "sleep infinity"]) sp_i = c.exec_run(["conda", "list"]) sp_v = c.exec_run(["conda", "search", "--outdated"]) + specs = None + if remove_dependencies: + raw_specs = c.exec_run( + ["grep", "^# update specs:", "/opt/conda/conda-meta/history"] + ) + + specs = parse_specs(raw_specs.output.decode("utf-8")) installed = get_versions(sp_i.output.decode("utf-8")) available = get_versions(sp_v.output.decode("utf-8")) result = list() for pkg, inst_vs in installed.items(): - avail_vs = sorted(list(available[pkg]), key=semantic_cmp) - if not avail_vs: - continue - current = min(inst_vs, key=semantic_cmp) - newest = avail_vs[-1] - if avail_vs and current != newest: - if semantic_cmp(current) < semantic_cmp(newest): - result.append({"Package": pkg, "Current": current, "Newest": newest}) - print_result(installed, result) + if not remove_dependencies or pkg in specs: + avail_vs = sorted(list(available[pkg]), key=semantic_cmp) + if not avail_vs: + continue + current = min(inst_vs, key=semantic_cmp) + newest = avail_vs[-1] + if avail_vs and current != newest: + if semantic_cmp(current) < semantic_cmp(newest): + result.append( + {"Package": pkg, "Current": current, "Newest": newest} + ) + print_result(installed, specs, result) + + +def parse_specs(raw_specs): + """Return the list of requested packages (specs) + + Versions are removed from packages. + """ + packages = list() + for spec in (spec for spec in raw_specs.split("\n") if spec.strip() != ""): + packages += map( + lambda x: x.split("=", 1)[0], ast.literal_eval(spec.split(": ")[1]) + ) + LOGGER.debug(f"List of specs from conda env: {packages}") + return packages From bdfd8da0b00c1cd6f92d3dcc1cade28753bd68cd Mon Sep 17 00:00:00 2001 From: romainx Date: Sat, 29 Feb 2020 08:20:54 +0100 Subject: [PATCH 4/6] Added a note in the documentation --- docs/contributing/packages.md | 17 +++++++++++++++++ pytest.ini | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/contributing/packages.md b/docs/contributing/packages.md index ef9e8b55..de491495 100644 --- a/docs/contributing/packages.md +++ b/docs/contributing/packages.md @@ -13,3 +13,20 @@ make build/somestack-notebook 4. [Submit a pull request](https://github.com/PointCloudLibrary/pcl/wiki/A-step-by-step-guide-on-preparing-and-submitting-a-pull-request) (PR) with your changes. 5. Watch for Travis to report a build success or failure for your PR on GitHub. 6. Discuss changes with the maintainers and address any build issues. Version conflicts are the most common problem. You may need to upgrade additional packages to fix build failures. + +## Notes + +In order to help identifying packages that can be updated you can use the following helper tool. +It will list all the packages installed in the `Dockerfile` that can be updated -- dependencies are filtered to focus only on requested packages. + +```bash +$ make check-outdated/base-notebook + +# INFO test_outdated:test_outdated.py:80 3/8 (38%) packages could be updated +# INFO test_outdated:test_outdated.py:82 +# Package Current Newest +# ---------- --------- -------- +# conda 4.7.12 4.8.2 +# jupyterlab 1.2.5 2.0.0 +# python 3.7.4 3.8.2 +``` diff --git a/pytest.ini b/pytest.ini index 65f4b5fe..106434fb 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,5 +1,5 @@ [pytest] -addopts = -rA +addopts = -ra log_cli = 1 log_cli_level = INFO log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s) From b46fa3f9e6fcb3a8d1c0c76447db30f946790a15 Mon Sep 17 00:00:00 2001 From: romainx Date: Sun, 1 Mar 2020 08:19:28 +0100 Subject: [PATCH 5/6] Refactoring into CondaPackageHelper for reuse --- test/helpers.py | 179 ++++++++++++++++++++++++++++++++++++++++++ test/test_outdated.py | 126 +++-------------------------- 2 files changed, 188 insertions(+), 117 deletions(-) create mode 100644 test/helpers.py diff --git a/test/helpers.py b/test/helpers.py new file mode 100644 index 00000000..d7a9a657 --- /dev/null +++ b/test/helpers.py @@ -0,0 +1,179 @@ +# Copyright (c) Jupyter Development Team. +# Distributed under the terms of the Modified BSD License. + +# CondaPackageHelper is partially based on the work https://oerpli.github.io/post/2019/06/conda-outdated/. +# See copyright below. +# +# MIT License +# Copyright (c) 2019 Abraham Hinteregger +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import re +from collections import defaultdict +from itertools import chain +import logging +import ast + +from tabulate import tabulate + +LOGGER = logging.getLogger(__name__) + + +class CondaPackageHelper: + """Conda package helper permitting to get information about packages + """ + + def __init__(self, container): + # if isinstance(container, TrackedContainer): + self.running_container = CondaPackageHelper.start_container(container) + self.specs = None + self.installed = None + self.available = None + self.comparison = None + + @staticmethod + def start_container(container): + """Start the TrackedContainer and return an instance of a running container""" + LOGGER.info(f"Starting container {container.image_name} ...") + return container.run( + tty=True, command=["start.sh", "bash", "-c", "sleep infinity"] + ) + + def installed_packages(self): + """Return the installed packages""" + if self.installed is None: + LOGGER.info(f"Grabing the list of installed packages ...") + self.installed = self._packages(["conda", "list"]) + return self.installed + + def available_packages(self): + """Return the available packages""" + if self.available is None: + LOGGER.info( + f"Grabing the list of available packages (can take a while) ..." + ) + self.available = self._packages(["conda", "search", "--outdated"]) + return self.available + + def specified_packages(self): + """Return the specifications (i.e. packages installation requested)""" + if self.specs is None: + LOGGER.info(f"Grabing the list of specifications ...") + self.specs = self._specifications( + ["grep", "^# update specs:", "/opt/conda/conda-meta/history"] + ) + return self.specs + + def check_updatable_packages(self, specifications_only=True): + """Check the updatables packages including or not dependencies""" + specs = self.specified_packages() + installed = self.installed_packages() + available = self.available_packages() + self.comparison = list() + for pkg, inst_vs in self.installed.items(): + if not specifications_only or pkg in specs: + avail_vs = sorted( + list(available[pkg]), key=CondaPackageHelper.semantic_cmp + ) + if not avail_vs: + continue + current = min(inst_vs, key=CondaPackageHelper.semantic_cmp) + newest = avail_vs[-1] + if avail_vs and current != newest: + if CondaPackageHelper.semantic_cmp( + current + ) < CondaPackageHelper.semantic_cmp(newest): + self.comparison.append( + {"Package": pkg, "Current": current, "Newest": newest} + ) + return self.comparison + + def get_outdated_summary(self, specifications_only=True): + """Return a summary of outdated packages""" + if specifications_only: + nb_packages = len(self.specs) + else: + nb_packages = len(self.installed) + nb_updatable = len(self.comparison) + updatable_ratio = nb_updatable / nb_packages + return f"{nb_updatable}/{nb_packages} ({updatable_ratio:.0%}) packages could be updated" + + def get_outdated_table(self): + """Return a table of outdated packages""" + return tabulate(self.comparison, headers="keys") + + def _execute_command(self, command): + """Execute a command on a running container""" + rc = self.running_container.exec_run(command) + return rc.output.decode("utf-8") + + def _specifications(self, command): + """Return the list of specifications from a command""" + specifications = CondaPackageHelper._extract_specifications( + self._execute_command(command) + ) + LOGGER.debug(f"List of specifications and versions {specifications}") + return specifications + + def _packages(self, command): + """Return the list of packages from a command""" + packages = CondaPackageHelper._extract_packages(self._execute_command(command)) + LOGGER.debug(f"List of packages and versions {packages}") + return packages + + @staticmethod + def _extract_packages(lines): + """Extract packages and versions from the lines returned by the list of packages""" + ddict = defaultdict(set) + for line in lines.splitlines()[2:]: + pkg, version = re.match(r"^(\S+)\s+(\S+)", line, re.MULTILINE).groups() + ddict[pkg].add(version) + return ddict + + @staticmethod + def _extract_specifications(lines): + """Extract packages and versions from the lines returned by the list of specifications""" + packages_list = list() + for spec in (spec for spec in lines.split("\n") if spec.strip() != ""): + spec_list = ast.literal_eval(spec.split(": ")[1]) + packages_list += map(lambda x: x.split("=", 1), spec_list) + # TODO: could be improved + return {package[0]: set(package[1:]) for package in packages_list} + + @staticmethod + def semantic_cmp(version_string): + """Manage semantic versioning for comparison""" + + def mysplit(string): + version_substrs = lambda x: re.findall(r"([A-z]+|\d+)", x) + return list(chain(map(version_substrs, string.split(".")))) + + def str_ord(string): + num = 0 + for char in string: + num *= 255 + num += ord(char) + return num + + def try_int(version_str): + try: + return int(version_str) + except ValueError: + return str_ord(version_str) + + mss = list(chain(*mysplit(version_string))) + return tuple(map(try_int, mss)) diff --git a/test/test_outdated.py b/test/test_outdated.py index 4e74f701..91c91561 100644 --- a/test/test_outdated.py +++ b/test/test_outdated.py @@ -1,128 +1,20 @@ -""" -Based on the work https://oerpli.github.io/post/2019/06/conda-outdated/. -See copyright below. +# Copyright (c) Jupyter Development Team. +# Distributed under the terms of the Modified BSD License. -MIT License -Copyright (c) 2019 Abraham Hinteregger -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -""" - -import re -import subprocess -from collections import defaultdict -from itertools import chain import logging -import ast import pytest -from tabulate import tabulate +from helpers import CondaPackageHelper LOGGER = logging.getLogger(__name__) -def get_versions(lines): - """Extract versions from the lines""" - ddict = defaultdict(set) - for line in lines.splitlines()[2:]: - pkg, version = re.match(r"^(\S+)\s+(\S+)", line, re.MULTILINE).groups() - ddict[pkg].add(version) - return ddict - - -def semantic_cmp(version_string): - """Manage semantic versioning for comparison""" - - def mysplit(string): - version_substrs = lambda x: re.findall(r"([A-z]+|\d+)", x) - return list(chain(map(version_substrs, string.split(".")))) - - def str_ord(string): - num = 0 - for char in string: - num *= 255 - num += ord(char) - return num - - def try_int(version_str): - try: - return int(version_str) - except ValueError: - return str_ord(version_str) - - mss = list(chain(*mysplit(version_string))) - return tuple(map(try_int, mss)) - - -def print_result(installed, specs, result): - """Print the result of the outdated check""" - if specs is None: - nb_packages = len(installed) - else: - nb_packages = len(specs) - nb_updatable = len(result) - updatable_ratio = nb_updatable / nb_packages - LOGGER.info( - f"{nb_updatable}/{nb_packages} ({updatable_ratio:.0%}) packages could be updated" - ) - LOGGER.info(f"\n{tabulate(result, headers='keys')}\n") - - @pytest.mark.info -def test_outdated_packages(container, remove_dependencies=True): - """Getting the list of outdated packages""" +def test_outdated_packages(container, specifications_only=True): + """Getting the list of updatable packages""" LOGGER.info(f"Checking outdated packages in {container.image_name} ...") - c = container.run(tty=True, command=["start.sh", "bash", "-c", "sleep infinity"]) - sp_i = c.exec_run(["conda", "list"]) - sp_v = c.exec_run(["conda", "search", "--outdated"]) - specs = None - if remove_dependencies: - raw_specs = c.exec_run( - ["grep", "^# update specs:", "/opt/conda/conda-meta/history"] - ) - - specs = parse_specs(raw_specs.output.decode("utf-8")) - installed = get_versions(sp_i.output.decode("utf-8")) - available = get_versions(sp_v.output.decode("utf-8")) - result = list() - for pkg, inst_vs in installed.items(): - if not remove_dependencies or pkg in specs: - avail_vs = sorted(list(available[pkg]), key=semantic_cmp) - if not avail_vs: - continue - current = min(inst_vs, key=semantic_cmp) - newest = avail_vs[-1] - if avail_vs and current != newest: - if semantic_cmp(current) < semantic_cmp(newest): - result.append( - {"Package": pkg, "Current": current, "Newest": newest} - ) - print_result(installed, specs, result) - - -def parse_specs(raw_specs): - """Return the list of requested packages (specs) - - Versions are removed from packages. - """ - packages = list() - for spec in (spec for spec in raw_specs.split("\n") if spec.strip() != ""): - packages += map( - lambda x: x.split("=", 1)[0], ast.literal_eval(spec.split(": ")[1]) - ) - LOGGER.debug(f"List of specs from conda env: {packages}") - return packages + pkg_helper = CondaPackageHelper(container) + pkg_helper.check_updatable_packages(specifications_only) + LOGGER.info(pkg_helper.get_outdated_summary(specifications_only)) + LOGGER.info(f"\n{pkg_helper.get_outdated_table()}\n") From 416dc99d030e32fc00f00cd9e7685e65de8df24c Mon Sep 17 00:00:00 2001 From: romainx Date: Tue, 3 Mar 2020 21:11:33 +0100 Subject: [PATCH 6/6] Usage of conda env export --- test/helpers.py | 123 +++++++++++++++++++++++------------------------- 1 file changed, 60 insertions(+), 63 deletions(-) diff --git a/test/helpers.py b/test/helpers.py index d7a9a657..fc4ce852 100644 --- a/test/helpers.py +++ b/test/helpers.py @@ -26,7 +26,7 @@ import re from collections import defaultdict from itertools import chain import logging -import ast +import json from tabulate import tabulate @@ -53,30 +53,65 @@ class CondaPackageHelper: tty=True, command=["start.sh", "bash", "-c", "sleep infinity"] ) + @staticmethod + def _conda_export_command(from_history=False): + """Return the conda export command with or without history""" + cmd = ["conda", "env", "export", "-n", "base", "--json", "--no-builds"] + if from_history: + cmd.append("--from-history") + return cmd + def installed_packages(self): """Return the installed packages""" if self.installed is None: LOGGER.info(f"Grabing the list of installed packages ...") - self.installed = self._packages(["conda", "list"]) + self.installed = CondaPackageHelper._packages_from_json( + self._execute_command(CondaPackageHelper._conda_export_command()) + ) return self.installed + def specified_packages(self): + """Return the specifications (i.e. packages installation requested)""" + if self.specs is None: + LOGGER.info(f"Grabing the list of specifications ...") + self.specs = CondaPackageHelper._packages_from_json( + self._execute_command(CondaPackageHelper._conda_export_command(True)) + ) + return self.specs + + def _execute_command(self, command): + """Execute a command on a running container""" + rc = self.running_container.exec_run(command) + return rc.output.decode("utf-8") + + @staticmethod + def _packages_from_json(env_export): + """Extract packages and versions from the lines returned by the list of specifications""" + dependencies = json.loads(env_export).get("dependencies") + packages_list = map(lambda x: x.split("=", 1), dependencies) + # TODO: could be improved + return {package[0]: set(package[1:]) for package in packages_list} + def available_packages(self): """Return the available packages""" if self.available is None: LOGGER.info( f"Grabing the list of available packages (can take a while) ..." ) - self.available = self._packages(["conda", "search", "--outdated"]) + # Keeping command line output since `conda search --outdated --json` is way too long ... + self.available = CondaPackageHelper._extract_available( + self._execute_command(["conda", "search", "--outdated"]) + ) return self.available - def specified_packages(self): - """Return the specifications (i.e. packages installation requested)""" - if self.specs is None: - LOGGER.info(f"Grabing the list of specifications ...") - self.specs = self._specifications( - ["grep", "^# update specs:", "/opt/conda/conda-meta/history"] - ) - return self.specs + @staticmethod + def _extract_available(lines): + """Extract packages and versions from the lines returned by the list of packages""" + ddict = defaultdict(set) + for line in lines.splitlines()[2:]: + pkg, version = re.match(r"^(\S+)\s+(\S+)", line, re.MULTILINE).groups() + ddict[pkg].add(version) + return ddict def check_updatable_packages(self, specifications_only=True): """Check the updatables packages including or not dependencies""" @@ -102,58 +137,6 @@ class CondaPackageHelper: ) return self.comparison - def get_outdated_summary(self, specifications_only=True): - """Return a summary of outdated packages""" - if specifications_only: - nb_packages = len(self.specs) - else: - nb_packages = len(self.installed) - nb_updatable = len(self.comparison) - updatable_ratio = nb_updatable / nb_packages - return f"{nb_updatable}/{nb_packages} ({updatable_ratio:.0%}) packages could be updated" - - def get_outdated_table(self): - """Return a table of outdated packages""" - return tabulate(self.comparison, headers="keys") - - def _execute_command(self, command): - """Execute a command on a running container""" - rc = self.running_container.exec_run(command) - return rc.output.decode("utf-8") - - def _specifications(self, command): - """Return the list of specifications from a command""" - specifications = CondaPackageHelper._extract_specifications( - self._execute_command(command) - ) - LOGGER.debug(f"List of specifications and versions {specifications}") - return specifications - - def _packages(self, command): - """Return the list of packages from a command""" - packages = CondaPackageHelper._extract_packages(self._execute_command(command)) - LOGGER.debug(f"List of packages and versions {packages}") - return packages - - @staticmethod - def _extract_packages(lines): - """Extract packages and versions from the lines returned by the list of packages""" - ddict = defaultdict(set) - for line in lines.splitlines()[2:]: - pkg, version = re.match(r"^(\S+)\s+(\S+)", line, re.MULTILINE).groups() - ddict[pkg].add(version) - return ddict - - @staticmethod - def _extract_specifications(lines): - """Extract packages and versions from the lines returned by the list of specifications""" - packages_list = list() - for spec in (spec for spec in lines.split("\n") if spec.strip() != ""): - spec_list = ast.literal_eval(spec.split(": ")[1]) - packages_list += map(lambda x: x.split("=", 1), spec_list) - # TODO: could be improved - return {package[0]: set(package[1:]) for package in packages_list} - @staticmethod def semantic_cmp(version_string): """Manage semantic versioning for comparison""" @@ -177,3 +160,17 @@ class CondaPackageHelper: mss = list(chain(*mysplit(version_string))) return tuple(map(try_int, mss)) + + def get_outdated_summary(self, specifications_only=True): + """Return a summary of outdated packages""" + if specifications_only: + nb_packages = len(self.specs) + else: + nb_packages = len(self.installed) + nb_updatable = len(self.comparison) + updatable_ratio = nb_updatable / nb_packages + return f"{nb_updatable}/{nb_packages} ({updatable_ratio:.0%}) packages could be updated" + + def get_outdated_table(self): + """Return a table of outdated packages""" + return tabulate(self.comparison, headers="keys")