Fix invalid version error with _get_version()-provided version (#5670)

* Make sure that the repository we check is in the location we expect

* Merge `redbot._version` into `redbot`

* Generate VersionInfo in _get_version()

This way, if VersionInfo.from_str() generates exception due to invalid
version, we catch it.
This commit is contained in:
jack1142 2022-04-06 00:48:03 +02:00 committed by GitHub
parent 88d2cb3976
commit bc9f34c04b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 56 additions and 51 deletions

View File

@ -4,11 +4,10 @@ import sys
from typing import Match from typing import Match
import redbot import redbot
from redbot._version import __version__
if int(os.environ.get("JUST_RETURN_VERSION", 0)): if int(os.environ.get("JUST_RETURN_VERSION", 0)):
print(f"::set-output name=version::{__version__}") print(f"::set-output name=version::{redbot._VERSION}")
sys.exit(0) sys.exit(0)
@ -31,12 +30,12 @@ def repl(match: Match[str]) -> str:
version_info.micro += 1 version_info.micro += 1
version_info.dev_release = 1 version_info.dev_release = 1
return f'__version__ = "{version_info}"' return f'_VERSION = "{version_info}"'
with open("redbot/_version.py", encoding="utf-8") as fp: with open("redbot/__init__.py", encoding="utf-8") as fp:
new_contents, found = re.subn( new_contents, found = re.subn(
pattern=r'^__version__ = "(?P<version>[^"]*)"$', pattern=r'^_VERSION = "(?P<version>[^"]*)"$',
repl=repl, repl=repl,
string=fp.read(), string=fp.read(),
count=1, count=1,
@ -44,10 +43,10 @@ with open("redbot/_version.py", encoding="utf-8") as fp:
) )
if not found: if not found:
print("Couldn't find `__version__` line!") print("Couldn't find `_VERSION` line!")
sys.exit(1) sys.exit(1)
with open("redbot/_version.py", "w", encoding="utf-8", newline="\n") as fp: with open("redbot/__init__.py", "w", encoding="utf-8", newline="\n") as fp:
fp.write(new_contents) fp.write(new_contents)
print(f"::set-output name=new_version::{version_info}") print(f"::set-output name=new_version::{version_info}")

View File

@ -12,8 +12,6 @@ from typing import (
Union as _Union, Union as _Union,
) )
from redbot._version import _get_version
MIN_PYTHON_VERSION = (3, 8, 1) MIN_PYTHON_VERSION = (3, 8, 1)
@ -199,6 +197,50 @@ class VersionInfo:
"dev={dev_release}, local={local_version})" "dev={dev_release}, local={local_version})"
).format(**self.to_json()) ).format(**self.to_json())
@classmethod
def _get_version(cls, *, ignore_installed: bool = False) -> _Tuple[str, "VersionInfo"]:
if not _VERSION.endswith(".dev1"):
return _VERSION, cls.from_str(_VERSION)
try:
import os
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
# we only want to do this for editable installs
if not os.path.exists(os.path.join(path, ".git")):
raise RuntimeError("not a git repository")
import subprocess
output = subprocess.check_output(
("git", "describe", "--tags", "--long", "--dirty"),
stderr=subprocess.DEVNULL,
cwd=path,
)
_, count, commit, *dirty = output.decode("utf-8").strip().split("-", 3)
dirty_suffix = f".{dirty[0]}" if dirty else ""
ver = f"{_VERSION[:-1]}{count}+{commit}{dirty_suffix}"
return ver, cls.from_str(ver)
except Exception:
# `ignore_installed` is `True` when building with setuptools.
if ignore_installed:
# we don't want any failure to raise here but we should print it
import traceback
traceback.print_exc()
else:
try:
from importlib.metadata import version
ver = version("Red-DiscordBot")
return ver, cls.from_str(ver)
except Exception:
# we don't want any failure to raise here but we should print it
import traceback
traceback.print_exc()
return _VERSION, cls.from_str(_VERSION)
def _update_event_loop_policy(): def _update_event_loop_policy():
if _sys.implementation.name == "cpython": if _sys.implementation.name == "cpython":
@ -245,8 +287,10 @@ def _early_init():
_ensure_no_colorama() _ensure_no_colorama()
__version__ = _get_version() # This is bumped automatically by release workflow (`.github/workflows/scripts/bump_version.py`)
version_info = VersionInfo.from_str(__version__) _VERSION = "3.5.0.dev1"
__version__, version_info = VersionInfo._get_version()
# Filter fuzzywuzzy slow sequence matcher warning # Filter fuzzywuzzy slow sequence matcher warning
_warnings.filterwarnings("ignore", module=r"fuzzywuzzy.*") _warnings.filterwarnings("ignore", module=r"fuzzywuzzy.*")

View File

@ -1,38 +0,0 @@
def _get_version(*, ignore_installed: bool = False) -> str:
if not __version__.endswith(".dev1"):
return __version__
try:
import os
import subprocess
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
output = subprocess.check_output(
("git", "describe", "--tags", "--long", "--dirty"),
stderr=subprocess.DEVNULL,
cwd=path,
)
_, count, commit, *dirty = output.decode("utf-8").strip().split("-", 3)
dirty_suffix = f".{dirty[0]}" if dirty else ""
return f"{__version__[:-1]}{count}+{commit}{dirty_suffix}"
except Exception:
# `ignore_installed` is `True` when building with setuptools.
if ignore_installed:
# we don't want any failure to raise here but we should print it
import traceback
traceback.print_exc()
else:
try:
from importlib.metadata import version
return version("Red-DiscordBot")
except Exception:
# we don't want any failure to raise here but we should print it
import traceback
traceback.print_exc()
return __version__
__version__ = "3.5.0.dev1"

View File

@ -5,9 +5,9 @@ from setuptools import setup
# Since we're importing `redbot` package, we have to ensure that it's in sys.path. # Since we're importing `redbot` package, we have to ensure that it's in sys.path.
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from redbot._version import _get_version from redbot import VersionInfo
version = _get_version(ignore_installed=True) version, _ = VersionInfo._get_version(ignore_installed=True)
if os.getenv("TOX_RED", False) and sys.version_info >= (3, 10): if os.getenv("TOX_RED", False) and sys.version_info >= (3, 10):
# We want to be able to test Python versions that we do not support yet. # We want to be able to test Python versions that we do not support yet.