Skip to content

Commit

Permalink
Apply pre-commit fix
Browse files Browse the repository at this point in the history
From the artifact of the previous workflow run
  • Loading branch information
geo-ghci-int[bot] committed Dec 2, 2024
1 parent e3946ba commit 847c17e
Show file tree
Hide file tree
Showing 15 changed files with 62 additions and 118 deletions.
25 changes: 15 additions & 10 deletions c2cciutils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
c2cciutils shared utils function.
"""
"""c2cciutils shared utils function."""

import glob
import json
Expand All @@ -18,9 +16,7 @@


def get_repository() -> str:
"""
Get the current GitHub repository like `organization/project`.
"""
"""Get the current GitHub repository like `organization/project`."""
if "GITHUB_REPOSITORY" in os.environ:
return os.environ["GITHUB_REPOSITORY"]

Expand All @@ -44,11 +40,12 @@ def merge(default_config: Any, config: Any) -> Any:
Arguments:
default_config: The default config that will be applied
config: The base config, will be modified
"""
if not isinstance(default_config, dict) or not isinstance(config, dict):
return config

for key in default_config.keys():
for key in default_config:
if key not in config:
config[key] = default_config[key]
else:
Expand All @@ -73,9 +70,7 @@ def get_master_branch(repo: list[str]) -> tuple[str, bool]:


def get_config() -> c2cciutils.configuration.Configuration:
"""
Get the configuration, with project and auto detections.
"""
"""Get the configuration, with project and auto detections."""
config: c2cciutils.configuration.Configuration = {}
if os.path.exists("ci/config.yaml"):
with open("ci/config.yaml", encoding="utf-8") as open_file:
Expand Down Expand Up @@ -155,6 +150,7 @@ def error(
line: The line number of the error
col: The column number of the error
error_type: The kind of error (error or warning)
"""
result = ""
on_ci = os.environ.get("CI", "false").lower() == "true"
Expand Down Expand Up @@ -197,6 +193,7 @@ def compile_re(config: c2cciutils.configuration.VersionTransform, prefix: str =
prefix: The version prefix
Return the compiled transform config.
"""
result = []
for conf in config:
Expand Down Expand Up @@ -226,6 +223,7 @@ def match(
Returns the re match object, the matched config and the value as a tuple
On no match it returns None, value
"""
for conf in config:
matched = conf["from"].match(value)
Expand All @@ -243,6 +241,7 @@ def does_match(value: str, config: list[VersionTransform]) -> bool:
config: The result of `compile`
Returns True it it does match else False
"""
matched, _, _ = match(value, config)
return matched is not None
Expand All @@ -262,6 +261,7 @@ def get_value(matched: Optional[Match[str]], config: Optional[VersionTransform],
value: The default value on returned no match
Return the value
"""
return matched.expand(config.get("to", r"\1")) if matched is not None and config is not None else value

Expand All @@ -272,6 +272,7 @@ def print_versions(config: c2cciutils.configuration.PrintVersions) -> bool:
Arguments:
config: The print configuration
"""
for version in config.get("versions", c2cciutils.configuration.PRINT_VERSIONS_VERSIONS_DEFAULT):
try:
Expand Down Expand Up @@ -310,6 +311,7 @@ def gopass(key: str, default: Optional[str] = None) -> Optional[str]:
default: the value to return if gopass is not found
Return the value
"""
try:
return subprocess.check_output(["gopass", "show", key]).strip().decode()
Expand All @@ -326,6 +328,7 @@ def gopass_put(secret: str, key: str) -> None:
Arguments:
secret: The secret value
key: The key
"""
subprocess.check_output(["gopass", "insert", "--force", key], input=secret.encode())

Expand All @@ -338,6 +341,7 @@ def add_authorization_header(headers: dict[str, str]) -> dict[str, str]:
headers: The headers
Return the headers (to be chained)
"""
try:
token = (
Expand Down Expand Up @@ -375,6 +379,7 @@ def graphql(query_file: str, variables: dict[str, Any], default: Any = None) ->
Return the data result
In case of error it throw an exception
"""
with open(os.path.join(os.path.dirname(__file__), query_file), encoding="utf-8") as query_open:
query = query_open.read()
Expand Down
4 changes: 1 addition & 3 deletions c2cciutils/applications_definition.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Automatically generated file from a JSON schema.
"""
"""Automatically generated file from a JSON schema."""

from typing import Literal, TypedDict, Union

Expand Down
6 changes: 2 additions & 4 deletions c2cciutils/configuration.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Automatically generated file from a JSON schema.
"""
"""Automatically generated file from a JSON schema."""

from typing import Any, Literal, TypedDict, Union

Expand Down Expand Up @@ -721,7 +719,7 @@ class _PrintVersionsVersionsItem(TypedDict, total=False):


class _PublishDockerConfigSnyk(TypedDict, total=False):
"""Checks the published images with Snyk"""
"""Checks the published images with Snyk."""

monitor_args: Union["_PublishDockerSnykMonitorArgsOneof0", "_PublishDockerSnykMonitorArgsOneof1"]
"""
Expand Down
32 changes: 8 additions & 24 deletions c2cciutils/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@


class PrintVersions:
"""
Print some tools versions.
"""
"""Print some tools versions."""

def __init__(self, config: c2cciutils.configuration.PrintVersions) -> None:
"""Construct."""
Expand All @@ -24,9 +22,7 @@ def __call__(self) -> None:


class PrintConfig:
"""
Print the configuration.
"""
"""Print the configuration."""

def __init__(self, config: c2cciutils.configuration.Configuration) -> None:
"""Construct."""
Expand All @@ -40,49 +36,37 @@ def __call__(self) -> None:


def print_environment_variables() -> None:
"""
Print the environment variables.
"""
"""Print the environment variables."""
for name, value in sorted(os.environ.items()):
if name != "GITHUB_EVENT":
print(f"{name}: {value}")


def print_github_event_file() -> None:
"""
Print the GitHub event file.
"""
"""Print the GitHub event file."""
if "GITHUB_EVENT_PATH" in os.environ:
with open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8") as event:
print(event.read())


def print_github_event_object() -> None:
"""
Print the GitHub event object.
"""
"""Print the GitHub event object."""
github_event = json.loads(os.environ["GITHUB_EVENT"])
print(yaml.dump(github_event, indent=2))


def print_python_package_version() -> None:
"""
Print the version of the Python packages.
"""
"""Print the version of the Python packages."""
subprocess.run(["python3", "-m", "pip", "freeze", "--all"]) # pylint: disable=subprocess-run-check


def print_node_package_version() -> None:
"""
Print the version of the Python packages.
"""
"""Print the version of the Python packages."""
subprocess.run(["npm", "list", "--global"]) # pylint: disable=subprocess-run-check


def print_debian_package_version() -> None:
"""
Print the version of the Python packages.
"""
"""Print the version of the Python packages."""
subprocess.run(["dpkg", "--list"]) # pylint: disable=subprocess-run-check


Expand Down
8 changes: 2 additions & 6 deletions c2cciutils/lib/docker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Some utility functions for Docker images.
"""
"""Some utility functions for Docker images."""

import os
import subprocess # nosec: B404
Expand Down Expand Up @@ -102,9 +100,7 @@ def get_dpkg_packages_versions(


def get_versions_config() -> tuple[dict[str, dict[str, str]], bool]:
"""
Get the versions from the config file.
"""
"""Get the versions from the config file."""
if os.path.exists("ci/dpkg-versions.yaml"):
with open("ci/dpkg-versions.yaml", encoding="utf-8") as versions_file:
return (
Expand Down
2 changes: 2 additions & 0 deletions c2cciutils/lib/oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,10 @@ def pypi_login() -> None:
Connect to PyPI using OpenID Connect and mint a token for the user.
See Also
--------
- https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/about-security-hardening-with-openid-connect
- https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-pypi
"""
pypirc_filename = os.path.expanduser("~/.pypirc")

Expand Down
43 changes: 15 additions & 28 deletions c2cciutils/publish.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
The publishing functions.
"""
"""The publishing functions."""

import argparse
import datetime
Expand All @@ -10,11 +8,11 @@
import re
import subprocess # nosec
import sys
import tomllib
import uuid
from typing import Optional

import ruamel.yaml
import tomllib
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
Expand All @@ -24,15 +22,11 @@


class GoogleCalendar:
"""
Interact with the Google Calendar API.
"""
"""Interact with the Google Calendar API."""

# pylint: disable=too-many-instance-attributes
def __init__(self) -> None:
"""
Initialize.
"""
"""Initialize."""
self.scopes = ["https://www.googleapis.com/auth/calendar"] # in fact it is better to hard-code this
self.credentials_pickle_file = os.environ.get("TMP_CREDS_FILE", f"/tmp/{uuid.uuid4()}.pickle")
self.credentials_json_file = os.environ.get(
Expand Down Expand Up @@ -62,9 +56,7 @@ def __init__(self) -> None:
self.service = build("calendar", "v3", credentials=self.creds)

def init_calendar_service(self) -> Credentials: # type: ignore
"""
Initialize the calendar service.
"""
"""Initialize the calendar service."""
# The file token pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
Expand Down Expand Up @@ -95,19 +87,15 @@ def init_calendar_service(self) -> Credentials: # type: ignore
pickle.dump(creds, token)

def _update_creds(self) -> None:
"""
Update the credentials.
"""
"""Update the credentials."""
self.client_id = self.creds.client_id
self.client_secret = self.creds.client_secret
self.token = self.creds.token
self.token_uri = self.creds.token_uri
self.refresh_token = self.creds.refresh_token

def print_all_calendars(self) -> None:
"""
Print all calendar events.
"""
"""Print all calendar events."""
# list all the calendars that the user has access to.
# used to debug credentials
print("Getting list of calendars")
Expand All @@ -129,6 +117,7 @@ def print_latest_events(self, time_min: Optional[datetime.datetime] = None) -> N
Arguments:
time_min: The time to be considered.
"""
now = datetime.datetime.utcnow()
if not time_min:
Expand Down Expand Up @@ -163,6 +152,7 @@ def create_event(
Arguments:
summary: The event summary
description: The event description
"""
now = datetime.datetime.now()
start = now.isoformat()
Expand All @@ -178,9 +168,7 @@ def create_event(
print(f"Created event with id: {event_result['id']}")

def save_credentials_to_gopass(self) -> None:
"""
Save the calendar credentials to gopass.
"""
"""Save the calendar credentials to gopass."""
objects_to_save = {
"gs/ci/google_calendar/calendarId": self.calendar_id,
"gs/ci/google_calendar/token": self.token,
Expand All @@ -194,17 +182,13 @@ def save_credentials_to_gopass(self) -> None:
c2cciutils.gopass_put(secret, key)

def __del__(self) -> None:
"""
Delete the credentials file.
"""
"""Delete the credentials file."""
if os.path.exists(self.credentials_pickle_file):
os.remove(self.credentials_pickle_file)


def main_calendar() -> None:
"""
Run the calendar main function.
"""
"""Run the calendar main function."""
parser = argparse.ArgumentParser(
description="Interact with google API for the Docker publishing calendar"
)
Expand Down Expand Up @@ -254,6 +238,7 @@ def pip(
version_branch, feature_branch, feature_tag (for pull request)
publish: If False only check the package
package: The package configuration
"""
print(f"::group::{'Publishing' if publish else 'Checking'} '{package.get('path')}' to pypi")
sys.stdout.flush()
Expand Down Expand Up @@ -352,6 +337,7 @@ def docker(
tag_src: The source tag (usually latest)
dst_tags: Publish using the provided tags
images_full: The list of published images (with tag), used to build the dispatch event
"""
print(
f"::group::Publishing {image_config['name']} to the server {name} using the tags {', '.join(dst_tags)}"
Expand Down Expand Up @@ -411,6 +397,7 @@ def helm(folder: str, version: str, owner: str, repo: str, commit_sha: str, toke
repo: The GitHub repository name
commit_sha: The sha of the current commit
token: The GitHub token
"""
print(f"::group::Publishing Helm chart from '{folder}' to GitHub release")
sys.stdout.flush()
Expand Down
Loading

0 comments on commit 847c17e

Please sign in to comment.