Fixes deleting images if the branch API returns an error code and makes the error code a failure

This commit is contained in:
Trenton H 2022-10-31 09:43:33 -07:00
parent 0d941bfb05
commit 9214b41255
3 changed files with 27 additions and 20 deletions

View File

@ -249,10 +249,12 @@ class MainImageTagsCleaner(RegistryTagsCleaner):
will be removed, if the corresponding branch no longer exists. will be removed, if the corresponding branch no longer exists.
""" """
# Default to everything gets kept still
super().decide_what_tags_to_keep()
# Locate the feature branches # Locate the feature branches
feature_branches = {} feature_branches = {}
for branch in self.branch_api.get_branches( for branch in self.branch_api.get_branches(
owner=self.repo_owner,
repo=self.repo_name, repo=self.repo_name,
): ):
if branch.name.startswith("feature-"): if branch.name.startswith("feature-"):
@ -261,6 +263,10 @@ class MainImageTagsCleaner(RegistryTagsCleaner):
logger.info(f"Located {len(feature_branches)} feature branches") logger.info(f"Located {len(feature_branches)} feature branches")
if not len(feature_branches):
# Our work here is done, delete nothing
return
# Filter to packages which are tagged with feature-* # Filter to packages which are tagged with feature-*
packages_tagged_feature: List[ContainerPackage] = [] packages_tagged_feature: List[ContainerPackage] = []
for package in self.all_package_versions: for package in self.all_package_versions:

View File

@ -15,7 +15,7 @@ from typing import Dict
from typing import List from typing import List
from typing import Optional from typing import Optional
import requests import httpx
logger = logging.getLogger("github-api") logger = logging.getLogger("github-api")
@ -28,15 +28,15 @@ class _GithubApiBase:
def __init__(self, token: str) -> None: def __init__(self, token: str) -> None:
self._token = token self._token = token
self._session: Optional[requests.Session] = None self._client: Optional[httpx.Client] = None
def __enter__(self) -> "_GithubApiBase": def __enter__(self) -> "_GithubApiBase":
""" """
Sets up the required headers for auth and response Sets up the required headers for auth and response
type from the API type from the API
""" """
self._session = requests.Session() self._client = httpx.Client()
self._session.headers.update( self._client.headers.update(
{ {
"Accept": "application/vnd.github.v3+json", "Accept": "application/vnd.github.v3+json",
"Authorization": f"token {self._token}", "Authorization": f"token {self._token}",
@ -49,14 +49,14 @@ class _GithubApiBase:
Ensures the authorization token is cleaned up no matter Ensures the authorization token is cleaned up no matter
the reason for the exit the reason for the exit
""" """
if "Accept" in self._session.headers: if "Accept" in self._client.headers:
del self._session.headers["Accept"] del self._client.headers["Accept"]
if "Authorization" in self._session.headers: if "Authorization" in self._client.headers:
del self._session.headers["Authorization"] del self._client.headers["Authorization"]
# Close the session as well # Close the session as well
self._session.close() self._client.close()
self._session = None self._client = None
def _read_all_pages(self, endpoint): def _read_all_pages(self, endpoint):
""" """
@ -66,7 +66,7 @@ class _GithubApiBase:
internal_data = [] internal_data = []
while True: while True:
resp = self._session.get(endpoint) resp = self._client.get(endpoint)
if resp.status_code == 200: if resp.status_code == 200:
internal_data += resp.json() internal_data += resp.json()
if "next" in resp.links: if "next" in resp.links:
@ -76,7 +76,7 @@ class _GithubApiBase:
break break
else: else:
logger.warning(f"Request to {endpoint} return HTTP {resp.status_code}") logger.warning(f"Request to {endpoint} return HTTP {resp.status_code}")
break resp.raise_for_status()
return internal_data return internal_data
@ -113,14 +113,15 @@ class GithubBranchApi(_GithubApiBase):
def __init__(self, token: str) -> None: def __init__(self, token: str) -> None:
super().__init__(token) super().__init__(token)
self._ENDPOINT = "https://api.github.com/repos/{OWNER}/{REPO}/branches" self._ENDPOINT = "https://api.github.com/repos/{REPO}/branches"
def get_branches(self, owner: str, repo: str) -> List[GithubBranch]: def get_branches(self, repo: str) -> List[GithubBranch]:
""" """
Returns all current branches of the given repository owned by the given Returns all current branches of the given repository owned by the given
owner or organization. owner or organization.
""" """
endpoint = self._ENDPOINT.format(OWNER=owner, REPO=repo) # The environment GITHUB_REPOSITORY already contains the owner in the correct location
endpoint = self._ENDPOINT.format(REPO=repo)
internal_data = self._read_all_pages(endpoint) internal_data = self._read_all_pages(endpoint)
return [GithubBranch(branch) for branch in internal_data] return [GithubBranch(branch) for branch in internal_data]
@ -247,7 +248,7 @@ class GithubContainerRegistryApi(_GithubApiBase):
""" """
Deletes the given package version from the GHCR Deletes the given package version from the GHCR
""" """
resp = self._session.delete(package_data.url) resp = self._client.delete(package_data.url)
if resp.status_code != 204: if resp.status_code != 204:
logger.warning( logger.warning(
f"Request to delete {package_data.url} returned HTTP {resp.status_code}", f"Request to delete {package_data.url} returned HTTP {resp.status_code}",
@ -266,7 +267,7 @@ class GithubContainerRegistryApi(_GithubApiBase):
PACKAGE_VERSION_ID=package_data.id, PACKAGE_VERSION_ID=package_data.id,
) )
resp = self._session.post(endpoint) resp = self._client.post(endpoint)
if resp.status_code != 204: if resp.status_code != 204:
logger.warning( logger.warning(
f"Request to delete {endpoint} returned HTTP {resp.status_code}", f"Request to delete {endpoint} returned HTTP {resp.status_code}",

View File

@ -64,9 +64,9 @@ jobs:
with: with:
python-version: "3.10" python-version: "3.10"
- -
name: Install requests name: Install httpx
run: | run: |
python -m pip install requests python -m pip install httpx
# #
# Clean up primary package # Clean up primary package
# #