Skip to content

Commit

Permalink
feat: add get_requirement_versions function
Browse files Browse the repository at this point in the history
  • Loading branch information
Stephen-RA-King committed Aug 28, 2022
1 parent cec7a48 commit 32c2154
Showing 1 changed file with 106 additions and 1 deletion.
107 changes: 106 additions & 1 deletion src/piptools_sync/piptools_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import os
import time
from pathlib import Path
from typing import Any, Union
from typing import Any, List, Union

# Third party modules
import pkg_resources # type:ignore
Expand Down Expand Up @@ -66,13 +66,17 @@ def _utility_find_file_path(partial_path: str) -> Union[Path, int]:
"""

logger.debug("starting **** _utility_find_file_path ****")
logger.debug(f"attempting to find: {partial_path}")
result_list = sorted(Path(ROOT_DIR).glob(partial_path))
logger.debug(f"result_list: {result_list}")
if len(result_list) == 0:
logger.debug(f"Error - no files found: {result_list}")
return 0
elif len(result_list) > 1:
logger.debug(f"Error - more than one file found: {result_list}")
return 1
else:
logger.debug(f"file found: {result_list}")
return result_list[0]


Expand Down Expand Up @@ -338,3 +342,104 @@ def update_yaml(yaml_file: Path, repo: str, version: str) -> None:
yaml_contents["repos"][found_index]["rev"] = version
with open(yaml_file, mode="wt", encoding="utf-8") as file:
yaml.dump(yaml_contents, file)
logger.debug(f"{repo} updated to version {version}")


def find_requirements_file() -> Any:
"""Find the first piptools generated file in the pip requirements tree.
Given the root requirements file find and verify the final layered
requirements file is a pip-tools generated file.
Returns
result : Path
The pathlib.Path object to the derived requirement file.
"""

logger.debug("starting **** find_requirements_file function ****")
logger.debug(f"root requirement: {ROOT_REQUIREMENT}")

def next_file(req_file: Path) -> Any:
with open(req_file) as f:
lines = f.read()
if "autogenerated by pip-compile" in lines:
return req_file, 1
with open(req_file) as f:
lines = f.readlines() # type:ignore
for line in lines:
if "-r " in line:
_, next_req = line.split(" ")
next_req = next_req.strip()
next_req = _utility_find_file_path(next_req) # type:ignore
if next_req == 0:
raise FileNotFoundError("No Files found")
if next_req == 1:
logger.debug(f"found {next_req}")
raise NameError("Ambiguous result - more than one file found")
return next_req, 0
else:
raise FileNotFoundError(
"Requirement file generated by piptools " "Not found..."
)

final = 0
result = ROOT_REQUIREMENT
while final == 0:
result, final = next_file(result)
if final == 1:
filename = "".join([result.stem, result.suffix])
logger.debug(f"Found requirement file: {filename}")
return result


def get_installed_version(package: str) -> Union[str, None]:
"""Return installed package version given the package name.
This is the package version installed by pip and not the version in the
requirements file or the pre-commit-config.yaml file
Parameters
package : str
The name of the installed package.
Returns
installed_version : str
version of the package installed by pip.
"""

logger.debug("starting **** get_installed_version function ****")
try:
installed_version = pkg_resources.get_distribution(package).version
logger.debug(f"package version found: {installed_version}")
return installed_version
except pkg_resources.DistributionNotFound:
logger.info("package version Not found")
return None


def get_requirement_versions(req_file: Path, req_list: list) -> dict:
"""Get the repo version from the requirements file.
Parameters
req_file : Path
pathlib.Path object for the derived requirements file.
req_list : list
A list comprising packages that need versions.
Returns
req_version_list : dict
A Dictionary comprising key: package name, Value: the version
e.g. {'click': '8.1.3'}
"""

logger.debug("starting **** get_requirement_versions function ****")
req_version_list = {}
with open(req_file) as f:
lines = f.readlines()
for line in lines:
if "==" in line:
package, version = line.split("==")
version = _utility_remove_vee(version)
if package in req_list:
req_version_list[package.strip()] = version.strip()
return req_version_list

0 comments on commit 32c2154

Please sign in to comment.