py-requirements-guesser/main.py

140 lines
5.0 KiB
Python
Raw Normal View History

2021-06-24 07:36:28 +02:00
import re
import os
import argparse
import subprocess
from datetime import datetime
from xml.etree.ElementTree import fromstring as parse_xml
import requests
from utils import load_packages_from_requirements#, user_response_multi, user_response_yes_no
# TODO : Get all imports from source files
# TODO : Exclude imports where version is specified in requirements.txt
2021-06-24 08:33:54 +02:00
2021-06-24 07:36:28 +02:00
# TODO : Propose choice between date of first import or Added in requirements
2021-06-24 08:33:54 +02:00
# TODO : Other choices : When project was created, last commit (That wasnt on md file), 75 percentile of time between commits
2021-06-24 07:36:28 +02:00
# TODO : Pin also the dependencies tree of the packages Ex : Torch package might install numpy, etc
# TODO : Poetry mode ?
2021-06-24 08:33:54 +02:00
# - There might be a version in the history (1st Commit : matplotlib==1.0.1 -> 2nd commit : matplotlib==1.1.2 -> 3rd commit : )
2021-06-24 07:36:28 +02:00
# TODO : import name doesn't always match the pypi name
2021-06-24 08:33:54 +02:00
# A potential solution : https://github.com/thebjorn/pydeps/blob/master/pydeps/package_names.py
# from pipreqs.pipreqs import get_all_imports, get_pkg_names
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
# TODO : Add a mode where file/folder creation/last update is used if no git repo ?
2021-06-24 07:36:28 +02:00
EXTRACT_DATE_REGEX = re.compile(r'Date:\s*(\d+)')
2021-06-24 07:36:28 +02:00
LETTER_REGEX = re.compile(r'[a-zA-Z]')
parser = argparse.ArgumentParser("Python Requirements Version Guesser")
parser.add_argument('--git_repo_path', type=str, default=None, required=False)
def get_pypi_history(package_name, ignore_release_candidat=True):
2021-06-24 08:33:54 +02:00
"""
Retrieve version release dates via Pypi JSON api
"""
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
resp = requests.get(f"https://pypi.org/pypi/{package_name}/json").json()
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
versions = []
for version, release_info_per_os in resp['releases'].items():
# Just taking the first platform upload date for now..
# Is it really different for other platforms ? Need to validate
# TODO : Give appropriate version based on os and python Versions resp['info']['requires_dist'] # ['require_python']
if len(release_info_per_os) == 0:
continue
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
if ignore_release_candidat and LETTER_REGEX.search(version):
continue
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
release_info = release_info_per_os[0]
release_date = datetime.strptime(release_info['upload_time'].split("T")[0], '%Y-%m-%d')
versions.append((version, release_date))
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
# FIXME : Do we really need to sort ? Versions should already be sorted
return sorted(versions, key=lambda x:x[1], reverse=True)
2021-06-24 07:36:28 +02:00
def find_version_at_date(available_versions, date):
2021-06-24 08:33:54 +02:00
last_version = available_versions[0][0]
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
# FIXME : Do binary search
for candidate_version, candidate_date in available_versions:
if date >= candidate_date:
return candidate_version
else:
last_version = candidate_version
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
# Date is older than available versions... Fallback on the oldest available version
return last_version
2021-06-24 07:36:28 +02:00
def get_date_when_package_added(package_name, via_requirements=False):
2021-06-24 08:33:54 +02:00
if not via_requirements:
search_pattern = f"^import {package_name}$|^from {package_name}"
filename = ""
else:
search_pattern = f"{package_name}$"
filename = "requirements.txt"
# We grep for 'date' | '+ search pattern' so that we keep only commits that insert lines (+)
cmd = f"git log -G '{search_pattern}' --date unix -p {filename} | grep -i 'date\\|\\+.*{package_name}'"
try:
blame_out = subprocess.check_output(cmd, shell=True).decode().strip()
except:
blame_out = ""
if len(blame_out) == 0:
#return []
raise Exception(f"[ERROR] couldn't find package '{package_name}' via git-log")
# Remove commit that are not directly followed by '+ import' (We grepped for this in cmd)
# This is ugly.. TODO: figure out a better way in the grep command
dates = []
got_plus = False
for line in blame_out.split('\n')[::-1]:
if line[0] == "+":
got_plus = True
elif got_plus:
got_plus = False
matches = EXTRACT_DATE_REGEX.search(line)
if matches:
dates.append(datetime.fromtimestamp(int(matches.group(1))))
else:
raise Exception("[ERROR] while parsing git-log")
# Get first date where the line was added
return sorted(dates, reverse=True)[0]
2021-06-24 07:36:28 +02:00
if __name__ == "__main__":
2021-06-24 08:33:54 +02:00
packages_in_requirements = load_packages_from_requirements('requirements.txt')
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
packages = []
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
for package_name, version in packages_in_requirements.items():
if version is None:
date_added = get_date_when_package_added(package_name, via_requirements=True)
available_versions = get_pypi_history(package_name, ignore_release_candidat=True)
version = find_version_at_date(available_versions, date_added)
print(f"{package_name} - {date_added}")
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
else:
print(f"{package_name} version is specified in requirements.txt ({version})")
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
packages.append((package_name, version))
2021-06-24 07:36:28 +02:00
2021-06-24 08:33:54 +02:00
# TODO : Write to requirements.txt
for package_name, version in sorted(packages, key=lambda x:x[0]):
print(f"{package_name}=={version}")
2021-06-24 07:36:28 +02:00