Skip to content

Commit

Permalink
Add docstrings and harden the code a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
droideck committed Jan 23, 2024
1 parent 1076d72 commit 8f9d39c
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions rpm/bundle-rust-npm.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,24 @@

# handle a control-c gracefully
def signal_handler(signal, frame):
"""Exits the script gracefully on SIGINT."""
print('\n\nExiting...')
sys.exit(0)


def backup_specfile(spec_file: str):
time_now = time.strftime("%Y%m%d_%H%M%S")
log.info(f"Backing up file {spec_file} to {spec_file}.{time_now}")
shutil.copy2(spec_file, f"{spec_file}.{time_now}")
"""Creates a backup of the specfile with a timestamp."""
try:
time_now = time.strftime("%Y%m%d_%H%M%S")
log.info(f"Backing up file {spec_file} to {spec_file}.{time_now}")
shutil.copy2(spec_file, f"{spec_file}.{time_now}")
except IOError as e:
log.error(f"Failed to backup specfile: {e}")
sys.exit(1)


def run_cmd(cmd):
"""Executes a command and returns its output."""
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
args = ' '.join(ensure_list_str(result.args))
stdout = ensure_str(result.stdout)
Expand All @@ -74,12 +81,14 @@ def run_cmd(cmd):


def process_rust_crates(output: str) -> Dict[str, Tuple[str, str]]:
"""Processes the output from cargo-license to extract crate information."""
crates = json.loads(output)
return {crate['name']: (enclose_if_contains_or(crate['license']), crate['version'])
for crate in crates if crate['name'] not in IGNORED_RUST_PACKAGES}


def process_npm_packages(output: str) -> Dict[str, Tuple[str, str]]:
"""Processes the output from license-checker to extract npm package information."""
packages = json.loads(output)
processed_packages = {}
for package, data in packages.items():
Expand All @@ -92,6 +101,7 @@ def process_npm_packages(output: str) -> Dict[str, Tuple[str, str]]:


def process_npm_license(license_data) -> str:
"""Formats the license data for npm packages."""
npm_license = license_data if isinstance(license_data, str) else ' OR '.join(license_data)
return enclose_if_contains_or(npm_license)

Expand All @@ -102,6 +112,7 @@ def enclose_if_contains_or(license_str: str) -> str:


def build_provides_lines(rust_crates: Dict[str, Tuple[str, str]], npm_packages: Dict[str, Tuple[str, str]]) -> list[str]:
"""Builds lines to be added to the spec file for provided packages."""
provides_lines = [f"Provides: bundled(crate({crate})) = {version.replace('-', '_')}\n"
for crate, (_, version) in rust_crates.items()]
provides_lines += [f"Provides: bundled(npm({package})) = {version.replace('-', '_')}\n"
Expand All @@ -110,11 +121,15 @@ def build_provides_lines(rust_crates: Dict[str, Tuple[str, str]], npm_packages:


def create_license_line(rust_crates: Dict[str, Tuple[str, str]], npm_packages: Dict[str, Tuple[str, str]]) -> str:
"""Creates a line for the spec file with combined license information."""
licenses = {license for _, (license, _) in {**rust_crates, **npm_packages}.items() if license}
return " AND ".join(sorted(licenses))


def replace_license(spec_file: str, license_string: str):
"""Replaces the license section in the spec file with a new license string and
adds a comment for manual review and adjustment.
"""
result = []
with open(spec_file, "r") as file:
contents = file.readlines()
Expand All @@ -131,6 +146,9 @@ def replace_license(spec_file: str, license_string: str):


def clean_specfile(spec_file: str) -> bool:
"""Cleans up the spec file by removing the previous bundled package information.
Returns a boolean indicating if the clean-up was successful.
"""
result = []
remove_lines = False
cleaned = False
Expand All @@ -157,6 +175,9 @@ def clean_specfile(spec_file: str) -> bool:


def write_provides_bundled(provides_lines: List[str], spec_file: str, cleaned: bool):
"""Writes bundled package information to the spec file.
Includes generated 'Provides' lines and marks the section for easy future modification.
"""
# Find a line index where 'Provides' ends
with open(spec_file, "r") as file:
spec_file_lines = file.readlines()
Expand Down Expand Up @@ -201,10 +222,10 @@ def write_provides_bundled(provides_lines: List[str], spec_file: str, cleaned: b

if not os.path.isdir(args.cargo_path):
log.error(f"Path {args.cargo_path} does not exist or is not a directory")
exit(1)
sys.exit(1)
if not os.path.isdir(args.npm_path):
log.error(f"Path {args.npm_path} does not exist or is not a directory")
exit(1)
sys.exit(1)

cleaned = clean_specfile(args.spec_file)

Expand All @@ -213,7 +234,7 @@ def write_provides_bundled(provides_lines: List[str], spec_file: str, cleaned: b

if rust_output is None or npm_output is None:
log.error("Failed to process dependencies. Ensure cargo-license and license-checker are installed and accessible.")
exit(1)
sys.exit(1)

rust_crates = process_rust_crates(rust_output)
npm_packages = process_npm_packages(npm_output)
Expand Down

0 comments on commit 8f9d39c

Please sign in to comment.