Skip to content

Commit

Permalink
Refactor code and improve readability
Browse files Browse the repository at this point in the history
Several changes were made across various modules and tests to improve readability and maintainability. The key edits include modifying verbose instructions to make them more succinct, discarding the "snapcraft.yaml" file, and refactoring certain functions. Unnecessary import statements were also removed. This refactor should make the code easier to understand and work with.
  • Loading branch information
Jochem Berends committed Jun 24, 2024
1 parent bc332cc commit b7cbf7d
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 96 deletions.
18 changes: 11 additions & 7 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 10 additions & 6 deletions kecpkg/commands/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,23 +55,26 @@
"update_package_info",
is_flag=True,
default=True,
help="Update the `package-info.json` for the KE-crunch execution to point to correct entrypoint based on "
"settings. This is okay to leave ON. Use `--no-update` if you have a custom `package-info.json`.",
help="Update the `package-info.json` for the KE-crunch execution to point to correct "
"entrypoint based on settings. This is okay to leave ON. Use `--no-update` if you "
"have a custom `package-info.json`.",
)
@click.option(
"--sign/--no-sign",
"do_sign",
is_flag=True,
default=False,
help="Sign the contents of the package with a cryptographic key from the keyring. Defaults to not sign.",
help="Sign the contents of the package with a cryptographic key from the keyring. Defaults "
"to not sign.",
)
@click.option(
"--keyid",
"--key-id",
"-k",
"sign_keyid",
help="ID of the cryptographic key to do the sign the contents of the built package. If not provided it "
"will use the default key from the KECPKG keystore. Use in combination with `--sign`",
help="ID of the cryptographic key to do the sign the contents of the built package. If not"
"provided it will use the default key from the KECPKG keystore. Use in combination "
"with `--sign`",
)
@click.option(
"--passphrase",
Expand Down Expand Up @@ -167,7 +170,8 @@ def generate_artifact_hashes(package_dir, artifacts, settings, verbose=False):
artifacts_content = []

for af in artifacts:
# we do not need to create a hash from the ARTIFACTS and ARTIFACTS.SIG file if they are present in the list
# we do not need to create a hash from the ARTIFACTS and ARTIFACTS.SIG file if they
# are present in the list
if af not in [artifacts_fn, artifacts_fn + ".SIG"]:
af_fp = os.path.join(package_dir, af)
artifacts_content.append(
Expand Down
9 changes: 6 additions & 3 deletions kecpkg/commands/sign.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
"do_import",
type=click.Path(exists=True),
help="Import secret keyfile (in .asc) to the KECPKG keyring which will be used for signing. "
"You can export a created key in gpg with `gpg -a --export-secret-key [keyID] > secret_key.asc`.",
"You can export a created key in gpg with `gpg -a --export-secret-key [keyID] > "
"secret_key.asc`.",
)
@click.option(
"--delete-key",
Expand All @@ -78,7 +79,8 @@
"-e",
"do_export_key",
type=click.Path(),
help="Export public key to filename with `--keyid KeyID` in .ASC format for public distribution.",
help="Export public key to filename with `--keyid KeyID` in .ASC format for "
"public distribution.",
)
@click.option(
"--clear-keyring",
Expand Down Expand Up @@ -137,7 +139,8 @@ def _do_list(gpg, explain=False):
else:
if explain:
echo_info(
"No keys found in KECPKG keyring. Use `--import-key` or `--create-key` to add a "
"No keys found in KECPKG keyring. Use `--import-key` or "
"`--create-key` to add a "
"secret key to the KECPKG keyring in order to sign KECPKG's."
)
sys.exit(1)
Expand Down
26 changes: 9 additions & 17 deletions kecpkg/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,16 +76,18 @@ def create_venv(package_dir, settings, pypath=None, use_global=False, verbose=Fa
:param package_dir: the full path to the package directory
:param settings: the settings dict (including the venv_dir name to create the right venv)
:param pypath: absolute path to the python binary interpreter to create the virtual environment with
:param use_global: Use global sysem site packages when creating virtual environment (default False)
:param pypath: absolute path to the python binary interpreter to create the virtual
environment with
:param use_global: Use global sysem site packages when creating virtual environment
(default False)
:param verbose: Use verbosity (default False)
"""
venv_dir = os.path.join(package_dir, settings.get("venv_dir"))

if not pypath:
from distutils.spawn import find_executable
import shutil

pypath = find_executable(get_proper_python())
pypath = shutil.which(get_proper_python())

command = [sys.executable, "-m", "virtualenv", venv_dir, "-p", pypath]
if use_global: # no cov
Expand Down Expand Up @@ -118,11 +120,8 @@ def pip_install_venv(package_dir, settings, verbose=False):
if not os.path.exists(
os.path.join(package_dir, settings.get("requirements_filename"))
):
echo_failure(
"could not find requirements.txt to install, check if `{}` exists or update settings".format(
settings.get("requirements_filename")
)
)
echo_failure(f"could not find requirements.txt to install, check if "
f"`{settings.get('requirements_filename')}` exists or update settings")
sys.exit(1)

install_command = [
Expand All @@ -144,14 +143,7 @@ def pip_install_venv(package_dir, settings, verbose=False):
)
)
result = None
if six.PY3:
result = subprocess.run(install_command, shell=NEED_SUBPROCESS_SHELL)
return result.returncode
elif six.PY2:
result = subprocess.check_output(
install_command, shell=NEED_SUBPROCESS_SHELL
)
return result and 0 or -1
result = subprocess.run(install_command, shell=NEED_SUBPROCESS_SHELL)

if result:
echo_success(str(result))
Expand Down
1 change: 0 additions & 1 deletion kecpkg/files/templates/script.py.template
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ This script is part of package `{{ package_name }}`
Created by: {{ name }} <{{ email }}>
{%- endif -%}
"""
from pykechain import get_project
import sys

__version__ = '{{ version }}'
Expand Down
28 changes: 12 additions & 16 deletions kecpkg/gpg.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,26 @@
import subprocess
import sys
from datetime import datetime
from typing import Any, Optional

import six
from typing import Any, List, Optional

from gnupg import GPG

from kecpkg.settings import GNUPG_KECPKG_HOME
from kecpkg.utils import (
ON_LINUX,
ON_WINDOWS,
ON_MACOS,
echo_failure,
read_chunks,
echo_info,
ensure_dir_exists,
ON_LINUX, ON_MACOS, ON_WINDOWS, echo_failure, echo_info, ensure_dir_exists, read_chunks,
)

LOGLEVEL = logging.INFO


def hash_of_file(path, algorithm="sha256"):
"""Return the hash digest of a file."""
"""Return the my_hash digest of a file."""
with open(path, "rb") as archive:
hash = hashlib.new(algorithm)
my_hash = hashlib.new(algorithm)
for chunk in read_chunks(archive):
hash.update(chunk)
return hash.hexdigest()
my_hash.update(chunk)
return my_hash.hexdigest()


__gpg: Optional[GPG] = None
Expand Down Expand Up @@ -89,12 +82,14 @@ def get_gpg() -> GPG:
"We checked: '{}'".format(gpg_bin)
)
echo_failure(
"- For Linux please install GnuPG using your package manager. In Ubuntu/Debian this can be "
"- For Linux please install GnuPG using your package manager. In "
"Ubuntu/Debian this can be "
"achieved with `sudo apt install gnupg`."
)
echo_failure("- For Mac OSX please install GnuPG using `brew install gpg`.")
echo_failure(
"- For Windows please install GnuPG using the downloads via: https://gnupg.org/download/"
"- For Windows please install GnuPG using the downloads via: "
"https://gnupg.org/download/"
)
sys.exit(1)

Expand Down Expand Up @@ -137,7 +132,8 @@ def tabulate_keys(gpg: GPG, explain: Optional[bool] = False) -> None:
If explain = Truem, it will exit with returncode 1 when no keys are present.
:param gpg: GPG objects
:param explain: With explain is True, more text is added and will exit(1) when no keys are present.
:param explain: With explain is True, more text is added and will exit(1) when no
keys are present.
:return: None.
"""
result = gpg.list_keys(secret=True)
Expand Down
6 changes: 3 additions & 3 deletions kecpkg/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import platform
import re
import shutil
import six
import sys
from contextlib import contextmanager

Expand All @@ -33,8 +32,9 @@ def create_file(filepath, content=None, overwrite=True):
Will overwrite file already in place if overwrite flag is set.
If a list is provided each line in the list is written on a new line in the file (`fp.writelines`)
otherwise the string will be written as such and newline characters (`\\\\n`) will be respected.
If a list is provided each line in the list is written on a new line in the file (
`fp.writelines`) otherwise the string will be written as such and newline characters (
`\\\\n`) will be respected.
:param filepath: full path to a file to create
:param content: textual content.
Expand Down
34 changes: 0 additions & 34 deletions snapcraft.yaml

This file was deleted.

6 changes: 3 additions & 3 deletions tests/commands/test_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from click.testing import CliRunner

from kecpkg.cli import kecpkg
from kecpkg.settings import load_settings, save_settings, copy_default_settings
from kecpkg.utils import get_package_dir, ensure_dir_exists
from tests.utils import temp_chdir, BaseTestCase, touch_file
from kecpkg.settings import copy_default_settings, save_settings
from kecpkg.utils import ensure_dir_exists, get_package_dir
from tests.utils import BaseTestCase, temp_chdir, touch_file


class TestCommandPurge(BaseTestCase):
Expand Down
3 changes: 2 additions & 1 deletion tests/commands/test_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
@skipIf(running_on_ci(), reason="Test do not work on a CI environment")
@skipIf(
"os.getenv('KECHAIN_URL') is None",
reason="Skipping test as the KECHAIN_URL is not available as environment variable. Cannot upload kecpkg to "
reason="Skipping test as the KECHAIN_URL is not available as environment variable. "
"Cannot upload kecpkg to "
"test this functionality. Provice a `.env` file locally to enable these tests.",
)
class TestCommandUpload(BaseTestCase):
Expand Down
9 changes: 4 additions & 5 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from contextlib import contextmanager
from unittest import TestCase

import six
from click.testing import CliRunner


Expand Down Expand Up @@ -61,17 +60,17 @@ def connected_to_internet(): # no cov
# Test connection
socket.create_connection((host, 80), 2)
return True
except:
except OSError:
return False


def running_on_ci(): # no cov
# type: () -> bool
"""If the system is running on a CI platform."""
if (
os.environ.get("CI")
or os.environ.get("TRAVIS")
or os.environ.get("GITHUB_ACTIONS")
os.environ.get("CI")
or os.environ.get("TRAVIS")
or os.environ.get("GITHUB_ACTIONS")
):
return True
return False

0 comments on commit b7cbf7d

Please sign in to comment.