|
26 | 26 | import json |
27 | 27 | import re |
28 | 28 | import uuid |
| 29 | +import zipfile |
29 | 30 | from operator import attrgetter |
30 | 31 | from pathlib import Path |
31 | 32 |
|
32 | 33 | from django.apps import apps |
| 34 | +from django.core.files.base import ContentFile |
33 | 35 | from django.core.serializers.json import DjangoJSONEncoder |
34 | 36 | from django.forms.models import model_to_dict |
35 | 37 | from django.template import Context |
@@ -1138,3 +1140,43 @@ def to_ort_package_list_yml(project): |
1138 | 1140 | "attribution": to_attribution, |
1139 | 1141 | "ort-package-list": to_ort_package_list_yml, |
1140 | 1142 | } |
| 1143 | + |
| 1144 | + |
| 1145 | +def make_zip_from_files(files): |
| 1146 | + """Return an in-memory zipfile given a list of (filename, file_path) pairs.""" |
| 1147 | + zip_buffer = io.BytesIO() |
| 1148 | + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file: |
| 1149 | + for filename, file_path in files: |
| 1150 | + with open(file_path, "rb") as f: |
| 1151 | + zip_file.writestr(filename, f.read()) |
| 1152 | + zip_buffer.seek(0) |
| 1153 | + return zip_buffer |
| 1154 | + |
| 1155 | + |
| 1156 | +def to_all_formats(project): |
| 1157 | + """Generate all output formats for a project and return a Django File-like zip.""" |
| 1158 | + files = [] |
| 1159 | + for output_function in FORMAT_TO_FUNCTION_MAPPING.values(): |
| 1160 | + output_file = output_function(project) |
| 1161 | + filename = safe_filename(f"{project.name}_{output_file.name}") |
| 1162 | + files.append((filename, output_file)) |
| 1163 | + |
| 1164 | + zip_buffer = make_zip_from_files(files) |
| 1165 | + |
| 1166 | + # Wrap it into a Django File-like object |
| 1167 | + zip_file = ContentFile(zip_buffer.getvalue()) |
| 1168 | + zip_file.name = safe_filename(f"{project.name}_outputs.zip") |
| 1169 | + |
| 1170 | + return zip_file |
| 1171 | + |
| 1172 | + |
| 1173 | +def to_all_outputs(project): |
| 1174 | + """Return a Django File-like zip containing all existing project's output/ files.""" |
| 1175 | + files = [(path.name, path) for path in project.output_path.glob("*")] |
| 1176 | + zip_buffer = make_zip_from_files(files) |
| 1177 | + |
| 1178 | + # Wrap it into a Django File-like object |
| 1179 | + zip_file = ContentFile(zip_buffer.getvalue()) |
| 1180 | + zip_file.name = safe_filename(f"{project.name}_outputs.zip") |
| 1181 | + |
| 1182 | + return zip_file |
0 commit comments