Switch to tools.utils.gh.get_github_token

Signed-off-by: Pedro Algarvio <palgarvio@vmware.com>
This commit is contained in:
Pedro Algarvio 2023-10-28 09:38:42 +01:00 committed by Pedro Algarvio
parent 68bca1ee8d
commit 0d5a6bf7f7
3 changed files with 24 additions and 9 deletions

View file

@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Any
from ptscripts import Context, command_group
import tools.utils
import tools.utils.gh
if sys.version_info < (3, 11):
from typing_extensions import NotRequired, TypedDict
@ -914,8 +915,9 @@ def _get_pr_test_labels_from_api(
headers = {
"Accept": "application/vnd.github+json",
}
if "GITHUB_TOKEN" in os.environ:
headers["Authorization"] = f"Bearer {os.environ['GITHUB_TOKEN']}"
github_token = tools.utils.gh.get_github_token(ctx)
if github_token is not None:
headers["Authorization"] = f"Bearer {github_token}"
web.headers.update(headers)
ret = web.get(f"https://api.github.com/repos/{repository}/pulls/{pr}")
if ret.status_code != 200:

View file

@ -134,13 +134,17 @@ def get_salt_releases(ctx: Context, repository: str) -> list[Version]:
"""
Return a list of salt versions
"""
# Deferred import
import tools.utils.gh
versions = set()
with ctx.web as web:
headers = {
"Accept": "application/vnd.github+json",
}
if "GITHUB_TOKEN" in os.environ:
headers["Authorization"] = f"Bearer {os.environ['GITHUB_TOKEN']}"
github_token = tools.utils.gh.get_github_token(ctx)
if github_token is not None:
headers["Authorization"] = f"Bearer {github_token}"
web.headers.update(headers)
ret = web.get(f"https://api.github.com/repos/{repository}/tags")
if ret.status_code != 200:

View file

@ -218,11 +218,20 @@ def get_github_token(ctx: Context) -> str | None:
Get the GITHUB_TOKEN to be able to authenticate to the API.
"""
github_token = os.environ.get("GITHUB_TOKEN")
if github_token is None:
gh = shutil.which("gh")
ret = ctx.run(gh, "auth", "token", check=False, capture=True)
if ret.returncode == 0:
github_token = ret.stdout.decode().strip() or None
if github_token is not None:
ctx.info("$GITHUB_TOKEN was found on the environ")
return github_token
gh = shutil.which("gh")
if gh is None:
ctx.info("The 'gh' CLI tool is not available. Can't get a token using it.")
return github_token
ret = ctx.run(gh, "auth", "token", check=False, capture=True)
if ret.returncode == 0:
ctx.info("Got the GitHub token from the 'gh' CLI tool")
return ret.stdout.decode().strip() or None
ctx.info("Failed to get the GitHub token from the 'gh' CLI tool")
return github_token