|
| 1 | +import toml |
| 2 | +import sys |
| 3 | +import re |
| 4 | +import subprocess |
| 5 | + |
| 6 | + |
| 7 | +def get_pip_list(): |
| 8 | + result = subprocess.run(["pip", "list"], capture_output=True, text=True) |
| 9 | + return result.stdout |
| 10 | + |
| 11 | + |
| 12 | +def parse_pip_list(pip_list): |
| 13 | + package_versions = {} |
| 14 | + for line in pip_list.strip().split("\n")[2:]: # Skip headers |
| 15 | + match = re.match(r"(\S+)\s+(\S+)", line) |
| 16 | + if match: |
| 17 | + package_versions[match.group(1).lower()] = match.group(2) |
| 18 | + return package_versions |
| 19 | + |
| 20 | + |
| 21 | +def update_pyproject_toml(pyproject_path, package_versions): |
| 22 | + with open(pyproject_path, "r") as f: |
| 23 | + lines = f.readlines() |
| 24 | + |
| 25 | + in_dependencies = False |
| 26 | + updated_lines = [] |
| 27 | + for line in lines: |
| 28 | + stripped = line.strip() |
| 29 | + |
| 30 | + if stripped.startswith("dependencies = ["): |
| 31 | + in_dependencies = True |
| 32 | + updated_lines.append(line) |
| 33 | + continue |
| 34 | + |
| 35 | + if in_dependencies: |
| 36 | + if stripped == "]": |
| 37 | + in_dependencies = False |
| 38 | + updated_lines.append(line) |
| 39 | + continue |
| 40 | + |
| 41 | + match = re.match(r'\s*"([^"]+)"(.*)', stripped) |
| 42 | + if match: |
| 43 | + package_name = match.group(1) |
| 44 | + constraints = match.group(2) |
| 45 | + lower_package = package_name.lower() |
| 46 | + if lower_package in package_versions and "==" not in constraints and "<=" not in constraints and ">=" not in constraints and "@" not in constraints: |
| 47 | + updated_line = f' "{package_name}=={package_versions[lower_package]}",\n' |
| 48 | + print(f"Updated {package_name} to version {package_versions[lower_package]}") |
| 49 | + else: |
| 50 | + updated_line = line |
| 51 | + updated_lines.append(updated_line) |
| 52 | + else: |
| 53 | + updated_lines.append(line) |
| 54 | + else: |
| 55 | + updated_lines.append(line) |
| 56 | + |
| 57 | + with open(pyproject_path, "w") as f: |
| 58 | + f.writelines(updated_lines) |
| 59 | + print("pyproject.toml dependencies section has been updated.") |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + pyproject_file = "pyproject.toml" |
| 64 | + pip_list_content = get_pip_list() |
| 65 | + package_versions = parse_pip_list(pip_list_content) |
| 66 | + update_pyproject_toml(pyproject_file, package_versions) |
0 commit comments