2024-07-03 19:58:18 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# To run this script you must install docker and piddeptree python package
|
|
|
|
#
|
|
|
|
|
|
|
|
import os
|
2024-09-27 10:19:39 +00:00
|
|
|
import subprocess
|
2024-07-03 19:58:18 +00:00
|
|
|
import sys
|
|
|
|
|
2024-07-03 20:52:54 +00:00
|
|
|
|
2024-09-30 18:28:06 +00:00
|
|
|
def build_docker_deps(image_name: str, imagedir: str) -> None:
|
|
|
|
print("Fetch the newest manifest for", image_name)
|
|
|
|
pip_cmd = (
|
|
|
|
"pip install pipdeptree 2>/dev/null 1>/dev/null && pipdeptree --freeze "
|
|
|
|
"--warn silence --exclude pipdeptree"
|
|
|
|
)
|
2024-09-30 21:43:36 +00:00
|
|
|
# /=/!d - remove dependencies without pin
|
|
|
|
# ubuntu - ignore system packages
|
|
|
|
# \s - remove spaces
|
|
|
|
sed = r"sed '/==/!d; /==.*+ubuntu/d; s/\s//g'"
|
|
|
|
cmd = rf"""docker run --rm --entrypoint "/bin/bash" {image_name} -c "{pip_cmd} | {sed} | sort -u" > {imagedir}/requirements.txt"""
|
2024-09-30 18:28:06 +00:00
|
|
|
print("Running the command:", cmd)
|
2024-07-03 19:58:18 +00:00
|
|
|
subprocess.check_call(cmd, shell=True)
|
|
|
|
|
2024-07-03 20:52:54 +00:00
|
|
|
|
2024-07-03 19:58:18 +00:00
|
|
|
def check_docker_file_install_with_pip(filepath):
|
|
|
|
image_name = None
|
2024-09-30 18:28:06 +00:00
|
|
|
with open(filepath, "r", encoding="utf-8") as f:
|
2024-07-03 19:58:18 +00:00
|
|
|
for line in f:
|
2024-07-03 20:52:54 +00:00
|
|
|
if "docker build" in line:
|
|
|
|
arr = line.split(" ")
|
2024-07-03 19:58:18 +00:00
|
|
|
if len(arr) > 4:
|
|
|
|
image_name = arr[4]
|
2024-07-03 20:52:54 +00:00
|
|
|
if "pip3 install" in line or "pip install" in line:
|
2024-07-03 19:58:18 +00:00
|
|
|
return image_name, True
|
|
|
|
return image_name, False
|
|
|
|
|
2024-07-03 20:52:54 +00:00
|
|
|
|
2024-09-30 18:28:06 +00:00
|
|
|
def process_affected_images(images_dir: str) -> None:
|
2024-07-03 19:58:18 +00:00
|
|
|
for root, _dirs, files in os.walk(images_dir):
|
|
|
|
for f in files:
|
|
|
|
if f == "Dockerfile":
|
|
|
|
docker_file_path = os.path.join(root, f)
|
|
|
|
print("Checking image on path", docker_file_path)
|
2024-07-03 20:52:54 +00:00
|
|
|
image_name, has_pip = check_docker_file_install_with_pip(
|
|
|
|
docker_file_path
|
|
|
|
)
|
2024-07-03 19:58:18 +00:00
|
|
|
if has_pip:
|
|
|
|
print("Find pip in", image_name)
|
|
|
|
try:
|
|
|
|
build_docker_deps(image_name, root)
|
|
|
|
except Exception as ex:
|
|
|
|
print(ex)
|
|
|
|
else:
|
|
|
|
print("Pip not found in", docker_file_path)
|
|
|
|
|
|
|
|
|
|
|
|
process_affected_images(sys.argv[1])
|