|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# To run this script you must install docker and piddeptree python package |
| 3 | +# |
| 4 | + |
| 5 | +import subprocess |
| 6 | +import os |
| 7 | +import sys |
| 8 | + |
| 9 | + |
| 10 | +def build_docker_deps(image_name, imagedir): |
| 11 | + cmd = f"""docker run --entrypoint "/bin/bash" {image_name} -c "pip install pipdeptree 2>/dev/null 1>/dev/null && pipdeptree --freeze --warn silence | sed 's/ \+//g' | sort | uniq" > {imagedir}/requirements.txt""" |
| 12 | + subprocess.check_call(cmd, shell=True) |
| 13 | + |
| 14 | + |
| 15 | +def check_docker_file_install_with_pip(filepath): |
| 16 | + image_name = None |
| 17 | + with open(filepath, "r") as f: |
| 18 | + for line in f: |
| 19 | + if "docker build" in line: |
| 20 | + arr = line.split(" ") |
| 21 | + if len(arr) > 4: |
| 22 | + image_name = arr[4] |
| 23 | + if "pip3 install" in line or "pip install" in line: |
| 24 | + return image_name, True |
| 25 | + return image_name, False |
| 26 | + |
| 27 | + |
| 28 | +def process_affected_images(images_dir): |
| 29 | + for root, _dirs, files in os.walk(images_dir): |
| 30 | + for f in files: |
| 31 | + if f == "Dockerfile": |
| 32 | + docker_file_path = os.path.join(root, f) |
| 33 | + print("Checking image on path", docker_file_path) |
| 34 | + image_name, has_pip = check_docker_file_install_with_pip( |
| 35 | + docker_file_path |
| 36 | + ) |
| 37 | + if has_pip: |
| 38 | + print("Find pip in", image_name) |
| 39 | + try: |
| 40 | + build_docker_deps(image_name, root) |
| 41 | + except Exception as ex: |
| 42 | + print(ex) |
| 43 | + else: |
| 44 | + print("Pip not found in", docker_file_path) |
| 45 | + |
| 46 | + |
| 47 | +process_affected_images(sys.argv[1]) |
0 commit comments