#!/usr/bin/env python import base64 import json import os import argparse def encode_file_to_base64(file_path, json_path): ''' Reads a file, encodes its content in Base64, and writes it to a JSON file under ['files'][filename]. ''' if not os.path.isfile(file_path): print(f'Error: File "{file_path}" not found.') return with open(file_path, 'rb') as f: encoded_content = base64.b64encode(f.read()).decode('utf-8') filename = os.path.basename(file_path) json_data = {} # Read existing JSON if the file exists if os.path.exists(json_path): with open(json_path, 'r', encoding='utf-8') as json_file: try: json_data = json.load(json_file) except json.JSONDecodeError: print('Warning: JSON file is empty or invalid. Creating a new structure.') # Ensure 'files' key exists if 'files' not in json_data: json_data['files'] = {} # Add Base64 content under filename json_data['files'][filename] = encoded_content # Write updated data back to JSON file with open(json_path, 'w', encoding='utf-8') as json_file: json.dump(json_data, json_file, indent=4) print(f'Successfully encoded "{filename}" and saved to "{json_path}".') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Encode a file to Base64 and store it in a JSON file.') parser.add_argument('file_path', help='Path to the file to encode.') parser.add_argument('json_path', help='Path to the JSON output file.') args = parser.parse_args() encode_file_to_base64(args.file_path, args.json_path)