Skip to content

Commit

Permalink
Fix ruff issues
Browse files Browse the repository at this point in the history
Runs `ruff format .` on the workspace.
  • Loading branch information
Javagedes committed Oct 1, 2024
1 parent cfea0e8 commit 646cdd9
Show file tree
Hide file tree
Showing 88 changed files with 3,901 additions and 3,265 deletions.
19 changes: 11 additions & 8 deletions BasicDevTests.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ def TestFilenameLowercase(apath):

def PackageAndModuleValidCharacters(apath):
"""Check pep8 recommendations for package and module names."""
match = re.match('^[a-z0-9_/.]+$', apath.replace("\\", "/"))
match = re.match("^[a-z0-9_/.]+$", apath.replace("\\", "/"))
if match is None:
logging.critical(
f"PackageAndModuleValidCharacters failure: package or module name {apath} has something invalid")
f"PackageAndModuleValidCharacters failure: package or module name {apath} has something invalid"
)
return False
return True

Expand All @@ -55,7 +56,9 @@ def TestNoSpaces(apath):


def TestRequiredLicense(apath):
licenses = ["SPDX-License-Identifier: BSD-2-Clause-Patent", ]
licenses = [
"SPDX-License-Identifier: BSD-2-Clause-Patent",
]
try:
with open(apath, "rb") as f_obj:
contents = f_obj.read().decode()
Expand All @@ -79,15 +82,15 @@ def TestRequiredLicense(apath):
error = 0
for a in py_files:
aRelativePath = os.path.relpath(a, os.getcwd())
if (not TestEncodingOk(a, "ascii")):
if not TestEncodingOk(a, "ascii"):
error += 1
if (not TestFilenameLowercase(aRelativePath)):
if not TestFilenameLowercase(aRelativePath):
error += 1
if (not TestNoSpaces(aRelativePath)):
if not TestNoSpaces(aRelativePath):
error += 1
if (not TestRequiredLicense(a)):
if not TestRequiredLicense(a):
error += 1
if (not PackageAndModuleValidCharacters(aRelativePath)): # use relative path so only test within package
if not PackageAndModuleValidCharacters(aRelativePath): # use relative path so only test within package
error += 1

logging.critical(f"Found {error} error(s) in {len(py_files)} file(s)")
Expand Down
3 changes: 2 additions & 1 deletion ConfirmVersionAndTag.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
"""Script to check that the wheel/package created is aligned on a git tag."""

import glob
import os
import sys

p = os.path.join(os.getcwd(), "dist")
whl_file = glob.glob(os.path.join(p, "*.whl"))
if (len(whl_file) != 1):
if len(whl_file) != 1:
for filename in whl_file:
print(filename)
raise Exception("Too many wheel files")
Expand Down
4 changes: 2 additions & 2 deletions docs/user/features/creating_invocable.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ class SettingsManager(UpdateSettingsManager, CiSetupSettingsManager, BinaryBuild
logging.warning(f"Deleting {output_dir}")
shutil.rmtree(output_dir, ignore_errors=True)
os.makedirs(output_dir)
except:
except Exception:
pass

self.nuget_version = self._GetNextVersion(self.nuget_version)
Expand Down Expand Up @@ -680,7 +680,7 @@ class SettingsManager(UpdateSettingsManager, CiSetupSettingsManager, BinaryBuild
logging.warning(f"Deleting {output_dir}")
shutil.rmtree(output_dir, ignore_errors=True)
os.makedirs(output_dir)
except:
except Exception:
pass

self.nuget_version = self._GetNextVersion(self.nuget_version)
Expand Down
29 changes: 21 additions & 8 deletions docs/user/gen_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Used in conjunction with mkdocs to generate static markdown files for each
file inside the edk2toolext package for ReadTheDocs hosting.
"""

import mkdocs_gen_files
import glob
import os
Expand All @@ -19,11 +20,23 @@ def main():
"""Entry into script that is executed."""
files = glob.glob("**/*.py", recursive=True, root_dir="edk2toolext")

excluded_files = ["__init__.py", "capsule_helper.py", "capsule_tool.py", "pyopenssl_signer.py",
"signing_helper.py", "signtool_signer.py", "sig_db_tool.py",
"firmware_policy_tool.py", "image_validation.py", "nuget_publishing.py",
"omnicache.py", "nuget.py", "versioninfo_tool.py", "versioninfo_helper.py",
"secureboot_audit.py"]
excluded_files = [
"__init__.py",
"capsule_helper.py",
"capsule_tool.py",
"pyopenssl_signer.py",
"signing_helper.py",
"signtool_signer.py",
"sig_db_tool.py",
"firmware_policy_tool.py",
"image_validation.py",
"nuget_publishing.py",
"omnicache.py",
"nuget.py",
"versioninfo_tool.py",
"versioninfo_helper.py",
"secureboot_audit.py",
]

for file_path in files:
edit_path = file_path
Expand All @@ -40,7 +53,7 @@ def main():

filename = f"api{os.sep}{file_path}"
with mkdocs_gen_files.open(filename, "w") as f:
ff = file_path.replace(os.sep, '.').replace('.md', '')
ff = file_path.replace(os.sep, ".").replace(".md", "")
ff = f"edk2toolext.{ff}"
print(f"::: {ff}", file=f)
print(" handler: python", file=f)
Expand All @@ -54,9 +67,9 @@ def main():
print(" show_source: False", file=f)

# Point the "Edit on Github" button in the docs to point at the source code
edit_path = os.path.join('..', 'edk2toolext', edit_path)
edit_path = os.path.join("..", "edk2toolext", edit_path)
mkdocs_gen_files.set_edit_path(filename, edit_path)

with mkdocs_gen_files.open("api/.pages", "w") as f:
print("title: API Reference", file=f)

Expand Down
31 changes: 18 additions & 13 deletions edk2toolext/base_abstract_invocable.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
##

"""The Base abstract Invocable that all other invocables should inherit from."""

import logging
import os
import sys
Expand All @@ -29,6 +30,7 @@ class BaseAbstractInvocable(object):
plugin_manager (plugin_manager.PluginManager): the plugin manager
helper (HelperFunctions): container for all helper functions
"""

def __init__(self) -> None:
"""Init the Invocable."""
self.log_filename = None
Expand Down Expand Up @@ -171,7 +173,7 @@ def ConfigureLogging(self) -> None:
!!! tip
Optional override in a subclass if new behavior is needed
"""
logger = logging.getLogger('')
logger = logging.getLogger("")
logger.setLevel(self.GetLoggingLevel("base"))

# Adjust console mode depending on mode.
Expand All @@ -182,10 +184,10 @@ def ConfigureLogging(self) -> None:
log_directory = os.path.join(self.GetWorkspaceRoot(), self.GetLoggingFolderRelativeToRoot())

txtlogfile = self.GetLoggingLevel("txt")
if (txtlogfile is not None):
logfile, filelogger = edk2_logging.setup_txt_logger(log_directory,
self.GetLoggingFileName("txt"),
txtlogfile)
if txtlogfile is not None:
logfile, filelogger = edk2_logging.setup_txt_logger(
log_directory, self.GetLoggingFileName("txt"), txtlogfile
)
self.log_filename = logfile

logging.info("Log Started: " + datetime.strftime(datetime.now(), "%A, %B %d, %Y %I:%M%p"))
Expand All @@ -206,34 +208,37 @@ def Invoke(self) -> None:
# Next, get the environment set up.
#
(build_env, shell_env) = self_describing_environment.BootstrapEnvironment(
self.GetWorkspaceRoot(), self.GetActiveScopes(), self.GetSkippedDirectories())
self.GetWorkspaceRoot(), self.GetActiveScopes(), self.GetSkippedDirectories()
)

# Make sure the environment verifies IF it is required for this invocation
if self.GetVerifyCheckRequired() and not self_describing_environment.VerifyEnvironment(
self.GetWorkspaceRoot(), self.GetActiveScopes(), self.GetSkippedDirectories()):
raise RuntimeError("External Dependencies in the environment are out of date. "
"Consider running stuart_update to possibly resolve this issue.")
self.GetWorkspaceRoot(), self.GetActiveScopes(), self.GetSkippedDirectories()
):
raise RuntimeError(
"External Dependencies in the environment are out of date. "
"Consider running stuart_update to possibly resolve this issue."
)

# Load plugins
logging.log(edk2_logging.SECTION, "Loading Plugins")

self.plugin_manager = plugin_manager.PluginManager()
failedPlugins = self.plugin_manager.SetListOfEnvironmentDescriptors(
build_env.plugins)
failedPlugins = self.plugin_manager.SetListOfEnvironmentDescriptors(build_env.plugins)
if failedPlugins:
logging.critical("One or more plugins failed to load. Halting build.")
for a in failedPlugins:
logging.error("Failed Plugin: {0}".format(a["name"]))
raise Exception("One or more plugins failed to load.")

self.helper = HelperFunctions()
if (self.helper.LoadFromPluginManager(self.plugin_manager) > 0):
if self.helper.LoadFromPluginManager(self.plugin_manager) > 0:
raise Exception("One or more helper plugins failed to load.")

logging.log(edk2_logging.SECTION, "Start Invocable Tool")
retcode = self.Go()
logging.log(edk2_logging.SECTION, "Summary")
if (retcode != 0):
if retcode != 0:
logging.error("Error")
else:
edk2_logging.log_progress("Success")
Expand Down
6 changes: 4 additions & 2 deletions edk2toolext/bin/nuget.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
"""This module contains code that knows how to download nuget."""

import logging
import os
import urllib.error
Expand Down Expand Up @@ -36,15 +37,15 @@ def DownloadNuget(unpack_folder: str = None) -> str:
(RuntimeError): Sha256 did not match
"""
if unpack_folder is None:
unpack_folder = resources.files('edk2toolext.bin')
unpack_folder = resources.files("edk2toolext.bin")

out_file_name = Path(unpack_folder) / "NuGet.exe"
# check if we have the nuget file already downloaded
if not out_file_name.is_file():
logging.debug(f"Attempting to download NuGet to: {out_file_name}")
try:
# Download the file and save it locally under `temp_file_name`
with urllib.request.urlopen(URL) as response, open(out_file_name, 'wb') as out_file:
with urllib.request.urlopen(URL) as response, open(out_file_name, "wb") as out_file:
out_file.write(response.read())
except urllib.error.HTTPError as e:
logging.error("We ran into an issue when getting NuGet")
Expand All @@ -53,6 +54,7 @@ def DownloadNuget(unpack_folder: str = None) -> str:
# do the hash to make sure the file is good
with open(out_file_name, "rb") as file:
import hashlib

temp_file_sha256 = hashlib.sha256(file.read()).hexdigest()
if temp_file_sha256.lower() != SHA256.lower():
os.remove(out_file_name)
Expand Down
Loading

0 comments on commit 646cdd9

Please sign in to comment.