Last active
June 13, 2024 15:19
-
-
Save shyuep/7d7a570d62ea931ac1e1a175b4a49af1 to your computer and use it in GitHub Desktop.
Requirements.txt manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import subprocess | |
import sys | |
import argparse | |
import warnings | |
import re | |
from importlib.metadata import version, PackageNotFoundError | |
from packaging.version import parse | |
def update_req(args): | |
reqfn = args.req_file | |
req = [] | |
changes = 0 | |
with open(reqfn, "rt") as f: | |
for line in f: | |
line = line.strip() | |
prev_changes = changes | |
if not line.startswith("#"): | |
toks1 = re.split(";", line) | |
toks2 = re.split("[=><]+", toks1[0].strip()) | |
if len(toks2) == 2: | |
pkg, ver = toks2 | |
try: | |
latest = version(pkg) | |
except PackageNotFoundError: | |
latest = None | |
if latest is None: | |
print( | |
"Unable to determine environment version for %s. Using existing version." | |
% (pkg) | |
) | |
latest = ver | |
if parse(latest) > parse(ver): | |
print("%s: %s -> %s" % (pkg, ver, latest)) | |
changes += 1 | |
if len(toks1) == 2: | |
req.append("%s==%s; %s" % (pkg, latest, toks1[-1].strip())) | |
else: | |
req.append("%s==%s" % (pkg, latest)) | |
if changes == prev_changes: | |
req.append(line) | |
if changes > 0: | |
r = args.inplace or input("Write changes to %s (y/[n])? " % reqfn) == "y" | |
if r: | |
with open(reqfn, "wt") as f: | |
f.write("\n".join(req)) | |
else: | |
print("No changes needed!") | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser( | |
description="reqman is a manager for requirements.txt files", | |
epilog="Author: Shyue Ping Ong", | |
) | |
subparsers = parser.add_subparsers() | |
parser_update = subparsers.add_parser( | |
"update", | |
help="Update requirements.txt based on current environment (detected using pkg_resources).", | |
) | |
parser_update.add_argument( | |
"-i", | |
"--inplace", | |
dest="inplace", | |
action="store_true", | |
help="If set, the file will automatically be updated.", | |
) | |
parser_update.add_argument( | |
"-r", | |
"--req_file", | |
dest="req_file", | |
default="requirements.txt", | |
help="Input requirements file. Defaults to requirements.txt in current directory.", | |
) | |
parser_update.set_defaults(func=update_req) | |
args = parser.parse_args() | |
try: | |
getattr(args, "func") | |
except AttributeError: | |
parser.print_help() | |
sys.exit(0) | |
args.func(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment