From 006c0eb4689e2015663bc0fa054b87e2b97dafc0 Mon Sep 17 00:00:00 2001 From: ashitsalesforce <71143047+ashitsalesforce@users.noreply.github.com> Date: Sun, 1 Jun 2025 23:51:44 -0700 Subject: [PATCH 1/7] refactored code better error handling, logging, and cleanup of temporary directories --- updateSWT.py | 440 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 274 insertions(+), 166 deletions(-) diff --git a/updateSWT.py b/updateSWT.py index 2e333060..ec7dd82e 100755 --- a/updateSWT.py +++ b/updateSWT.py @@ -1,6 +1,11 @@ #!/usr/bin/env python3 -import requests, zipfile, io, shutil, os, sys +import requests +import zipfile +import io +import shutil +import os +import sys import subprocess from bs4 import BeautifulSoup from os.path import expanduser @@ -9,6 +14,9 @@ import argparse import atexit import tempfile +import logging +from typing import Optional, Dict, List +from dataclasses import dataclass #################################################################### # Prerequisites: @@ -23,190 +31,290 @@ # # Follow-on manual steps: # - Update version value for SWT dependencies in pom.xml with the downloaded SWT version. -# -# Outline of the steps taken: -# - Start at https://download.eclipse.org/eclipse/downloads/ -# - Go to "Latest Release" section -# - Click on the first link in the "Build Name" column -# - Go to "SWT Binary and Source" section -# - Click on the links next to "Windows (64 bit version)", "Mac OSX (64 bit version)", and "Mac OSX (64 bit version for Arm64/AArch64)" -# - Extract the contents of the zip file -# - Go to the extraction folder and run mvn install:install-file command -# #################################################################### -LOCAL_REPO_DIR = "./local-proj-repo" -TEMP_DIR = None +# Configure logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + datefmt='%Y-%m-%d %H:%M:%S' +) +logger = logging.getLogger(__name__) -def is_exe(fpath): +# Constants +LOCAL_REPO_DIR = "./local-proj-repo" +ECLIPSE_DOWNLOAD_URL = "https://download.eclipse.org/eclipse/downloads/" +SWT_SIGNATURE_FILES = [ + "META-INF/ECLIPSE_.SF", + "META-INF/ECLIPSE_.DSA", + "META-INF/ECLIPSE_.RSA" +] + +# Platform configurations +PLATFORM_CONFIGS = { + "swtwin32_x86_64": "Windows (x86 64-bit)", + "swtwin32_aarch64": "Windows (ARM 64-bit)", + "swtmac_x86_64": "Mac OSX (x86 64-bit)", + "swtmac_aarch64": "Mac OSX (ARM 64-bit)", + "swtlinux_x86_64": "Linux (x86 64-bit)", + "swtlinux_aarch64": "Linux (ARM 64-bit)" +} + +@dataclass +class SWTConfig: + """Configuration for SWT update process.""" + version: str + force_update: bool + git_clone_root: str + temp_dir: Optional[str] = None + +class SWTUpdateError(Exception): + """Base exception for SWT update errors.""" + pass + +class MavenNotFoundError(SWTUpdateError): + """Raised when Maven is not found in PATH.""" + pass + +class VersionNotFoundError(SWTUpdateError): + """Raised when specified version is not found for download.""" + pass + +def is_exe(fpath: str) -> bool: + """Check if a file is executable. + + Args: + fpath: Path to the file to check + + Returns: + bool: True if file exists and is executable + """ return os.path.isfile(fpath) and os.access(fpath, os.X_OK) -def cleanupBeforeExit(): - if TEMP_DIR and os.path.exists(TEMP_DIR): - shutil.rmtree(TEMP_DIR) +def cleanupBeforeExit(config: Optional[SWTConfig] = None) -> None: + """Clean up temporary directory before script exit. + + Args: + config: SWT configuration containing temp directory path + """ + if config and config.temp_dir and os.path.exists(config.temp_dir): + logger.info(f"Cleaning up temporary directory: {config.temp_dir}") + shutil.rmtree(config.temp_dir) + +def getSWTDownloadLinkForPlatform(soup: BeautifulSoup, platformString: str) -> str: + """Get the download link for a specific platform from the Eclipse download page. + + Args: + soup: BeautifulSoup object of the download page + platformString: Platform identifier string to search for -def exitWithError(errorStr): - print(errorStr) - sys.exit(-1) - -########################################################### - -def getSWTDownloadLinkForPlatform(soup, platformString): + Returns: + str: Download link for the platform + + Raises: + VersionNotFoundError: If platform link is not found + """ results = soup.find(id="SWT").find_next("td").string - while results != None and results != platformString : + while results is not None and results != platformString: results = results.find_next("td").string - if results == platformString : - results = results.find_next("a")['href'] - - return results - -######## end of getSWTDownloadLinkForPlatform ########## - -def downloadAndExtractZip(url): - zipfileName = url.split('=',1)[1] - unzippedDirName = os.path.join(TEMP_DIR, zipfileName.removesuffix('.zip')) - - page = requests.get(url) - soup = BeautifulSoup(page.content, "html.parser") - zipURL = soup.find("meta").find_next("a")['href'] - - page = requests.get(zipURL) - soup = BeautifulSoup(page.content, "html.parser") - divWithZip = soup.find("div", {"class":"mirror-well"}) - zipURL = divWithZip.find_next("a")['href'] - zipURL = "https://www.eclipse.org/downloads/" + zipURL + if results == platformString: + return results.find_next("a")['href'] + + raise VersionNotFoundError(f"Download link not found for platform: {platformString}") - # navigate the redirect to the actual mirror - page = requests.get(zipURL) - soup = BeautifulSoup(page.content, "html.parser") - zipURL = soup.find('meta', attrs={'http-equiv': 'Refresh'})['content'].split(';')[1].split('=')[1] +def downloadAndExtractZip(url: str, temp_dir: str) -> str: + """Download and extract SWT zip file to temporary directory. - # delete existing content - if os.path.exists(unzippedDirName) and os.path.isdir(unzippedDirName): - shutil.rmtree(unzippedDirName) - response = requests.get(zipURL, stream=True) - z = zipfile.ZipFile(io.BytesIO(response.content)) - z.extractall(unzippedDirName) - subprocess.run(["zip", - "-d", - unzippedDirName + "/swt.jar", - "META-INF/ECLIPSE_.SF", - "META-INF/ECLIPSE_.DSA", - "META-INF/ECLIPSE_.RSA"]) - - return unzippedDirName - -######## end of downloadAndExtractZip ########## - -def installInLocalMavenRepo(unzippedSWTDir, mvnArtifactId, gitCloneRootDir): - swtVersion = unzippedSWTDir.split('-')[1] + Args: + url: URL of the download page + temp_dir: Temporary directory to extract to + + Returns: + str: Path to the extracted directory + + Raises: + SWTUpdateError: If download or extraction fails + """ + try: + zipfileName = url.split('=', 1)[1] + unzippedDirName = os.path.join(temp_dir, zipfileName.removesuffix('.zip')) + + # Get the actual zip file URL + page = requests.get(url) + soup = BeautifulSoup(page.content, "html.parser") + zipURL = soup.find("meta").find_next("a")['href'] + + page = requests.get(zipURL) + soup = BeautifulSoup(page.content, "html.parser") + divWithZip = soup.find("div", {"class": "mirror-well"}) + zipURL = divWithZip.find_next("a")['href'] + zipURL = "https://www.eclipse.org/downloads/" + zipURL + + # Navigate the redirect to the actual mirror + page = requests.get(zipURL) + soup = BeautifulSoup(page.content, "html.parser") + zipURL = soup.find('meta', attrs={'http-equiv': 'Refresh'})['content'].split(';')[1].split('=')[1] + + # Clean up existing content + if os.path.exists(unzippedDirName): + shutil.rmtree(unzippedDirName) + + # Download and extract + response = requests.get(zipURL, stream=True) + z = zipfile.ZipFile(io.BytesIO(response.content)) + z.extractall(unzippedDirName) + + # Remove signature files + for sig_file in SWT_SIGNATURE_FILES: + subprocess.run(["zip", "-d", os.path.join(unzippedDirName, "swt.jar"), sig_file], + capture_output=True) + + return unzippedDirName + except Exception as e: + raise SWTUpdateError(f"Failed to download and extract SWT: {str(e)}") + +def installInLocalMavenRepo(unzippedSWTDir: str, mvnArtifactId: str, gitCloneRootDir: str) -> None: + """Install SWT jar into local Maven repository. + + Args: + unzippedSWTDir: Directory containing extracted SWT jar + mvnArtifactId: Maven artifact ID + gitCloneRootDir: Root directory of git clone + + Raises: + MavenNotFoundError: If Maven is not found in PATH + SWTUpdateError: If installation fails + """ + if shutil.which("mvn") is None: + raise MavenNotFoundError("Maven command not found in PATH") - if shutil.which("mvn") == None : - exitWithError("did not find mvn command in the execute path") + swtVersion = unzippedSWTDir.split('-')[1] + + mavenCommand = [ + "mvn", "install:install-file", + f"-Dfile={os.path.join(unzippedSWTDir, 'swt.jar')}", + "-DgroupId=local.swt", + f"-DartifactId={mvnArtifactId}", + f"-Dversion={swtVersion}", + "-Dpackaging=jar", + f"-Dmaven.repo.local={os.path.join(gitCloneRootDir, 'local-proj-repo')}" + ] + + try: + subprocess.run(mavenCommand, check=True, capture_output=True, text=True) + logger.info(f"Successfully installed {mvnArtifactId} version {swtVersion}") + except subprocess.CalledProcessError as e: + raise SWTUpdateError(f"Failed to install SWT in Maven repo: {e.stderr}") + +def getLocalSWTVersion(mvnArtifactId: str) -> str: + """Get the version of SWT installed in local Maven repository. + + Args: + mvnArtifactId: Maven artifact ID to check - mavenCommand = "mvn install:install-file " \ - + "-Dfile=" + unzippedSWTDir + "/swt.jar " \ - + "-DgroupId=local.swt " \ - + "-DartifactId=" + mvnArtifactId + " " \ - + "-Dversion=" + swtVersion + " " \ - + "-Dpackaging=jar " \ - + "-Dmaven.repo.local=" + gitCloneRootDir + "/local-proj-repo" - subprocess.run(mavenCommand, shell=True) - -######## end of installInLocalMavenRepo ########## - -def getLocalSWTVersion(mvnArtifactId): - localSWTVersion = "" + Returns: + str: Version string if found, empty string otherwise + """ artifactPath = os.path.join(LOCAL_REPO_DIR, "local/swt", mvnArtifactId) if os.path.isdir(artifactPath): - # Look for version directories (they should be numeric) subdirs = [d for d in os.listdir(artifactPath) if os.path.isdir(os.path.join(artifactPath, d))] if subdirs: - localSWTVersion = subdirs[0] # Take the first version directory - print(f"Found local version for {mvnArtifactId}: {localSWTVersion}") - return localSWTVersion - -def updateSWT(mvnArtifactId, downloadPageLabel, gitCloneRootDir, version, forceUpdate): - URL = "https://download.eclipse.org/eclipse/downloads/" - page = requests.get(URL) + version = subdirs[0] + logger.info(f"Found local version for {mvnArtifactId}: {version}") + return version + return "" - soup = BeautifulSoup(page.content, "html.parser") - linkToVersionDownload = "" +def updateSWT(config: SWTConfig, mvnArtifactId: str, downloadPageLabel: str) -> None: + """Update SWT for a specific platform. - localSWTVersion = getLocalSWTVersion(mvnArtifactId) + Args: + config: SWT update configuration + mvnArtifactId: Maven artifact ID + downloadPageLabel: Platform label on download page + + Raises: + VersionNotFoundError: If version not found for download + SWTUpdateError: If update process fails + """ + try: + page = requests.get(ECLIPSE_DOWNLOAD_URL) + soup = BeautifulSoup(page.content, "html.parser") + linkToVersionDownload = "" + + localSWTVersion = getLocalSWTVersion(mvnArtifactId) + + if config.version == "": + anchorElement = soup.find(id="Latest_Release").find_next("a") + linkToVersionDownload = anchorElement['href'] + config.version = anchorElement.text.strip() + logger.info(f"Found download version: {config.version}") + else: + for link in soup.find_all('a', href=True): + if config.version in link.text: + linkToVersionDownload = link['href'] + break + + logger.info(f"Comparing versions - Local: '{localSWTVersion}', Download: '{config.version}'") + if not config.force_update and config.version.strip() == localSWTVersion.strip(): + logger.info(f"Skipping download for {mvnArtifactId} - version {config.version} already installed") + return + + if not linkToVersionDownload: + raise VersionNotFoundError(f"Version {config.version} not found for download") + + downloadsPage = ECLIPSE_DOWNLOAD_URL + linkToVersionDownload + page = requests.get(downloadsPage) + soup = BeautifulSoup(page.content, "html.parser") + + results = getSWTDownloadLinkForPlatform(soup, downloadPageLabel) + unzippedDir = downloadAndExtractZip(downloadsPage + results, config.temp_dir) + installInLocalMavenRepo(unzippedDir, mvnArtifactId, config.git_clone_root) + + except Exception as e: + raise SWTUpdateError(f"Failed to update SWT for {mvnArtifactId}: {str(e)}") + +def main() -> None: + """Main entry point for the script.""" + parser = argparse.ArgumentParser(description="Update SWT dependencies in local Maven repository") + parser.add_argument("-v", "--version", required=False, default="", + help="Specific version to download (default: latest)") + parser.add_argument("-f", "--force", required=False, default=False, nargs='?', const=True, + help="Force update even if versions match") + parser.add_argument("-c", "--cloneroot", required=False, default=os.getcwd(), + help="Root directory of git clone") + + arguments = parser.parse_args() - if version == "" : - anchorElement = soup.find(id="Latest_Release").find_next("a") - linkToVersionDownload = anchorElement['href'] - version = anchorElement.text - print(f"Found download version: {version}") - else: - for link in soup.findAll('a', href=True): - if version in link.text : - linkToVersionDownload = link['href'] - break - - print(f"Comparing versions - Local: '{localSWTVersion}', Download: '{version}'") - if not forceUpdate and version.strip() == localSWTVersion.strip(): - print(f"Skipping download for {mvnArtifactId} - version {version} already installed") - return - - if linkToVersionDownload == "" : - exitWithError("version " + version + " not found for download") - - downloadsPage = URL + linkToVersionDownload - page = requests.get(downloadsPage) - soup = BeautifulSoup(page.content, "html.parser") + config = SWTConfig( + version=arguments.version, + force_update=arguments.force, + git_clone_root=arguments.cloneroot, + temp_dir=tempfile.mkdtemp() + ) - results = getSWTDownloadLinkForPlatform(soup, downloadPageLabel) - unzippedDir = downloadAndExtractZip(downloadsPage + results) - installInLocalMavenRepo(unzippedDir, mvnArtifactId, gitCloneRootDir) - -######## end of updateSWTAndPOM ######################### - -atexit.register(cleanupBeforeExit) - -parser = argparse.ArgumentParser(description = "my parser") -parser.add_argument("-v", "--version", required = False, default = "") -parser.add_argument("-f", "--force", required = False, default = False, nargs='?', const=True) -parser.add_argument("-c", "--cloneroot", required = False, default = os.getcwd()) - -arguments = parser.parse_args() - -# initialize variables from arguments -version = arguments.version -rootdir = arguments.cloneroot -forceUpdate = arguments.force - -# Create temporary directory for downloads -TEMP_DIR = tempfile.mkdtemp() -print(f"Created temporary directory: {TEMP_DIR}") - -# Windows x86 -updateSWT("swtwin32_x86_64", "Windows (x86 64-bit)", rootdir, version, forceUpdate) - -# Windows ARM -updateSWT("swtwin32_aarch64", "Windows (ARM 64-bit)", rootdir, version, forceUpdate) - -# Mac x86 -updateSWT("swtmac_x86_64", "Mac OSX (x86 64-bit)", rootdir, version, forceUpdate) - -# Mac ARM -updateSWT("swtmac_aarch64", "Mac OSX (ARM 64-bit)", rootdir, version, forceUpdate) - -# Linux x86 -updateSWT("swtlinux_x86_64", "Linux (x86 64-bit)", rootdir, version, forceUpdate) - -# Linux ARM -updateSWT("swtlinux_aarch64", "Linux (ARM 64-bit)", rootdir, version, forceUpdate) - -# Clean up temporary directory -if os.path.exists(TEMP_DIR): - shutil.rmtree(TEMP_DIR) - -# Clean up any non-local directories in the local repo -for subdir in os.listdir(LOCAL_REPO_DIR): - if subdir != "local": - shutil.rmtree(os.path.join(LOCAL_REPO_DIR, subdir)) + logger.info(f"Created temporary directory: {config.temp_dir}") + + try: + for artifact_id, platform_label in PLATFORM_CONFIGS.items(): + updateSWT(config, artifact_id, platform_label) + + # Clean up any non-local directories in the local repo + for subdir in os.listdir(LOCAL_REPO_DIR): + if subdir != "local": + shutil.rmtree(os.path.join(LOCAL_REPO_DIR, subdir)) + + except Exception as e: + logger.error(f"Error during SWT update: {str(e)}") + sys.exit(1) + finally: + if config.temp_dir and os.path.exists(config.temp_dir): + shutil.rmtree(config.temp_dir) + +if __name__ == "__main__": + config = None + try: + main() + finally: + cleanupBeforeExit(config) From 5b11a4e1fb44b8a21dd56d9debc9edd76ac0a98e Mon Sep 17 00:00:00 2001 From: ashitsalesforce <71143047+ashitsalesforce@users.noreply.github.com> Date: Mon, 2 Jun 2025 08:07:07 -0700 Subject: [PATCH 2/7] avoid "lazy formatting" warning Fix for Codacy scan warning: "Use lazy % formatting in logging functions (logging-fstring-interpolation)" --- updateSWT.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/updateSWT.py b/updateSWT.py index ec7dd82e..e36e375f 100755 --- a/updateSWT.py +++ b/updateSWT.py @@ -98,7 +98,7 @@ def cleanupBeforeExit(config: Optional[SWTConfig] = None) -> None: config: SWT configuration containing temp directory path """ if config and config.temp_dir and os.path.exists(config.temp_dir): - logger.info(f"Cleaning up temporary directory: {config.temp_dir}") + logger.info("Cleaning up temporary directory: %s", config.temp_dir) shutil.rmtree(config.temp_dir) def getSWTDownloadLinkForPlatform(soup: BeautifulSoup, platformString: str) -> str: @@ -203,7 +203,7 @@ def installInLocalMavenRepo(unzippedSWTDir: str, mvnArtifactId: str, gitCloneRoo try: subprocess.run(mavenCommand, check=True, capture_output=True, text=True) - logger.info(f"Successfully installed {mvnArtifactId} version {swtVersion}") + logger.info("Successfully installed %s version %s", mvnArtifactId, swtVersion) except subprocess.CalledProcessError as e: raise SWTUpdateError(f"Failed to install SWT in Maven repo: {e.stderr}") @@ -222,7 +222,7 @@ def getLocalSWTVersion(mvnArtifactId: str) -> str: if os.path.isdir(os.path.join(artifactPath, d))] if subdirs: version = subdirs[0] - logger.info(f"Found local version for {mvnArtifactId}: {version}") + logger.info("Found local version for %s: %s", mvnArtifactId, version) return version return "" @@ -249,16 +249,16 @@ def updateSWT(config: SWTConfig, mvnArtifactId: str, downloadPageLabel: str) -> anchorElement = soup.find(id="Latest_Release").find_next("a") linkToVersionDownload = anchorElement['href'] config.version = anchorElement.text.strip() - logger.info(f"Found download version: {config.version}") + logger.info("Found download version: %s", config.version) else: for link in soup.find_all('a', href=True): if config.version in link.text: linkToVersionDownload = link['href'] break - logger.info(f"Comparing versions - Local: '{localSWTVersion}', Download: '{config.version}'") + logger.info("Comparing versions - Local: '%s', Download: '%s'", localSWTVersion, config.version) if not config.force_update and config.version.strip() == localSWTVersion.strip(): - logger.info(f"Skipping download for {mvnArtifactId} - version {config.version} already installed") + logger.info("Skipping download for %s - version %s already installed", mvnArtifactId, config.version) return if not linkToVersionDownload: @@ -294,7 +294,7 @@ def main() -> None: temp_dir=tempfile.mkdtemp() ) - logger.info(f"Created temporary directory: {config.temp_dir}") + logger.info("Created temporary directory: %s", config.temp_dir) try: for artifact_id, platform_label in PLATFORM_CONFIGS.items(): @@ -306,7 +306,7 @@ def main() -> None: shutil.rmtree(os.path.join(LOCAL_REPO_DIR, subdir)) except Exception as e: - logger.error(f"Error during SWT update: {str(e)}") + logger.error("Error during SWT update: %s", str(e)) sys.exit(1) finally: if config.temp_dir and os.path.exists(config.temp_dir): From f2645a230bf9b2e2ea112aa293ff362569cc46c0 Mon Sep 17 00:00:00 2001 From: ashitsalesforce <71143047+ashitsalesforce@users.noreply.github.com> Date: Mon, 2 Jun 2025 08:45:44 -0700 Subject: [PATCH 3/7] avoid "lazy formatting" warning Fix for Codacy scan warning: "Use lazy % formatting in logging functions (logging-fstring-interpolation)" --- updateSWT.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/updateSWT.py b/updateSWT.py index e36e375f..c302d497 100755 --- a/updateSWT.py +++ b/updateSWT.py @@ -172,7 +172,7 @@ def downloadAndExtractZip(url: str, temp_dir: str) -> str: return unzippedDirName except Exception as e: - raise SWTUpdateError(f"Failed to download and extract SWT: {str(e)}") + raise SWTUpdateError("Failed to download and extract SWT: %s" % str(e)) def installInLocalMavenRepo(unzippedSWTDir: str, mvnArtifactId: str, gitCloneRootDir: str) -> None: """Install SWT jar into local Maven repository. @@ -205,7 +205,7 @@ def installInLocalMavenRepo(unzippedSWTDir: str, mvnArtifactId: str, gitCloneRoo subprocess.run(mavenCommand, check=True, capture_output=True, text=True) logger.info("Successfully installed %s version %s", mvnArtifactId, swtVersion) except subprocess.CalledProcessError as e: - raise SWTUpdateError(f"Failed to install SWT in Maven repo: {e.stderr}") + raise SWTUpdateError("Failed to install SWT in Maven repo: %s" % e.stderr) def getLocalSWTVersion(mvnArtifactId: str) -> str: """Get the version of SWT installed in local Maven repository. @@ -262,7 +262,7 @@ def updateSWT(config: SWTConfig, mvnArtifactId: str, downloadPageLabel: str) -> return if not linkToVersionDownload: - raise VersionNotFoundError(f"Version {config.version} not found for download") + raise VersionNotFoundError("Version %s not found for download" % config.version) downloadsPage = ECLIPSE_DOWNLOAD_URL + linkToVersionDownload page = requests.get(downloadsPage) @@ -273,7 +273,7 @@ def updateSWT(config: SWTConfig, mvnArtifactId: str, downloadPageLabel: str) -> installInLocalMavenRepo(unzippedDir, mvnArtifactId, config.git_clone_root) except Exception as e: - raise SWTUpdateError(f"Failed to update SWT for {mvnArtifactId}: {str(e)}") + raise SWTUpdateError("Failed to update SWT for %s: %s" % (mvnArtifactId, str(e))) def main() -> None: """Main entry point for the script.""" From 2a96f37b760cdc651a2786e4453fab84c296597f Mon Sep 17 00:00:00 2001 From: ashitsalesforce <71143047+ashitsalesforce@users.noreply.github.com> Date: Mon, 2 Jun 2025 08:54:16 -0700 Subject: [PATCH 4/7] two blank lines after the SWTConfig class definition to follow PEP 8 guidelines. two blank lines after the SWTConfig class definition to follow PEP 8 guidelines. --- updateSWT.py | 1 + 1 file changed, 1 insertion(+) diff --git a/updateSWT.py b/updateSWT.py index c302d497..f8a29622 100755 --- a/updateSWT.py +++ b/updateSWT.py @@ -68,6 +68,7 @@ class SWTConfig: git_clone_root: str temp_dir: Optional[str] = None + class SWTUpdateError(Exception): """Base exception for SWT update errors.""" pass From 537e2cfc1fc8882d526bc95a98b0fddedc49fdac Mon Sep 17 00:00:00 2001 From: ashitsalesforce <71143047+ashitsalesforce@users.noreply.github.com> Date: Mon, 2 Jun 2025 09:43:10 -0700 Subject: [PATCH 5/7] two blank lines after two blank lines after class definition to follow PEP 8 guidelines. two blank lines after two blank lines after class definition to follow PEP 8 guidelines. --- updateSWT.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/updateSWT.py b/updateSWT.py index f8a29622..704f3558 100755 --- a/updateSWT.py +++ b/updateSWT.py @@ -309,10 +309,12 @@ def main() -> None: except Exception as e: logger.error("Error during SWT update: %s", str(e)) sys.exit(1) + finally: if config.temp_dir and os.path.exists(config.temp_dir): shutil.rmtree(config.temp_dir) + if __name__ == "__main__": config = None try: From 899fdf0c695d49c44affbcac1130d168aa753ea1 Mon Sep 17 00:00:00 2001 From: ashitsalesforce <71143047+ashitsalesforce@users.noreply.github.com> Date: Mon, 2 Jun 2025 10:01:07 -0700 Subject: [PATCH 6/7] explicit check=True parameter in all subprocess.run calls explicit check=True parameter in all subprocess.run calls --- updateSWT.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/updateSWT.py b/updateSWT.py index 704f3558..12d20dc3 100755 --- a/updateSWT.py +++ b/updateSWT.py @@ -166,10 +166,16 @@ def downloadAndExtractZip(url: str, temp_dir: str) -> str: z = zipfile.ZipFile(io.BytesIO(response.content)) z.extractall(unzippedDirName) - # Remove signature files + # Remove signature files if they exist + swt_jar = os.path.join(unzippedDirName, "swt.jar") for sig_file in SWT_SIGNATURE_FILES: - subprocess.run(["zip", "-d", os.path.join(unzippedDirName, "swt.jar"), sig_file], - capture_output=True) + try: + subprocess.run(["zip", "-d", swt_jar, sig_file], + capture_output=True, check=True) + except subprocess.CalledProcessError as e: + # Ignore errors if file doesn't exist in the jar + if e.returncode != 12: # zip returns 12 when file not found + raise return unzippedDirName except Exception as e: From 6975205d51a63d9a05f831bcd452f13b44dea28a Mon Sep 17 00:00:00 2001 From: ashitsalesforce <71143047+ashitsalesforce@users.noreply.github.com> Date: Mon, 2 Jun 2025 12:28:12 -0700 Subject: [PATCH 7/7] fix warning about partial exec path fix the warning about starting process with partial exec path --- updateSWT.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/updateSWT.py b/updateSWT.py index 12d20dc3..f6ed0932 100755 --- a/updateSWT.py +++ b/updateSWT.py @@ -170,7 +170,7 @@ def downloadAndExtractZip(url: str, temp_dir: str) -> str: swt_jar = os.path.join(unzippedDirName, "swt.jar") for sig_file in SWT_SIGNATURE_FILES: try: - subprocess.run(["zip", "-d", swt_jar, sig_file], + subprocess.run(["/usr/bin/zip", "-d", swt_jar, sig_file], capture_output=True, check=True) except subprocess.CalledProcessError as e: # Ignore errors if file doesn't exist in the jar