From 94ab109ca9f736cde020416f2c2e732b00748f00 Mon Sep 17 00:00:00 2001 From: Andrey Khrolenok Date: Sun, 13 Sep 2020 03:48:34 +0300 Subject: [PATCH 1/3] Add semantic realese workflow --- .github/workflows/semantic_release.yml | 53 +++++++++++++ .pre-commit-config.yaml | 8 -- README.md | 43 ++++------- script/dev-deploy | 2 +- script/update_tracker.py | 102 ------------------------- script/version_bump.py | 87 ++++++++++++++------- setup.cfg | 5 ++ tracker.json | 16 ---- 8 files changed, 133 insertions(+), 183 deletions(-) create mode 100644 .github/workflows/semantic_release.yml delete mode 100755 script/update_tracker.py delete mode 100644 tracker.json diff --git a/.github/workflows/semantic_release.yml b/.github/workflows/semantic_release.yml new file mode 100644 index 0000000..75f1c74 --- /dev/null +++ b/.github/workflows/semantic_release.yml @@ -0,0 +1,53 @@ +--- +name: semantic_release + +on: + push: + branches: + - master + +jobs: + deploy: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + with: + ref: master + - name: Set up Python 3.7 + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install python-semantic-release + - name: Setup Git + run: | + git config --global user.name "semantic-release" + git config --global user.email "semantic-release@GitHub" + - name: Publish with semantic-release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + DEBUG='*' semantic-release publish + # Pack the ha-gismeteo dir as a zip and upload to the release + - name: Zip gismeteo dir + run: | + cd /home/runner/work/ha-gismeteo/ha-gismeteo/custom_components/gismeteo + zip gismeteo.zip -r ./ + - name: Set release variable + run: | + echo "::set-env name=release_version::`git describe --abbrev=0`" + - name: Sleep + # add delay so upload does not kill the release notes from semantic-release + run: | + sleep 5 + - name: Upload zip to release + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: /home/runner/work/ha-gismeteo/ha-gismeteo/custom_components/gismeteo/gismeteo.zip + asset_name: gismeteo.zip + tag: ${{ env.release_version }} + overwrite: true diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f89b335..ce3fdde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,10 +30,6 @@ repos: - id: no-commit-to-branch args: - --branch=master - - repo: https://github.com/adrienverge/yamllint.git - rev: v1.23.0 - hooks: - - id: yamllint - repo: local hooks: # Run mypy through our wrapper script in order to get the possible @@ -47,10 +43,6 @@ repos: types: [python] require_serial: true files: ^custom_components/.+\.py$ - - id: update-tracker - name: "Update Tracker" - entry: script/update_tracker.py - language: system - id: pylint name: pylint entry: python3 -m pylint.__main__ diff --git a/README.md b/README.md index 215ab66..5ad8f62 100644 --- a/README.md +++ b/README.md @@ -65,12 +65,12 @@ I put a lot of work into making this repo and component available and updated to _(string) (Optional)_\ Name to use in the frontend.\ _Default value: Gismeteo_ - + **mode:**\ _(string) (Optional)_\ Can specify `hourly` or `daily`. Select `hourly` for a three-hour forecast, `daily` for daily forecast.\ _Default value: `hourly`_ - + **latitude:**\ _(float) (Optional)_\ Latitude of the location to display the weather.\ @@ -115,46 +115,46 @@ I put a lot of work into making this repo and component available and updated to _(string) (Optional)_\ Additional name for the sensors. Default to platform name.\ _Default value: Gismeteo_ - + **forecast:**\ _(boolean) (Optional)_\ Enables the forecast. The default is to display the current conditions.\ _Default value: false_ - + **monitored_conditions:**\ _(list) (Required)_\ Conditions to display in the frontend. - + > **weather**\ > A human-readable text summary. -> +> > **temperature**\ > The current temperature. -> +> > **wind_speed**\ > The wind speed. -> +> > **wind_bearing**\ > The wind bearing. -> +> > **humidity**\ > The relative humidity. -> +> > **pressure**\ > The sea-level air pressure in millibars. -> +> > **clouds**\ > Description about cloud coverage. -> +> > **rain**\ > The rain volume. -> +> > **snow**\ > The snow volume. -> +> > **storm**\ > The storm prediction. -> +> > **geomagnetic**\ > The geomagnetic field value:\ > 1 = No noticeable geomagnetic disturbance\ @@ -168,18 +168,7 @@ I put a lot of work into making this repo and component available and updated to ## Track updates -You can automatically track new versions of this component and update it by [custom-updater](https://github.com/custom-components/custom_updater) (deprecated) or [HACS][hacs]. - -For custom-updater to initiate tracking add this lines to you `configuration.yaml` file: - -```yaml -# Example configuration.yaml entry -custom_updater: - track: - - components - component_urls: - - https://raw.githubusercontent.com/Limych/ha-gismeteo/master/tracker.json -``` +You can automatically track new versions of this component and update it by [HACS][hacs]. [forum-support]: https://community.home-assistant.io/t/gismeteo-weather-provider/109668 [hacs]: https://github.com/custom-components/hacs diff --git a/script/dev-deploy b/script/dev-deploy index 735ed0d..157f0b9 100755 --- a/script/dev-deploy +++ b/script/dev-deploy @@ -32,7 +32,7 @@ die() { -ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." >/dev/null 2>&1 && pwd )" +ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" HASSIO_CONFIG="${ROOT}/dev-config" diff --git a/script/update_tracker.py b/script/update_tracker.py deleted file mode 100755 index b5c141b..0000000 --- a/script/update_tracker.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env python3 -"""Tracker updater for custom_updater.""" - -# Copyright (c) 2019, Andrey "Limych" Khrolenok -# Creative Commons BY-NC-SA 4.0 International Public License -# (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) -import copy -import json -import logging -import os -import re - -# http://docs.python.org/2/howto/logging.html#library-config -# Avoids spurious error messages if no logger is configured by the user -import sys - -logging.getLogger(__name__).addHandler(logging.NullHandler()) - -# logging.basicConfig(level=logging.DEBUG) - -_LOGGER = logging.getLogger(__name__) - -ROOT = os.path.dirname(os.path.abspath(f"{__file__}/..")) -TRACKER_FPATH = ( - f"{ROOT}/custom_components.json" - if os.path.isfile(f"{ROOT}/custom_components.json") - else f"{ROOT}/tracker.json" -) - -sys.path.append(ROOT) - - -def fallback_version(localpath): - """Return version from regex match.""" - return_value = "" - if os.path.isfile(localpath): - with open(localpath) as local: - ret = re.compile(r"^\b(VERSION|__version__)\s*=\s*['\"](.*)['\"]") - for line in local.readlines(): - matcher = ret.match(line) - if matcher: - return_value = str(matcher.group(2)) - return return_value - - -def get_component_version(localpath, package): - """Return the local version if any.""" - if "." in package: - package = "{}.{}".format(package.split(".")[1], package.split(".")[0]) - package = f"custom_components.{package}" - _LOGGER.debug("Started for %s (%s)", localpath, package) - return_value = "" - if os.path.isfile(localpath): - _LOGGER.debug(package) - try: - name = "__version__" - return_value = getattr(__import__(package, fromlist=[name]), name) - except Exception as err: # pylint: disable=broad-except - _LOGGER.debug(str(err)) - if return_value == "": - try: - name = "VERSION" - return_value = getattr(__import__(package, fromlist=[name]), name) - except Exception as err: # pylint: disable=broad-except - _LOGGER.debug(str(err)) - if return_value == "": - return_value = fallback_version(localpath) - _LOGGER.debug(str(return_value)) - return return_value - - -def update_tracker(tracker_fpath): - """Run tracker file update.""" - with open(tracker_fpath) as tracker_file: - tracker = json.load(tracker_file) - old_tr = copy.deepcopy(tracker) - for package in tracker: - _LOGGER.info("Updating version for %s", package) - local_path = "{}/{}".format( - ROOT, tracker[package]["local_location"].lstrip("/\\") - ) - tracker[package]["version"] = get_component_version(local_path, package) - base_path = os.path.split(local_path)[0] - base_url = os.path.split(tracker[package]["remote_location"])[0] - resources = [] - for current_path, _, files in os.walk(base_path): - if current_path.find("__pycache__") != -1: - continue - for file in files: - file = os.path.join(current_path, file).replace("\\", "/") - if file != local_path: - resources.append(base_url + file[len(base_path) :]) - resources.sort() - tracker[package]["resources"] = resources - - if tracker != old_tr: - with open(tracker_fpath, "w") as tracker_file: - json.dump(tracker, tracker_file, indent=4) - - -update_tracker(TRACKER_FPATH) -# subprocess.run(["git", "add", TRACKER_FPATH]) diff --git a/script/version_bump.py b/script/version_bump.py index 1f1c08b..fca1117 100755 --- a/script/version_bump.py +++ b/script/version_bump.py @@ -36,28 +36,28 @@ def fallback_version(localpath): return return_value -def get_component_version(localpath, package): +def get_package_version(localpath, package): """Return the local version if any.""" - if "." in package: - package = "{}.{}".format(package.split(".")[1], package.split(".")[0]) - package = f"custom_components.{package}" _LOGGER.debug("Started for %s (%s)", localpath, package) return_value = "" if os.path.isfile(localpath): try: name = "__version__" - return_value = getattr(__import__(package, fromlist=[name]), name) + return_value = getattr(__import__(f"..{package}", fromlist=[name]), name) except Exception as err: # pylint: disable=broad-except _LOGGER.debug(str(err)) if return_value == "": try: name = "VERSION" - return_value = getattr(__import__(package, fromlist=[name]), name) + return_value = getattr( + __import__(f"..{package}", fromlist=[name]), name + ) except Exception as err: # pylint: disable=broad-except _LOGGER.debug(str(err)) if return_value == "": return_value = fallback_version(localpath) _LOGGER.debug(str(return_value)) + assert return_value, "Version not found!" return return_value @@ -152,17 +152,27 @@ def bump_version(version, bump_type): return Version(str(temp)) -def write_version(component_path, version): +def write_version(package_path, version, dry_run=False): """Update custom component constant file with new version.""" - component_path += "/const.py" - with open(component_path) as fil: - content = fil.read() + for suffix in ("__init__", "const"): + file_path = f"{package_path}/{suffix}.py" + _LOGGER.debug("Try to change %s", file_path) - content = re.sub("VERSION = .*\n", f"VERSION = '{version}'\n", content) - content = re.sub("__version__ = .*\n", f"__version__ = '{version}'\n", content) + with open(file_path) as fil: + cur_content = content = fil.read() - with open(component_path, "wt") as fil: - fil.write(content) + content = re.sub(r"\nVERSION = .*\n", f"\nVERSION = '{version}'\n", content) + content = re.sub( + r"\n__version__ = .*\n", f"\n__version__ = '{version}'\n", content + ) + + if cur_content != content: + _LOGGER.debug("%s changed", file_path) + if dry_run: + print("%s could was changed." % os.path.basename(file_path)) + else: + with open(file_path, "wt") as fil: + fil.write(content) def main(): @@ -178,34 +188,53 @@ def main(): parser.add_argument( "--commit", action="store_true", help="Create a version bump commit." ) + parser.add_argument( + "package_dir", nargs="?", default=None, help="The path to package." + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Preview version bumping without running it.", + ) arguments = parser.parse_args() + if arguments.dry_run: + print("!!! Dry Run !!! No Files Was Changed") + # pylint: disable=subprocess-run-check if arguments.commit and subprocess.run(["git", "diff", "--quiet"]).returncode == 1: print("Cannot use --commit because git is dirty.") return - component = None - for current_path, dirs, _ in os.walk(f"{ROOT}/custom_components"): - if current_path.find("__pycache__") != -1: - continue - for dname in dirs: - if dname != "__pycache__": - component = dname - - assert component, "Component not found!" - component_path = f"{ROOT}/custom_components/{component}" - - current = Version(get_component_version(f"{component_path}/__init__.py", component)) + if arguments.package_dir is not None: + package_dir = os.path.abspath(arguments.package_dir) + package = package_dir.split("/")[-1] + else: + package = None + for current_path, dirs, _ in os.walk(f"{ROOT}/custom_components"): + if current_path.find("__pycache__") != -1: + continue + for dname in dirs: + if dname != "__pycache__": + package = dname + + assert package, "Component not found!" + package_dir = f"{ROOT}/custom_components/{package}" + package = f"custom_components.{package}" + + current = Version(get_package_version(f"{package_dir}/__init__.py", package)) bumped = bump_version(current, arguments.type) assert bumped > current, "BUG! New version is not newer than old version" - write_version(component_path, bumped) + if arguments.dry_run: + print(f"Current version: {current}\n" f" New version: {bumped}") + + write_version(package_dir, bumped, arguments.dry_run) - if not arguments.commit: + if not arguments.commit or arguments.dry_run: return - subprocess.run(["git", "commit", "-nam", f"Bumped version to {bumped}"]) + subprocess.run(["git", "commit", "-nam", f"Bump version to {bumped}"]) # pylint: disable=import-outside-toplevel diff --git a/setup.cfg b/setup.cfg index 9769c0e..9de6675 100644 --- a/setup.cfg +++ b/setup.cfg @@ -7,3 +7,8 @@ exclude = [mypy] ignore_missing_imports = True + +[semantic_release] +version_variable=custom_components/gismeteo/const.py:VERSION +upload_to_pypi=false +upload_to_release=false diff --git a/tracker.json b/tracker.json deleted file mode 100644 index 467bc98..0000000 --- a/tracker.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "gismeteo": { - "version": "2.0.14", - "local_location": "/custom_components/gismeteo/__init__.py", - "remote_location": "https://raw.githubusercontent.com/Limych/ha-gismeteo/master/custom_components/gismeteo/__init__.py", - "visit_repo": "https://github.com/Limych/ha-gismeteo", - "changelog": "https://github.com/Limych/ha-gismeteo/releases/latest", - "resources": [ - "https://raw.githubusercontent.com/Limych/ha-gismeteo/master/custom_components/gismeteo/cache.py", - "https://raw.githubusercontent.com/Limych/ha-gismeteo/master/custom_components/gismeteo/const.py", - "https://raw.githubusercontent.com/Limych/ha-gismeteo/master/custom_components/gismeteo/manifest.json", - "https://raw.githubusercontent.com/Limych/ha-gismeteo/master/custom_components/gismeteo/sensor.py", - "https://raw.githubusercontent.com/Limych/ha-gismeteo/master/custom_components/gismeteo/weather.py" - ] - } -} \ No newline at end of file From a9a7b79c4d30aacb3b91981bb6667c4458f658a4 Mon Sep 17 00:00:00 2001 From: Andrey Khrolenok Date: Sun, 13 Sep 2020 03:54:00 +0300 Subject: [PATCH 2/3] Move Base component constants to __init__.py --- custom_components/gismeteo/__init__.py | 10 +++++++--- custom_components/gismeteo/const.py | 6 ------ custom_components/gismeteo/sensor.py | 3 +-- custom_components/gismeteo/weather.py | 3 +-- setup.cfg | 2 +- 5 files changed, 10 insertions(+), 14 deletions(-) diff --git a/custom_components/gismeteo/__init__.py b/custom_components/gismeteo/__init__.py index 7cbab08..c9d678b 100644 --- a/custom_components/gismeteo/__init__.py +++ b/custom_components/gismeteo/__init__.py @@ -60,9 +60,6 @@ BASE_URL, MMHG2HPA, MS2KMH, - VERSION, - ISSUE_URL, - DOMAIN, ) try: @@ -74,6 +71,13 @@ _LOGGER = logging.getLogger(__name__) +# Base component constants +DOMAIN = "gismeteo" +VERSION = "2.0.14" +ISSUE_URL = "https://github.com/Limych/ha-gismeteo/issues" +ATTRIBUTION = "Data provided by Gismeteo" + + # pylint: disable=unused-argument def setup(hass, config): """Set up component.""" diff --git a/custom_components/gismeteo/const.py b/custom_components/gismeteo/const.py index 3cb3eb1..aa375e0 100644 --- a/custom_components/gismeteo/const.py +++ b/custom_components/gismeteo/const.py @@ -14,12 +14,6 @@ from homeassistant.components.weather import ATTR_FORECAST_CONDITION -# Base component constants -DOMAIN = "gismeteo" -VERSION = "2.0.14" -ISSUE_URL = "https://github.com/Limych/ha-gismeteo/issues" -ATTRIBUTION = "Data provided by Gismeteo" - BASE_URL = "https://services.gismeteo.ru/inform-service/inf_chrome" MMHG2HPA = 1.333223684 diff --git a/custom_components/gismeteo/sensor.py b/custom_components/gismeteo/sensor.py index 2737e65..35625f7 100644 --- a/custom_components/gismeteo/sensor.py +++ b/custom_components/gismeteo/sensor.py @@ -24,9 +24,8 @@ from homeassistant.helpers.entity import Entity from homeassistant.helpers.storage import STORAGE_DIR -from . import Gismeteo +from . import Gismeteo, ATTRIBUTION from .const import ( - ATTRIBUTION, DEFAULT_NAME, MIN_TIME_BETWEEN_UPDATES, CONF_CACHE_DIR, diff --git a/custom_components/gismeteo/weather.py b/custom_components/gismeteo/weather.py index dee187d..d46fe6a 100644 --- a/custom_components/gismeteo/weather.py +++ b/custom_components/gismeteo/weather.py @@ -24,9 +24,8 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers.storage import STORAGE_DIR -from . import Gismeteo +from . import Gismeteo, ATTRIBUTION from .const import ( - ATTRIBUTION, DEFAULT_NAME, MIN_TIME_BETWEEN_UPDATES, CONF_CACHE_DIR, diff --git a/setup.cfg b/setup.cfg index 9de6675..bbb0f34 100644 --- a/setup.cfg +++ b/setup.cfg @@ -9,6 +9,6 @@ exclude = ignore_missing_imports = True [semantic_release] -version_variable=custom_components/gismeteo/const.py:VERSION +version_variable=custom_components/gismeteo/__init__.py:VERSION upload_to_pypi=false upload_to_release=false From 4eedd6f7f825ea4282074604718a3fa8abe64ac8 Mon Sep 17 00:00:00 2001 From: Andrey Khrolenok Date: Sun, 13 Sep 2020 03:54:36 +0300 Subject: [PATCH 3/3] Bump version to 2.0.15 --- custom_components/gismeteo/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/gismeteo/__init__.py b/custom_components/gismeteo/__init__.py index c9d678b..7e0533d 100644 --- a/custom_components/gismeteo/__init__.py +++ b/custom_components/gismeteo/__init__.py @@ -73,7 +73,7 @@ # Base component constants DOMAIN = "gismeteo" -VERSION = "2.0.14" +VERSION = '2.0.15' ISSUE_URL = "https://github.com/Limych/ha-gismeteo/issues" ATTRIBUTION = "Data provided by Gismeteo"