import os import json import mimetypes import base64 import argparse def read_file(file_path, binary=False): mode = 'rb' if binary else 'r' with open(file_path, mode) as file: return file.read() def process_directory(directory_path, output_file): # Initialize the dictionary to hold file data data = {'requestPolicies': {}, 'routes': []} max_size = 4096 # 4KB in bytes # Iterate over all files in the directory for filename in os.listdir(directory_path): file_path = os.path.join(directory_path, filename) if os.path.isfile(file_path): content_type, _ = mimetypes.guess_type(filename) if not content_type: content_type = 'application/octet-stream' # Default to binary data if unknown type # Check if the file is binary is_binary = content_type.startswith('image/') or content_type == 'application/octet-stream' file_content = read_file(file_path, binary=is_binary) # Encode binary files in base64 if is_binary: file_content = base64.b64encode(file_content).decode('utf-8') section = { 'path': f"/{filename}", 'methods': ['GET'], 'backend': { 'type': 'STOCK_RESPONSE_BACKEND', 'status': '200', 'body': file_content, 'headers': [{'name': 'Content-Type', 'value': content_type}] } } # Check the size of the body content if len(section['backend']['body']) > max_size: raise ValueError(f"The content of the file '{filename}' exceeds the maximum size of 4KB.") data['routes'].append(section) # Write the dictionary to a JSON file with open(output_file, 'w') as json_file: json.dump(data, json_file, indent=4) # Inform the user where the JSON file is saved print(f"The JSON file has been saved at: {output_file}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Process a directory of files into a JSON representation.") parser.add_argument('directory', type=str, help="The path to the directory containing the files") parser.add_argument('output', type=str, help="The path to the output JSON file") args = parser.parse_args() process_directory(args.directory, args.output)